Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / prettier-eslint / 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.7";
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 _a;
2520     var nullLogger = {
2521         logEvent: ts.noop,
2522         logErrEvent: ts.noop,
2523         logPerfEvent: ts.noop,
2524         logInfoEvent: ts.noop,
2525         logStartCommand: ts.noop,
2526         logStopCommand: ts.noop,
2527         logStartUpdateProgram: ts.noop,
2528         logStopUpdateProgram: ts.noop,
2529         logStartUpdateGraph: ts.noop,
2530         logStopUpdateGraph: ts.noop,
2531         logStartResolveModule: ts.noop,
2532         logStopResolveModule: ts.noop,
2533         logStartParseSourceFile: ts.noop,
2534         logStopParseSourceFile: ts.noop,
2535         logStartReadFile: ts.noop,
2536         logStopReadFile: ts.noop,
2537         logStartBindFile: ts.noop,
2538         logStopBindFile: ts.noop,
2539         logStartScheduledOperation: ts.noop,
2540         logStopScheduledOperation: ts.noop,
2541     };
2542     // Load optional module to enable Event Tracing for Windows
2543     // See https://github.com/microsoft/typescript-etw for more information
2544     var etwModule;
2545     try {
2546         var etwModulePath = (_a = process.env.TS_ETW_MODULE_PATH) !== null && _a !== void 0 ? _a : "./node_modules/@microsoft/typescript-etw";
2547         // require() will throw an exception if the module is not found
2548         // It may also return undefined if not installed properly
2549         etwModule = require(etwModulePath);
2550     }
2551     catch (e) {
2552         etwModule = undefined;
2553     }
2554     /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
2555     ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
2556 })(ts || (ts = {}));
2557 /* @internal */
2558 var ts;
2559 (function (ts) {
2560     // https://semver.org/#spec-item-2
2561     // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
2562     // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
2563     // > version, and Z is the patch version. Each element MUST increase numerically.
2564     //
2565     // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
2566     // value of `0`.
2567     var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2568     // https://semver.org/#spec-item-9
2569     // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
2570     // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
2571     // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
2572     // > MUST NOT include leading zeroes.
2573     var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
2574     // https://semver.org/#spec-item-10
2575     // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
2576     // > identifiers immediately following the patch or pre-release version. Identifiers MUST
2577     // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
2578     var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
2579     // https://semver.org/#spec-item-9
2580     // > Numeric identifiers MUST NOT include leading zeroes.
2581     var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
2582     /**
2583      * Describes a precise semantic version number, https://semver.org
2584      */
2585     var Version = /** @class */ (function () {
2586         function Version(major, minor, patch, prerelease, build) {
2587             if (minor === void 0) { minor = 0; }
2588             if (patch === void 0) { patch = 0; }
2589             if (prerelease === void 0) { prerelease = ""; }
2590             if (build === void 0) { build = ""; }
2591             if (typeof major === "string") {
2592                 var result = ts.Debug.checkDefined(tryParseComponents(major), "Invalid version");
2593                 (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
2594             }
2595             ts.Debug.assert(major >= 0, "Invalid argument: major");
2596             ts.Debug.assert(minor >= 0, "Invalid argument: minor");
2597             ts.Debug.assert(patch >= 0, "Invalid argument: patch");
2598             ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
2599             ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
2600             this.major = major;
2601             this.minor = minor;
2602             this.patch = patch;
2603             this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
2604             this.build = build ? build.split(".") : ts.emptyArray;
2605         }
2606         Version.tryParse = function (text) {
2607             var result = tryParseComponents(text);
2608             if (!result)
2609                 return undefined;
2610             var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
2611             return new Version(major, minor, patch, prerelease, build);
2612         };
2613         Version.prototype.compareTo = function (other) {
2614             // https://semver.org/#spec-item-11
2615             // > Precedence is determined by the first difference when comparing each of these
2616             // > identifiers from left to right as follows: Major, minor, and patch versions are
2617             // > always compared numerically.
2618             //
2619             // https://semver.org/#spec-item-11
2620             // > Precedence for two pre-release versions with the same major, minor, and patch version
2621             // > MUST be determined by comparing each dot separated identifier from left to right until
2622             // > a difference is found [...]
2623             //
2624             // https://semver.org/#spec-item-11
2625             // > Build metadata does not figure into precedence
2626             if (this === other)
2627                 return 0 /* EqualTo */;
2628             if (other === undefined)
2629                 return 1 /* GreaterThan */;
2630             return ts.compareValues(this.major, other.major)
2631                 || ts.compareValues(this.minor, other.minor)
2632                 || ts.compareValues(this.patch, other.patch)
2633                 || comparePrerelaseIdentifiers(this.prerelease, other.prerelease);
2634         };
2635         Version.prototype.increment = function (field) {
2636             switch (field) {
2637                 case "major": return new Version(this.major + 1, 0, 0);
2638                 case "minor": return new Version(this.major, this.minor + 1, 0);
2639                 case "patch": return new Version(this.major, this.minor, this.patch + 1);
2640                 default: return ts.Debug.assertNever(field);
2641             }
2642         };
2643         Version.prototype.toString = function () {
2644             var result = this.major + "." + this.minor + "." + this.patch;
2645             if (ts.some(this.prerelease))
2646                 result += "-" + this.prerelease.join(".");
2647             if (ts.some(this.build))
2648                 result += "+" + this.build.join(".");
2649             return result;
2650         };
2651         Version.zero = new Version(0, 0, 0);
2652         return Version;
2653     }());
2654     ts.Version = Version;
2655     function tryParseComponents(text) {
2656         var match = versionRegExp.exec(text);
2657         if (!match)
2658             return undefined;
2659         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;
2660         if (prerelease && !prereleaseRegExp.test(prerelease))
2661             return undefined;
2662         if (build && !buildRegExp.test(build))
2663             return undefined;
2664         return {
2665             major: parseInt(major, 10),
2666             minor: parseInt(minor, 10),
2667             patch: parseInt(patch, 10),
2668             prerelease: prerelease,
2669             build: build
2670         };
2671     }
2672     function comparePrerelaseIdentifiers(left, right) {
2673         // https://semver.org/#spec-item-11
2674         // > When major, minor, and patch are equal, a pre-release version has lower precedence
2675         // > than a normal version.
2676         if (left === right)
2677             return 0 /* EqualTo */;
2678         if (left.length === 0)
2679             return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
2680         if (right.length === 0)
2681             return -1 /* LessThan */;
2682         // https://semver.org/#spec-item-11
2683         // > Precedence for two pre-release versions with the same major, minor, and patch version
2684         // > MUST be determined by comparing each dot separated identifier from left to right until
2685         // > a difference is found [...]
2686         var length = Math.min(left.length, right.length);
2687         for (var i = 0; i < length; i++) {
2688             var leftIdentifier = left[i];
2689             var rightIdentifier = right[i];
2690             if (leftIdentifier === rightIdentifier)
2691                 continue;
2692             var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
2693             var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
2694             if (leftIsNumeric || rightIsNumeric) {
2695                 // https://semver.org/#spec-item-11
2696                 // > Numeric identifiers always have lower precedence than non-numeric identifiers.
2697                 if (leftIsNumeric !== rightIsNumeric)
2698                     return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
2699                 // https://semver.org/#spec-item-11
2700                 // > identifiers consisting of only digits are compared numerically
2701                 var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
2702                 if (result)
2703                     return result;
2704             }
2705             else {
2706                 // https://semver.org/#spec-item-11
2707                 // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
2708                 var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
2709                 if (result)
2710                     return result;
2711             }
2712         }
2713         // https://semver.org/#spec-item-11
2714         // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
2715         // > of the preceding identifiers are equal.
2716         return ts.compareValues(left.length, right.length);
2717     }
2718     /**
2719      * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
2720      */
2721     var VersionRange = /** @class */ (function () {
2722         function VersionRange(spec) {
2723             this._alternatives = spec ? ts.Debug.checkDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
2724         }
2725         VersionRange.tryParse = function (text) {
2726             var sets = parseRange(text);
2727             if (sets) {
2728                 var range = new VersionRange("");
2729                 range._alternatives = sets;
2730                 return range;
2731             }
2732             return undefined;
2733         };
2734         VersionRange.prototype.test = function (version) {
2735             if (typeof version === "string")
2736                 version = new Version(version);
2737             return testDisjunction(version, this._alternatives);
2738         };
2739         VersionRange.prototype.toString = function () {
2740             return formatDisjunction(this._alternatives);
2741         };
2742         return VersionRange;
2743     }());
2744     ts.VersionRange = VersionRange;
2745     // https://github.com/npm/node-semver#range-grammar
2746     //
2747     // range-set    ::= range ( logical-or range ) *
2748     // range        ::= hyphen | simple ( ' ' simple ) * | ''
2749     // logical-or   ::= ( ' ' ) * '||' ( ' ' ) *
2750     var logicalOrRegExp = /\s*\|\|\s*/g;
2751     var whitespaceRegExp = /\s+/g;
2752     // https://github.com/npm/node-semver#range-grammar
2753     //
2754     // partial      ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
2755     // xr           ::= 'x' | 'X' | '*' | nr
2756     // nr           ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
2757     // qualifier    ::= ( '-' pre )? ( '+' build )?
2758     // pre          ::= parts
2759     // build        ::= parts
2760     // parts        ::= part ( '.' part ) *
2761     // part         ::= nr | [-0-9A-Za-z]+
2762     var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2763     // https://github.com/npm/node-semver#range-grammar
2764     //
2765     // hyphen       ::= partial ' - ' partial
2766     var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
2767     // https://github.com/npm/node-semver#range-grammar
2768     //
2769     // simple       ::= primitive | partial | tilde | caret
2770     // primitive    ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
2771     // tilde        ::= '~' partial
2772     // caret        ::= '^' partial
2773     var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
2774     function parseRange(text) {
2775         var alternatives = [];
2776         for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
2777             var range = _a[_i];
2778             if (!range)
2779                 continue;
2780             var comparators = [];
2781             var match = hyphenRegExp.exec(range);
2782             if (match) {
2783                 if (!parseHyphen(match[1], match[2], comparators))
2784                     return undefined;
2785             }
2786             else {
2787                 for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
2788                     var simple = _c[_b];
2789                     var match_1 = rangeRegExp.exec(simple);
2790                     if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
2791                         return undefined;
2792                 }
2793             }
2794             alternatives.push(comparators);
2795         }
2796         return alternatives;
2797     }
2798     function parsePartial(text) {
2799         var match = partialRegExp.exec(text);
2800         if (!match)
2801             return undefined;
2802         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];
2803         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);
2804         return { version: version, major: major, minor: minor, patch: patch };
2805     }
2806     function parseHyphen(left, right, comparators) {
2807         var leftResult = parsePartial(left);
2808         if (!leftResult)
2809             return false;
2810         var rightResult = parsePartial(right);
2811         if (!rightResult)
2812             return false;
2813         if (!isWildcard(leftResult.major)) {
2814             comparators.push(createComparator(">=", leftResult.version));
2815         }
2816         if (!isWildcard(rightResult.major)) {
2817             comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
2818                 isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
2819                     createComparator("<=", rightResult.version));
2820         }
2821         return true;
2822     }
2823     function parseComparator(operator, text, comparators) {
2824         var result = parsePartial(text);
2825         if (!result)
2826             return false;
2827         var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
2828         if (!isWildcard(major)) {
2829             switch (operator) {
2830                 case "~":
2831                     comparators.push(createComparator(">=", version));
2832                     comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
2833                         "minor")));
2834                     break;
2835                 case "^":
2836                     comparators.push(createComparator(">=", version));
2837                     comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
2838                         version.minor > 0 || isWildcard(patch) ? "minor" :
2839                             "patch")));
2840                     break;
2841                 case "<":
2842                 case ">=":
2843                     comparators.push(createComparator(operator, version));
2844                     break;
2845                 case "<=":
2846                 case ">":
2847                     comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
2848                         isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
2849                             createComparator(operator, version));
2850                     break;
2851                 case "=":
2852                 case undefined:
2853                     if (isWildcard(minor) || isWildcard(patch)) {
2854                         comparators.push(createComparator(">=", version));
2855                         comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
2856                     }
2857                     else {
2858                         comparators.push(createComparator("=", version));
2859                     }
2860                     break;
2861                 default:
2862                     // unrecognized
2863                     return false;
2864             }
2865         }
2866         else if (operator === "<" || operator === ">") {
2867             comparators.push(createComparator("<", Version.zero));
2868         }
2869         return true;
2870     }
2871     function isWildcard(part) {
2872         return part === "*" || part === "x" || part === "X";
2873     }
2874     function createComparator(operator, operand) {
2875         return { operator: operator, operand: operand };
2876     }
2877     function testDisjunction(version, alternatives) {
2878         // an empty disjunction is treated as "*" (all versions)
2879         if (alternatives.length === 0)
2880             return true;
2881         for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
2882             var alternative = alternatives_1[_i];
2883             if (testAlternative(version, alternative))
2884                 return true;
2885         }
2886         return false;
2887     }
2888     function testAlternative(version, comparators) {
2889         for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
2890             var comparator = comparators_1[_i];
2891             if (!testComparator(version, comparator.operator, comparator.operand))
2892                 return false;
2893         }
2894         return true;
2895     }
2896     function testComparator(version, operator, operand) {
2897         var cmp = version.compareTo(operand);
2898         switch (operator) {
2899             case "<": return cmp < 0;
2900             case "<=": return cmp <= 0;
2901             case ">": return cmp > 0;
2902             case ">=": return cmp >= 0;
2903             case "=": return cmp === 0;
2904             default: return ts.Debug.assertNever(operator);
2905         }
2906     }
2907     function formatDisjunction(alternatives) {
2908         return ts.map(alternatives, formatAlternative).join(" || ") || "*";
2909     }
2910     function formatAlternative(comparators) {
2911         return ts.map(comparators, formatComparator).join(" ");
2912     }
2913     function formatComparator(comparator) {
2914         return "" + comparator.operator + comparator.operand;
2915     }
2916 })(ts || (ts = {}));
2917 var ts;
2918 (function (ts) {
2919     // token > SyntaxKind.Identifier => token is a keyword
2920     // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
2921     var SyntaxKind;
2922     (function (SyntaxKind) {
2923         SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
2924         SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
2925         SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
2926         SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
2927         SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
2928         SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
2929         // We detect and preserve #! on the first line
2930         SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
2931         // We detect and provide better error recovery when we encounter a git merge marker.  This
2932         // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
2933         SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
2934         // Literals
2935         SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
2936         SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
2937         SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
2938         SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
2939         SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
2940         SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
2941         SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
2942         // Pseudo-literals
2943         SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
2944         SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
2945         SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
2946         // Punctuation
2947         SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
2948         SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
2949         SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
2950         SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
2951         SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
2952         SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
2953         SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
2954         SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
2955         SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
2956         SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
2957         SyntaxKind[SyntaxKind["QuestionDotToken"] = 28] = "QuestionDotToken";
2958         SyntaxKind[SyntaxKind["LessThanToken"] = 29] = "LessThanToken";
2959         SyntaxKind[SyntaxKind["LessThanSlashToken"] = 30] = "LessThanSlashToken";
2960         SyntaxKind[SyntaxKind["GreaterThanToken"] = 31] = "GreaterThanToken";
2961         SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 32] = "LessThanEqualsToken";
2962         SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken";
2963         SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 34] = "EqualsEqualsToken";
2964         SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken";
2965         SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken";
2966         SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken";
2967         SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken";
2968         SyntaxKind[SyntaxKind["PlusToken"] = 39] = "PlusToken";
2969         SyntaxKind[SyntaxKind["MinusToken"] = 40] = "MinusToken";
2970         SyntaxKind[SyntaxKind["AsteriskToken"] = 41] = "AsteriskToken";
2971         SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken";
2972         SyntaxKind[SyntaxKind["SlashToken"] = 43] = "SlashToken";
2973         SyntaxKind[SyntaxKind["PercentToken"] = 44] = "PercentToken";
2974         SyntaxKind[SyntaxKind["PlusPlusToken"] = 45] = "PlusPlusToken";
2975         SyntaxKind[SyntaxKind["MinusMinusToken"] = 46] = "MinusMinusToken";
2976         SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 47] = "LessThanLessThanToken";
2977         SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken";
2978         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken";
2979         SyntaxKind[SyntaxKind["AmpersandToken"] = 50] = "AmpersandToken";
2980         SyntaxKind[SyntaxKind["BarToken"] = 51] = "BarToken";
2981         SyntaxKind[SyntaxKind["CaretToken"] = 52] = "CaretToken";
2982         SyntaxKind[SyntaxKind["ExclamationToken"] = 53] = "ExclamationToken";
2983         SyntaxKind[SyntaxKind["TildeToken"] = 54] = "TildeToken";
2984         SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken";
2985         SyntaxKind[SyntaxKind["BarBarToken"] = 56] = "BarBarToken";
2986         SyntaxKind[SyntaxKind["QuestionToken"] = 57] = "QuestionToken";
2987         SyntaxKind[SyntaxKind["ColonToken"] = 58] = "ColonToken";
2988         SyntaxKind[SyntaxKind["AtToken"] = 59] = "AtToken";
2989         SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
2990         /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
2991         SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
2992         // Assignments
2993         SyntaxKind[SyntaxKind["EqualsToken"] = 62] = "EqualsToken";
2994         SyntaxKind[SyntaxKind["PlusEqualsToken"] = 63] = "PlusEqualsToken";
2995         SyntaxKind[SyntaxKind["MinusEqualsToken"] = 64] = "MinusEqualsToken";
2996         SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 65] = "AsteriskEqualsToken";
2997         SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 66] = "AsteriskAsteriskEqualsToken";
2998         SyntaxKind[SyntaxKind["SlashEqualsToken"] = 67] = "SlashEqualsToken";
2999         SyntaxKind[SyntaxKind["PercentEqualsToken"] = 68] = "PercentEqualsToken";
3000         SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 69] = "LessThanLessThanEqualsToken";
3001         SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 70] = "GreaterThanGreaterThanEqualsToken";
3002         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanGreaterThanEqualsToken";
3003         SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 72] = "AmpersandEqualsToken";
3004         SyntaxKind[SyntaxKind["BarEqualsToken"] = 73] = "BarEqualsToken";
3005         SyntaxKind[SyntaxKind["CaretEqualsToken"] = 74] = "CaretEqualsToken";
3006         // Identifiers and PrivateIdentifiers
3007         SyntaxKind[SyntaxKind["Identifier"] = 75] = "Identifier";
3008         SyntaxKind[SyntaxKind["PrivateIdentifier"] = 76] = "PrivateIdentifier";
3009         // Reserved words
3010         SyntaxKind[SyntaxKind["BreakKeyword"] = 77] = "BreakKeyword";
3011         SyntaxKind[SyntaxKind["CaseKeyword"] = 78] = "CaseKeyword";
3012         SyntaxKind[SyntaxKind["CatchKeyword"] = 79] = "CatchKeyword";
3013         SyntaxKind[SyntaxKind["ClassKeyword"] = 80] = "ClassKeyword";
3014         SyntaxKind[SyntaxKind["ConstKeyword"] = 81] = "ConstKeyword";
3015         SyntaxKind[SyntaxKind["ContinueKeyword"] = 82] = "ContinueKeyword";
3016         SyntaxKind[SyntaxKind["DebuggerKeyword"] = 83] = "DebuggerKeyword";
3017         SyntaxKind[SyntaxKind["DefaultKeyword"] = 84] = "DefaultKeyword";
3018         SyntaxKind[SyntaxKind["DeleteKeyword"] = 85] = "DeleteKeyword";
3019         SyntaxKind[SyntaxKind["DoKeyword"] = 86] = "DoKeyword";
3020         SyntaxKind[SyntaxKind["ElseKeyword"] = 87] = "ElseKeyword";
3021         SyntaxKind[SyntaxKind["EnumKeyword"] = 88] = "EnumKeyword";
3022         SyntaxKind[SyntaxKind["ExportKeyword"] = 89] = "ExportKeyword";
3023         SyntaxKind[SyntaxKind["ExtendsKeyword"] = 90] = "ExtendsKeyword";
3024         SyntaxKind[SyntaxKind["FalseKeyword"] = 91] = "FalseKeyword";
3025         SyntaxKind[SyntaxKind["FinallyKeyword"] = 92] = "FinallyKeyword";
3026         SyntaxKind[SyntaxKind["ForKeyword"] = 93] = "ForKeyword";
3027         SyntaxKind[SyntaxKind["FunctionKeyword"] = 94] = "FunctionKeyword";
3028         SyntaxKind[SyntaxKind["IfKeyword"] = 95] = "IfKeyword";
3029         SyntaxKind[SyntaxKind["ImportKeyword"] = 96] = "ImportKeyword";
3030         SyntaxKind[SyntaxKind["InKeyword"] = 97] = "InKeyword";
3031         SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 98] = "InstanceOfKeyword";
3032         SyntaxKind[SyntaxKind["NewKeyword"] = 99] = "NewKeyword";
3033         SyntaxKind[SyntaxKind["NullKeyword"] = 100] = "NullKeyword";
3034         SyntaxKind[SyntaxKind["ReturnKeyword"] = 101] = "ReturnKeyword";
3035         SyntaxKind[SyntaxKind["SuperKeyword"] = 102] = "SuperKeyword";
3036         SyntaxKind[SyntaxKind["SwitchKeyword"] = 103] = "SwitchKeyword";
3037         SyntaxKind[SyntaxKind["ThisKeyword"] = 104] = "ThisKeyword";
3038         SyntaxKind[SyntaxKind["ThrowKeyword"] = 105] = "ThrowKeyword";
3039         SyntaxKind[SyntaxKind["TrueKeyword"] = 106] = "TrueKeyword";
3040         SyntaxKind[SyntaxKind["TryKeyword"] = 107] = "TryKeyword";
3041         SyntaxKind[SyntaxKind["TypeOfKeyword"] = 108] = "TypeOfKeyword";
3042         SyntaxKind[SyntaxKind["VarKeyword"] = 109] = "VarKeyword";
3043         SyntaxKind[SyntaxKind["VoidKeyword"] = 110] = "VoidKeyword";
3044         SyntaxKind[SyntaxKind["WhileKeyword"] = 111] = "WhileKeyword";
3045         SyntaxKind[SyntaxKind["WithKeyword"] = 112] = "WithKeyword";
3046         // Strict mode reserved words
3047         SyntaxKind[SyntaxKind["ImplementsKeyword"] = 113] = "ImplementsKeyword";
3048         SyntaxKind[SyntaxKind["InterfaceKeyword"] = 114] = "InterfaceKeyword";
3049         SyntaxKind[SyntaxKind["LetKeyword"] = 115] = "LetKeyword";
3050         SyntaxKind[SyntaxKind["PackageKeyword"] = 116] = "PackageKeyword";
3051         SyntaxKind[SyntaxKind["PrivateKeyword"] = 117] = "PrivateKeyword";
3052         SyntaxKind[SyntaxKind["ProtectedKeyword"] = 118] = "ProtectedKeyword";
3053         SyntaxKind[SyntaxKind["PublicKeyword"] = 119] = "PublicKeyword";
3054         SyntaxKind[SyntaxKind["StaticKeyword"] = 120] = "StaticKeyword";
3055         SyntaxKind[SyntaxKind["YieldKeyword"] = 121] = "YieldKeyword";
3056         // Contextual keywords
3057         SyntaxKind[SyntaxKind["AbstractKeyword"] = 122] = "AbstractKeyword";
3058         SyntaxKind[SyntaxKind["AsKeyword"] = 123] = "AsKeyword";
3059         SyntaxKind[SyntaxKind["AssertsKeyword"] = 124] = "AssertsKeyword";
3060         SyntaxKind[SyntaxKind["AnyKeyword"] = 125] = "AnyKeyword";
3061         SyntaxKind[SyntaxKind["AsyncKeyword"] = 126] = "AsyncKeyword";
3062         SyntaxKind[SyntaxKind["AwaitKeyword"] = 127] = "AwaitKeyword";
3063         SyntaxKind[SyntaxKind["BooleanKeyword"] = 128] = "BooleanKeyword";
3064         SyntaxKind[SyntaxKind["ConstructorKeyword"] = 129] = "ConstructorKeyword";
3065         SyntaxKind[SyntaxKind["DeclareKeyword"] = 130] = "DeclareKeyword";
3066         SyntaxKind[SyntaxKind["GetKeyword"] = 131] = "GetKeyword";
3067         SyntaxKind[SyntaxKind["InferKeyword"] = 132] = "InferKeyword";
3068         SyntaxKind[SyntaxKind["IsKeyword"] = 133] = "IsKeyword";
3069         SyntaxKind[SyntaxKind["KeyOfKeyword"] = 134] = "KeyOfKeyword";
3070         SyntaxKind[SyntaxKind["ModuleKeyword"] = 135] = "ModuleKeyword";
3071         SyntaxKind[SyntaxKind["NamespaceKeyword"] = 136] = "NamespaceKeyword";
3072         SyntaxKind[SyntaxKind["NeverKeyword"] = 137] = "NeverKeyword";
3073         SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 138] = "ReadonlyKeyword";
3074         SyntaxKind[SyntaxKind["RequireKeyword"] = 139] = "RequireKeyword";
3075         SyntaxKind[SyntaxKind["NumberKeyword"] = 140] = "NumberKeyword";
3076         SyntaxKind[SyntaxKind["ObjectKeyword"] = 141] = "ObjectKeyword";
3077         SyntaxKind[SyntaxKind["SetKeyword"] = 142] = "SetKeyword";
3078         SyntaxKind[SyntaxKind["StringKeyword"] = 143] = "StringKeyword";
3079         SyntaxKind[SyntaxKind["SymbolKeyword"] = 144] = "SymbolKeyword";
3080         SyntaxKind[SyntaxKind["TypeKeyword"] = 145] = "TypeKeyword";
3081         SyntaxKind[SyntaxKind["UndefinedKeyword"] = 146] = "UndefinedKeyword";
3082         SyntaxKind[SyntaxKind["UniqueKeyword"] = 147] = "UniqueKeyword";
3083         SyntaxKind[SyntaxKind["UnknownKeyword"] = 148] = "UnknownKeyword";
3084         SyntaxKind[SyntaxKind["FromKeyword"] = 149] = "FromKeyword";
3085         SyntaxKind[SyntaxKind["GlobalKeyword"] = 150] = "GlobalKeyword";
3086         SyntaxKind[SyntaxKind["BigIntKeyword"] = 151] = "BigIntKeyword";
3087         SyntaxKind[SyntaxKind["OfKeyword"] = 152] = "OfKeyword";
3088         // Parse tree nodes
3089         // Names
3090         SyntaxKind[SyntaxKind["QualifiedName"] = 153] = "QualifiedName";
3091         SyntaxKind[SyntaxKind["ComputedPropertyName"] = 154] = "ComputedPropertyName";
3092         // Signature elements
3093         SyntaxKind[SyntaxKind["TypeParameter"] = 155] = "TypeParameter";
3094         SyntaxKind[SyntaxKind["Parameter"] = 156] = "Parameter";
3095         SyntaxKind[SyntaxKind["Decorator"] = 157] = "Decorator";
3096         // TypeMember
3097         SyntaxKind[SyntaxKind["PropertySignature"] = 158] = "PropertySignature";
3098         SyntaxKind[SyntaxKind["PropertyDeclaration"] = 159] = "PropertyDeclaration";
3099         SyntaxKind[SyntaxKind["MethodSignature"] = 160] = "MethodSignature";
3100         SyntaxKind[SyntaxKind["MethodDeclaration"] = 161] = "MethodDeclaration";
3101         SyntaxKind[SyntaxKind["Constructor"] = 162] = "Constructor";
3102         SyntaxKind[SyntaxKind["GetAccessor"] = 163] = "GetAccessor";
3103         SyntaxKind[SyntaxKind["SetAccessor"] = 164] = "SetAccessor";
3104         SyntaxKind[SyntaxKind["CallSignature"] = 165] = "CallSignature";
3105         SyntaxKind[SyntaxKind["ConstructSignature"] = 166] = "ConstructSignature";
3106         SyntaxKind[SyntaxKind["IndexSignature"] = 167] = "IndexSignature";
3107         // Type
3108         SyntaxKind[SyntaxKind["TypePredicate"] = 168] = "TypePredicate";
3109         SyntaxKind[SyntaxKind["TypeReference"] = 169] = "TypeReference";
3110         SyntaxKind[SyntaxKind["FunctionType"] = 170] = "FunctionType";
3111         SyntaxKind[SyntaxKind["ConstructorType"] = 171] = "ConstructorType";
3112         SyntaxKind[SyntaxKind["TypeQuery"] = 172] = "TypeQuery";
3113         SyntaxKind[SyntaxKind["TypeLiteral"] = 173] = "TypeLiteral";
3114         SyntaxKind[SyntaxKind["ArrayType"] = 174] = "ArrayType";
3115         SyntaxKind[SyntaxKind["TupleType"] = 175] = "TupleType";
3116         SyntaxKind[SyntaxKind["OptionalType"] = 176] = "OptionalType";
3117         SyntaxKind[SyntaxKind["RestType"] = 177] = "RestType";
3118         SyntaxKind[SyntaxKind["UnionType"] = 178] = "UnionType";
3119         SyntaxKind[SyntaxKind["IntersectionType"] = 179] = "IntersectionType";
3120         SyntaxKind[SyntaxKind["ConditionalType"] = 180] = "ConditionalType";
3121         SyntaxKind[SyntaxKind["InferType"] = 181] = "InferType";
3122         SyntaxKind[SyntaxKind["ParenthesizedType"] = 182] = "ParenthesizedType";
3123         SyntaxKind[SyntaxKind["ThisType"] = 183] = "ThisType";
3124         SyntaxKind[SyntaxKind["TypeOperator"] = 184] = "TypeOperator";
3125         SyntaxKind[SyntaxKind["IndexedAccessType"] = 185] = "IndexedAccessType";
3126         SyntaxKind[SyntaxKind["MappedType"] = 186] = "MappedType";
3127         SyntaxKind[SyntaxKind["LiteralType"] = 187] = "LiteralType";
3128         SyntaxKind[SyntaxKind["ImportType"] = 188] = "ImportType";
3129         // Binding patterns
3130         SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 189] = "ObjectBindingPattern";
3131         SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 190] = "ArrayBindingPattern";
3132         SyntaxKind[SyntaxKind["BindingElement"] = 191] = "BindingElement";
3133         // Expression
3134         SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 192] = "ArrayLiteralExpression";
3135         SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 193] = "ObjectLiteralExpression";
3136         SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 194] = "PropertyAccessExpression";
3137         SyntaxKind[SyntaxKind["ElementAccessExpression"] = 195] = "ElementAccessExpression";
3138         SyntaxKind[SyntaxKind["CallExpression"] = 196] = "CallExpression";
3139         SyntaxKind[SyntaxKind["NewExpression"] = 197] = "NewExpression";
3140         SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 198] = "TaggedTemplateExpression";
3141         SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 199] = "TypeAssertionExpression";
3142         SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 200] = "ParenthesizedExpression";
3143         SyntaxKind[SyntaxKind["FunctionExpression"] = 201] = "FunctionExpression";
3144         SyntaxKind[SyntaxKind["ArrowFunction"] = 202] = "ArrowFunction";
3145         SyntaxKind[SyntaxKind["DeleteExpression"] = 203] = "DeleteExpression";
3146         SyntaxKind[SyntaxKind["TypeOfExpression"] = 204] = "TypeOfExpression";
3147         SyntaxKind[SyntaxKind["VoidExpression"] = 205] = "VoidExpression";
3148         SyntaxKind[SyntaxKind["AwaitExpression"] = 206] = "AwaitExpression";
3149         SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 207] = "PrefixUnaryExpression";
3150         SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 208] = "PostfixUnaryExpression";
3151         SyntaxKind[SyntaxKind["BinaryExpression"] = 209] = "BinaryExpression";
3152         SyntaxKind[SyntaxKind["ConditionalExpression"] = 210] = "ConditionalExpression";
3153         SyntaxKind[SyntaxKind["TemplateExpression"] = 211] = "TemplateExpression";
3154         SyntaxKind[SyntaxKind["YieldExpression"] = 212] = "YieldExpression";
3155         SyntaxKind[SyntaxKind["SpreadElement"] = 213] = "SpreadElement";
3156         SyntaxKind[SyntaxKind["ClassExpression"] = 214] = "ClassExpression";
3157         SyntaxKind[SyntaxKind["OmittedExpression"] = 215] = "OmittedExpression";
3158         SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 216] = "ExpressionWithTypeArguments";
3159         SyntaxKind[SyntaxKind["AsExpression"] = 217] = "AsExpression";
3160         SyntaxKind[SyntaxKind["NonNullExpression"] = 218] = "NonNullExpression";
3161         SyntaxKind[SyntaxKind["MetaProperty"] = 219] = "MetaProperty";
3162         SyntaxKind[SyntaxKind["SyntheticExpression"] = 220] = "SyntheticExpression";
3163         // Misc
3164         SyntaxKind[SyntaxKind["TemplateSpan"] = 221] = "TemplateSpan";
3165         SyntaxKind[SyntaxKind["SemicolonClassElement"] = 222] = "SemicolonClassElement";
3166         // Element
3167         SyntaxKind[SyntaxKind["Block"] = 223] = "Block";
3168         SyntaxKind[SyntaxKind["EmptyStatement"] = 224] = "EmptyStatement";
3169         SyntaxKind[SyntaxKind["VariableStatement"] = 225] = "VariableStatement";
3170         SyntaxKind[SyntaxKind["ExpressionStatement"] = 226] = "ExpressionStatement";
3171         SyntaxKind[SyntaxKind["IfStatement"] = 227] = "IfStatement";
3172         SyntaxKind[SyntaxKind["DoStatement"] = 228] = "DoStatement";
3173         SyntaxKind[SyntaxKind["WhileStatement"] = 229] = "WhileStatement";
3174         SyntaxKind[SyntaxKind["ForStatement"] = 230] = "ForStatement";
3175         SyntaxKind[SyntaxKind["ForInStatement"] = 231] = "ForInStatement";
3176         SyntaxKind[SyntaxKind["ForOfStatement"] = 232] = "ForOfStatement";
3177         SyntaxKind[SyntaxKind["ContinueStatement"] = 233] = "ContinueStatement";
3178         SyntaxKind[SyntaxKind["BreakStatement"] = 234] = "BreakStatement";
3179         SyntaxKind[SyntaxKind["ReturnStatement"] = 235] = "ReturnStatement";
3180         SyntaxKind[SyntaxKind["WithStatement"] = 236] = "WithStatement";
3181         SyntaxKind[SyntaxKind["SwitchStatement"] = 237] = "SwitchStatement";
3182         SyntaxKind[SyntaxKind["LabeledStatement"] = 238] = "LabeledStatement";
3183         SyntaxKind[SyntaxKind["ThrowStatement"] = 239] = "ThrowStatement";
3184         SyntaxKind[SyntaxKind["TryStatement"] = 240] = "TryStatement";
3185         SyntaxKind[SyntaxKind["DebuggerStatement"] = 241] = "DebuggerStatement";
3186         SyntaxKind[SyntaxKind["VariableDeclaration"] = 242] = "VariableDeclaration";
3187         SyntaxKind[SyntaxKind["VariableDeclarationList"] = 243] = "VariableDeclarationList";
3188         SyntaxKind[SyntaxKind["FunctionDeclaration"] = 244] = "FunctionDeclaration";
3189         SyntaxKind[SyntaxKind["ClassDeclaration"] = 245] = "ClassDeclaration";
3190         SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 246] = "InterfaceDeclaration";
3191         SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 247] = "TypeAliasDeclaration";
3192         SyntaxKind[SyntaxKind["EnumDeclaration"] = 248] = "EnumDeclaration";
3193         SyntaxKind[SyntaxKind["ModuleDeclaration"] = 249] = "ModuleDeclaration";
3194         SyntaxKind[SyntaxKind["ModuleBlock"] = 250] = "ModuleBlock";
3195         SyntaxKind[SyntaxKind["CaseBlock"] = 251] = "CaseBlock";
3196         SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 252] = "NamespaceExportDeclaration";
3197         SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 253] = "ImportEqualsDeclaration";
3198         SyntaxKind[SyntaxKind["ImportDeclaration"] = 254] = "ImportDeclaration";
3199         SyntaxKind[SyntaxKind["ImportClause"] = 255] = "ImportClause";
3200         SyntaxKind[SyntaxKind["NamespaceImport"] = 256] = "NamespaceImport";
3201         SyntaxKind[SyntaxKind["NamedImports"] = 257] = "NamedImports";
3202         SyntaxKind[SyntaxKind["ImportSpecifier"] = 258] = "ImportSpecifier";
3203         SyntaxKind[SyntaxKind["ExportAssignment"] = 259] = "ExportAssignment";
3204         SyntaxKind[SyntaxKind["ExportDeclaration"] = 260] = "ExportDeclaration";
3205         SyntaxKind[SyntaxKind["NamedExports"] = 261] = "NamedExports";
3206         SyntaxKind[SyntaxKind["NamespaceExport"] = 262] = "NamespaceExport";
3207         SyntaxKind[SyntaxKind["ExportSpecifier"] = 263] = "ExportSpecifier";
3208         SyntaxKind[SyntaxKind["MissingDeclaration"] = 264] = "MissingDeclaration";
3209         // Module references
3210         SyntaxKind[SyntaxKind["ExternalModuleReference"] = 265] = "ExternalModuleReference";
3211         // JSX
3212         SyntaxKind[SyntaxKind["JsxElement"] = 266] = "JsxElement";
3213         SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 267] = "JsxSelfClosingElement";
3214         SyntaxKind[SyntaxKind["JsxOpeningElement"] = 268] = "JsxOpeningElement";
3215         SyntaxKind[SyntaxKind["JsxClosingElement"] = 269] = "JsxClosingElement";
3216         SyntaxKind[SyntaxKind["JsxFragment"] = 270] = "JsxFragment";
3217         SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 271] = "JsxOpeningFragment";
3218         SyntaxKind[SyntaxKind["JsxClosingFragment"] = 272] = "JsxClosingFragment";
3219         SyntaxKind[SyntaxKind["JsxAttribute"] = 273] = "JsxAttribute";
3220         SyntaxKind[SyntaxKind["JsxAttributes"] = 274] = "JsxAttributes";
3221         SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 275] = "JsxSpreadAttribute";
3222         SyntaxKind[SyntaxKind["JsxExpression"] = 276] = "JsxExpression";
3223         // Clauses
3224         SyntaxKind[SyntaxKind["CaseClause"] = 277] = "CaseClause";
3225         SyntaxKind[SyntaxKind["DefaultClause"] = 278] = "DefaultClause";
3226         SyntaxKind[SyntaxKind["HeritageClause"] = 279] = "HeritageClause";
3227         SyntaxKind[SyntaxKind["CatchClause"] = 280] = "CatchClause";
3228         // Property assignments
3229         SyntaxKind[SyntaxKind["PropertyAssignment"] = 281] = "PropertyAssignment";
3230         SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 282] = "ShorthandPropertyAssignment";
3231         SyntaxKind[SyntaxKind["SpreadAssignment"] = 283] = "SpreadAssignment";
3232         // Enum
3233         SyntaxKind[SyntaxKind["EnumMember"] = 284] = "EnumMember";
3234         // Unparsed
3235         SyntaxKind[SyntaxKind["UnparsedPrologue"] = 285] = "UnparsedPrologue";
3236         SyntaxKind[SyntaxKind["UnparsedPrepend"] = 286] = "UnparsedPrepend";
3237         SyntaxKind[SyntaxKind["UnparsedText"] = 287] = "UnparsedText";
3238         SyntaxKind[SyntaxKind["UnparsedInternalText"] = 288] = "UnparsedInternalText";
3239         SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 289] = "UnparsedSyntheticReference";
3240         // Top-level nodes
3241         SyntaxKind[SyntaxKind["SourceFile"] = 290] = "SourceFile";
3242         SyntaxKind[SyntaxKind["Bundle"] = 291] = "Bundle";
3243         SyntaxKind[SyntaxKind["UnparsedSource"] = 292] = "UnparsedSource";
3244         SyntaxKind[SyntaxKind["InputFiles"] = 293] = "InputFiles";
3245         // JSDoc nodes
3246         SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 294] = "JSDocTypeExpression";
3247         // The * type
3248         SyntaxKind[SyntaxKind["JSDocAllType"] = 295] = "JSDocAllType";
3249         // The ? type
3250         SyntaxKind[SyntaxKind["JSDocUnknownType"] = 296] = "JSDocUnknownType";
3251         SyntaxKind[SyntaxKind["JSDocNullableType"] = 297] = "JSDocNullableType";
3252         SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 298] = "JSDocNonNullableType";
3253         SyntaxKind[SyntaxKind["JSDocOptionalType"] = 299] = "JSDocOptionalType";
3254         SyntaxKind[SyntaxKind["JSDocFunctionType"] = 300] = "JSDocFunctionType";
3255         SyntaxKind[SyntaxKind["JSDocVariadicType"] = 301] = "JSDocVariadicType";
3256         // https://jsdoc.app/about-namepaths.html
3257         SyntaxKind[SyntaxKind["JSDocNamepathType"] = 302] = "JSDocNamepathType";
3258         SyntaxKind[SyntaxKind["JSDocComment"] = 303] = "JSDocComment";
3259         SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 304] = "JSDocTypeLiteral";
3260         SyntaxKind[SyntaxKind["JSDocSignature"] = 305] = "JSDocSignature";
3261         SyntaxKind[SyntaxKind["JSDocTag"] = 306] = "JSDocTag";
3262         SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 307] = "JSDocAugmentsTag";
3263         SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 308] = "JSDocImplementsTag";
3264         SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 309] = "JSDocAuthorTag";
3265         SyntaxKind[SyntaxKind["JSDocClassTag"] = 310] = "JSDocClassTag";
3266         SyntaxKind[SyntaxKind["JSDocPublicTag"] = 311] = "JSDocPublicTag";
3267         SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 312] = "JSDocPrivateTag";
3268         SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 313] = "JSDocProtectedTag";
3269         SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 314] = "JSDocReadonlyTag";
3270         SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 315] = "JSDocCallbackTag";
3271         SyntaxKind[SyntaxKind["JSDocEnumTag"] = 316] = "JSDocEnumTag";
3272         SyntaxKind[SyntaxKind["JSDocParameterTag"] = 317] = "JSDocParameterTag";
3273         SyntaxKind[SyntaxKind["JSDocReturnTag"] = 318] = "JSDocReturnTag";
3274         SyntaxKind[SyntaxKind["JSDocThisTag"] = 319] = "JSDocThisTag";
3275         SyntaxKind[SyntaxKind["JSDocTypeTag"] = 320] = "JSDocTypeTag";
3276         SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 321] = "JSDocTemplateTag";
3277         SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 322] = "JSDocTypedefTag";
3278         SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 323] = "JSDocPropertyTag";
3279         // Synthesized list
3280         SyntaxKind[SyntaxKind["SyntaxList"] = 324] = "SyntaxList";
3281         // Transformation nodes
3282         SyntaxKind[SyntaxKind["NotEmittedStatement"] = 325] = "NotEmittedStatement";
3283         SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 326] = "PartiallyEmittedExpression";
3284         SyntaxKind[SyntaxKind["CommaListExpression"] = 327] = "CommaListExpression";
3285         SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 328] = "MergeDeclarationMarker";
3286         SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 329] = "EndOfDeclarationMarker";
3287         SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 330] = "SyntheticReferenceExpression";
3288         // Enum value count
3289         SyntaxKind[SyntaxKind["Count"] = 331] = "Count";
3290         // Markers
3291         SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment";
3292         SyntaxKind[SyntaxKind["LastAssignment"] = 74] = "LastAssignment";
3293         SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 63] = "FirstCompoundAssignment";
3294         SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 74] = "LastCompoundAssignment";
3295         SyntaxKind[SyntaxKind["FirstReservedWord"] = 77] = "FirstReservedWord";
3296         SyntaxKind[SyntaxKind["LastReservedWord"] = 112] = "LastReservedWord";
3297         SyntaxKind[SyntaxKind["FirstKeyword"] = 77] = "FirstKeyword";
3298         SyntaxKind[SyntaxKind["LastKeyword"] = 152] = "LastKeyword";
3299         SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 113] = "FirstFutureReservedWord";
3300         SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 121] = "LastFutureReservedWord";
3301         SyntaxKind[SyntaxKind["FirstTypeNode"] = 168] = "FirstTypeNode";
3302         SyntaxKind[SyntaxKind["LastTypeNode"] = 188] = "LastTypeNode";
3303         SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
3304         SyntaxKind[SyntaxKind["LastPunctuation"] = 74] = "LastPunctuation";
3305         SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
3306         SyntaxKind[SyntaxKind["LastToken"] = 152] = "LastToken";
3307         SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
3308         SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
3309         SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
3310         SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
3311         SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
3312         SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
3313         SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
3314         SyntaxKind[SyntaxKind["LastBinaryOperator"] = 74] = "LastBinaryOperator";
3315         SyntaxKind[SyntaxKind["FirstStatement"] = 225] = "FirstStatement";
3316         SyntaxKind[SyntaxKind["LastStatement"] = 241] = "LastStatement";
3317         SyntaxKind[SyntaxKind["FirstNode"] = 153] = "FirstNode";
3318         SyntaxKind[SyntaxKind["FirstJSDocNode"] = 294] = "FirstJSDocNode";
3319         SyntaxKind[SyntaxKind["LastJSDocNode"] = 323] = "LastJSDocNode";
3320         SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 306] = "FirstJSDocTagNode";
3321         SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 323] = "LastJSDocTagNode";
3322         /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 122] = "FirstContextualKeyword";
3323         /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 152] = "LastContextualKeyword";
3324     })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
3325     var NodeFlags;
3326     (function (NodeFlags) {
3327         NodeFlags[NodeFlags["None"] = 0] = "None";
3328         NodeFlags[NodeFlags["Let"] = 1] = "Let";
3329         NodeFlags[NodeFlags["Const"] = 2] = "Const";
3330         NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
3331         NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
3332         NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
3333         NodeFlags[NodeFlags["OptionalChain"] = 32] = "OptionalChain";
3334         NodeFlags[NodeFlags["ExportContext"] = 64] = "ExportContext";
3335         NodeFlags[NodeFlags["ContainsThis"] = 128] = "ContainsThis";
3336         NodeFlags[NodeFlags["HasImplicitReturn"] = 256] = "HasImplicitReturn";
3337         NodeFlags[NodeFlags["HasExplicitReturn"] = 512] = "HasExplicitReturn";
3338         NodeFlags[NodeFlags["GlobalAugmentation"] = 1024] = "GlobalAugmentation";
3339         NodeFlags[NodeFlags["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions";
3340         NodeFlags[NodeFlags["DisallowInContext"] = 4096] = "DisallowInContext";
3341         NodeFlags[NodeFlags["YieldContext"] = 8192] = "YieldContext";
3342         NodeFlags[NodeFlags["DecoratorContext"] = 16384] = "DecoratorContext";
3343         NodeFlags[NodeFlags["AwaitContext"] = 32768] = "AwaitContext";
3344         NodeFlags[NodeFlags["ThisNodeHasError"] = 65536] = "ThisNodeHasError";
3345         NodeFlags[NodeFlags["JavaScriptFile"] = 131072] = "JavaScriptFile";
3346         NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 262144] = "ThisNodeOrAnySubNodesHasError";
3347         NodeFlags[NodeFlags["HasAggregatedChildData"] = 524288] = "HasAggregatedChildData";
3348         // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
3349         // walking the tree if the flags are not set. However, these flags are just a approximation
3350         // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
3351         // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
3352         // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
3353         // However, the removal operation should not occur often and in the case of the
3354         // removal, it is likely that users will add the import anyway.
3355         // The advantage of this approach is its simplicity. For the case of batch compilation,
3356         // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
3357         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 1048576] = "PossiblyContainsDynamicImport";
3358         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 2097152] = "PossiblyContainsImportMeta";
3359         NodeFlags[NodeFlags["JSDoc"] = 4194304] = "JSDoc";
3360         /* @internal */ NodeFlags[NodeFlags["Ambient"] = 8388608] = "Ambient";
3361         /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
3362         NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
3363         /* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
3364         NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
3365         NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
3366         NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
3367         // Parsing context flags
3368         NodeFlags[NodeFlags["ContextFlags"] = 25358336] = "ContextFlags";
3369         // Exclude these flags when parsing a Type
3370         NodeFlags[NodeFlags["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags";
3371         // Represents all flags that are potentially set once and
3372         // never cleared on SourceFiles which get re-used in between incremental parses.
3373         // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
3374         /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 3145728] = "PermanentlySetIncrementalFlags";
3375     })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
3376     var ModifierFlags;
3377     (function (ModifierFlags) {
3378         ModifierFlags[ModifierFlags["None"] = 0] = "None";
3379         ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
3380         ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
3381         ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
3382         ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
3383         ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
3384         ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
3385         ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
3386         ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
3387         ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
3388         ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
3389         ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
3390         ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
3391         ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
3392         // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
3393         ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
3394         ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
3395         ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
3396         ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
3397         ModifierFlags[ModifierFlags["All"] = 3071] = "All";
3398     })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
3399     var JsxFlags;
3400     (function (JsxFlags) {
3401         JsxFlags[JsxFlags["None"] = 0] = "None";
3402         /** An element from a named property of the JSX.IntrinsicElements interface */
3403         JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
3404         /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
3405         JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
3406         JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
3407     })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
3408     /* @internal */
3409     var RelationComparisonResult;
3410     (function (RelationComparisonResult) {
3411         RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
3412         RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
3413         RelationComparisonResult[RelationComparisonResult["Reported"] = 4] = "Reported";
3414         RelationComparisonResult[RelationComparisonResult["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable";
3415         RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
3416         RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
3417     })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
3418     /*@internal*/
3419     var GeneratedIdentifierFlags;
3420     (function (GeneratedIdentifierFlags) {
3421         // Kinds
3422         GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
3423         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
3424         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
3425         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
3426         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
3427         GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
3428         // Flags
3429         GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
3430         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
3431         GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
3432     })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
3433     var TokenFlags;
3434     (function (TokenFlags) {
3435         TokenFlags[TokenFlags["None"] = 0] = "None";
3436         /* @internal */
3437         TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
3438         /* @internal */
3439         TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
3440         /* @internal */
3441         TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
3442         /* @internal */
3443         TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
3444         TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
3445         TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
3446         TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
3447         TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
3448         TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
3449         /* @internal */
3450         TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
3451         /* @internal */
3452         TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape";
3453         /* @internal */
3454         TokenFlags[TokenFlags["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape";
3455         /* @internal */
3456         TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
3457         /* @internal */
3458         TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
3459     })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
3460     // NOTE: Ensure this is up-to-date with src/debug/debug.ts
3461     var FlowFlags;
3462     (function (FlowFlags) {
3463         FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
3464         FlowFlags[FlowFlags["Start"] = 2] = "Start";
3465         FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
3466         FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
3467         FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
3468         FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
3469         FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
3470         FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
3471         FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
3472         FlowFlags[FlowFlags["Call"] = 512] = "Call";
3473         FlowFlags[FlowFlags["ReduceLabel"] = 1024] = "ReduceLabel";
3474         FlowFlags[FlowFlags["Referenced"] = 2048] = "Referenced";
3475         FlowFlags[FlowFlags["Shared"] = 4096] = "Shared";
3476         FlowFlags[FlowFlags["Label"] = 12] = "Label";
3477         FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
3478     })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
3479     /* @internal */
3480     var CommentDirectiveType;
3481     (function (CommentDirectiveType) {
3482         CommentDirectiveType[CommentDirectiveType["ExpectError"] = 0] = "ExpectError";
3483         CommentDirectiveType[CommentDirectiveType["Ignore"] = 1] = "Ignore";
3484     })(CommentDirectiveType = ts.CommentDirectiveType || (ts.CommentDirectiveType = {}));
3485     var OperationCanceledException = /** @class */ (function () {
3486         function OperationCanceledException() {
3487         }
3488         return OperationCanceledException;
3489     }());
3490     ts.OperationCanceledException = OperationCanceledException;
3491     /*@internal*/
3492     var RefFileKind;
3493     (function (RefFileKind) {
3494         RefFileKind[RefFileKind["Import"] = 0] = "Import";
3495         RefFileKind[RefFileKind["ReferenceFile"] = 1] = "ReferenceFile";
3496         RefFileKind[RefFileKind["TypeReferenceDirective"] = 2] = "TypeReferenceDirective";
3497     })(RefFileKind = ts.RefFileKind || (ts.RefFileKind = {}));
3498     /* @internal */
3499     var StructureIsReused;
3500     (function (StructureIsReused) {
3501         StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
3502         StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
3503         StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
3504     })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
3505     /** Return code used by getEmitOutput function to indicate status of the function */
3506     var ExitStatus;
3507     (function (ExitStatus) {
3508         // Compiler ran successfully.  Either this was a simple do-nothing compilation (for example,
3509         // when -version or -help was provided, or this was a normal compilation, no diagnostics
3510         // were produced, and all outputs were generated successfully.
3511         ExitStatus[ExitStatus["Success"] = 0] = "Success";
3512         // Diagnostics were produced and because of them no code was generated.
3513         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
3514         // Diagnostics were produced and outputs were generated in spite of them.
3515         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
3516         // When build skipped because passed in project is invalid
3517         ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped";
3518         // When build is skipped because project references form cycle
3519         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped";
3520         /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
3521         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
3522     })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
3523     /* @internal */
3524     var UnionReduction;
3525     (function (UnionReduction) {
3526         UnionReduction[UnionReduction["None"] = 0] = "None";
3527         UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
3528         UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
3529     })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
3530     /* @internal */
3531     var ContextFlags;
3532     (function (ContextFlags) {
3533         ContextFlags[ContextFlags["None"] = 0] = "None";
3534         ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
3535         ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
3536         ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
3537     })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
3538     // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
3539     var NodeBuilderFlags;
3540     (function (NodeBuilderFlags) {
3541         NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
3542         // Options
3543         NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
3544         NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3545         NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
3546         NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3547         NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
3548         NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3549         NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3550         NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
3551         NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3552         NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
3553         NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3554         NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3555         NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3556         NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3557         NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3558         NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3559         NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3560         // Error handling
3561         NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
3562         NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
3563         NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
3564         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
3565         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
3566         NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3567         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
3568         // Errors (cont.)
3569         NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
3570         /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
3571         NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
3572         // State
3573         NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
3574         NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3575         NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
3576         NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
3577     })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
3578     // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
3579     var TypeFormatFlags;
3580     (function (TypeFormatFlags) {
3581         TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
3582         TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
3583         TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3584         // hole because there's a hole in node builder flags
3585         TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3586         // hole because there's a hole in node builder flags
3587         TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3588         TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3589         // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
3590         TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3591         // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
3592         TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3593         TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3594         TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3595         TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3596         TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3597         TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3598         TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3599         // Error Handling
3600         TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3601         // TypeFormatFlags exclusive
3602         TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
3603         TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
3604         // State
3605         TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
3606         TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
3607         TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
3608         TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3609         /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
3610         TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask";
3611     })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
3612     var SymbolFormatFlags;
3613     (function (SymbolFormatFlags) {
3614         SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
3615         // Write symbols's type argument if it is instantiated symbol
3616         // eg. class C<T> { p: T }   <-- Show p as C<T>.p here
3617         //     var a: C<number>;
3618         //     var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
3619         SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
3620         // Use only external alias information to get the symbol name in the given context
3621         // eg.  module m { export class c { } } import x = m.c;
3622         // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
3623         SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
3624         // Build symbol name using any nodes needed, instead of just components of an entity name
3625         SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
3626         // Prefer aliases which are not directly visible
3627         SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
3628         // Skip building an accessible symbol chain
3629         /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
3630     })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
3631     /* @internal */
3632     var SymbolAccessibility;
3633     (function (SymbolAccessibility) {
3634         SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
3635         SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
3636         SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
3637     })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
3638     /* @internal */
3639     var SyntheticSymbolKind;
3640     (function (SyntheticSymbolKind) {
3641         SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
3642         SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
3643     })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
3644     var TypePredicateKind;
3645     (function (TypePredicateKind) {
3646         TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
3647         TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
3648         TypePredicateKind[TypePredicateKind["AssertsThis"] = 2] = "AssertsThis";
3649         TypePredicateKind[TypePredicateKind["AssertsIdentifier"] = 3] = "AssertsIdentifier";
3650     })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
3651     /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
3652     /* @internal */
3653     var TypeReferenceSerializationKind;
3654     (function (TypeReferenceSerializationKind) {
3655         // The TypeReferenceNode could not be resolved.
3656         // The type name should be emitted using a safe fallback.
3657         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
3658         // The TypeReferenceNode resolves to a type with a constructor
3659         // function that can be reached at runtime (e.g. a `class`
3660         // declaration or a `var` declaration for the static side
3661         // of a type, such as the global `Promise` type in lib.d.ts).
3662         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
3663         // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
3664         TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
3665         // The TypeReferenceNode resolves to a Number-like type.
3666         TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
3667         // The TypeReferenceNode resolves to a BigInt-like type.
3668         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
3669         // The TypeReferenceNode resolves to a String-like type.
3670         TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
3671         // The TypeReferenceNode resolves to a Boolean-like type.
3672         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
3673         // The TypeReferenceNode resolves to an Array-like type.
3674         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
3675         // The TypeReferenceNode resolves to the ESSymbol type.
3676         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
3677         // The TypeReferenceNode resolved to the global Promise constructor symbol.
3678         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
3679         // The TypeReferenceNode resolves to a Function type or a type with call signatures.
3680         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
3681         // The TypeReferenceNode resolves to any other type.
3682         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
3683     })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
3684     var SymbolFlags;
3685     (function (SymbolFlags) {
3686         SymbolFlags[SymbolFlags["None"] = 0] = "None";
3687         SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
3688         SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
3689         SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
3690         SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
3691         SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
3692         SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
3693         SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
3694         SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
3695         SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
3696         SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
3697         SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
3698         SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
3699         SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
3700         SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
3701         SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
3702         SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
3703         SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
3704         SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
3705         SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
3706         SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
3707         SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
3708         SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
3709         SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
3710         SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
3711         SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
3712         SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
3713         SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
3714         SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
3715         /* @internal */
3716         SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
3717         SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
3718         SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
3719         SymbolFlags[SymbolFlags["Value"] = 111551] = "Value";
3720         SymbolFlags[SymbolFlags["Type"] = 788968] = "Type";
3721         SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
3722         SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
3723         SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
3724         // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
3725         // same name, or any other value that is not a variable, e.g. ValueModule or Class
3726         SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes";
3727         // Block-scoped declarations are not allowed to be re-declared
3728         // they can not merge with anything in the value space
3729         SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes";
3730         SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes";
3731         SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
3732         SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes";
3733         SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes";
3734         SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes";
3735         SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes";
3736         SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes";
3737         SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes";
3738         SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
3739         SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
3740         SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes";
3741         SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes";
3742         SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes";
3743         SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes";
3744         SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes";
3745         SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
3746         SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
3747         SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
3748         SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
3749         SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
3750         SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
3751         /* @internal */
3752         SymbolFlags[SymbolFlags["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier";
3753         /* @internal */
3754         SymbolFlags[SymbolFlags["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier";
3755         /* @internal */
3756         // The set of things we consider semantically classifiable.  Used to speed up the LS during
3757         // classification.
3758         SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
3759         /* @internal */
3760         SymbolFlags[SymbolFlags["LateBindingContainer"] = 6256] = "LateBindingContainer";
3761     })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
3762     /* @internal */
3763     var EnumKind;
3764     (function (EnumKind) {
3765         EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
3766         EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
3767     })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
3768     /* @internal */
3769     var CheckFlags;
3770     (function (CheckFlags) {
3771         CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
3772         CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
3773         CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
3774         CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
3775         CheckFlags[CheckFlags["ReadPartial"] = 16] = "ReadPartial";
3776         CheckFlags[CheckFlags["WritePartial"] = 32] = "WritePartial";
3777         CheckFlags[CheckFlags["HasNonUniformType"] = 64] = "HasNonUniformType";
3778         CheckFlags[CheckFlags["HasLiteralType"] = 128] = "HasLiteralType";
3779         CheckFlags[CheckFlags["ContainsPublic"] = 256] = "ContainsPublic";
3780         CheckFlags[CheckFlags["ContainsProtected"] = 512] = "ContainsProtected";
3781         CheckFlags[CheckFlags["ContainsPrivate"] = 1024] = "ContainsPrivate";
3782         CheckFlags[CheckFlags["ContainsStatic"] = 2048] = "ContainsStatic";
3783         CheckFlags[CheckFlags["Late"] = 4096] = "Late";
3784         CheckFlags[CheckFlags["ReverseMapped"] = 8192] = "ReverseMapped";
3785         CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter";
3786         CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter";
3787         CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType";
3788         CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType";
3789         CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped";
3790         CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional";
3791         CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
3792         CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
3793         CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
3794     })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
3795     var InternalSymbolName;
3796     (function (InternalSymbolName) {
3797         InternalSymbolName["Call"] = "__call";
3798         InternalSymbolName["Constructor"] = "__constructor";
3799         InternalSymbolName["New"] = "__new";
3800         InternalSymbolName["Index"] = "__index";
3801         InternalSymbolName["ExportStar"] = "__export";
3802         InternalSymbolName["Global"] = "__global";
3803         InternalSymbolName["Missing"] = "__missing";
3804         InternalSymbolName["Type"] = "__type";
3805         InternalSymbolName["Object"] = "__object";
3806         InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
3807         InternalSymbolName["Class"] = "__class";
3808         InternalSymbolName["Function"] = "__function";
3809         InternalSymbolName["Computed"] = "__computed";
3810         InternalSymbolName["Resolving"] = "__resolving__";
3811         InternalSymbolName["ExportEquals"] = "export=";
3812         InternalSymbolName["Default"] = "default";
3813         InternalSymbolName["This"] = "this";
3814     })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
3815     /* @internal */
3816     var NodeCheckFlags;
3817     (function (NodeCheckFlags) {
3818         NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
3819         NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
3820         NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
3821         NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
3822         NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
3823         NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
3824         NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
3825         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
3826         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
3827         NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
3828         NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
3829         NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
3830         NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
3831         NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
3832         NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
3833         NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
3834         NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
3835         NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
3836         NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
3837         NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
3838         NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
3839         NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
3840         NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
3841     })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
3842     var TypeFlags;
3843     (function (TypeFlags) {
3844         TypeFlags[TypeFlags["Any"] = 1] = "Any";
3845         TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
3846         TypeFlags[TypeFlags["String"] = 4] = "String";
3847         TypeFlags[TypeFlags["Number"] = 8] = "Number";
3848         TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
3849         TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
3850         TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
3851         TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
3852         TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
3853         TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
3854         TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
3855         TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
3856         TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
3857         TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
3858         TypeFlags[TypeFlags["Void"] = 16384] = "Void";
3859         TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
3860         TypeFlags[TypeFlags["Null"] = 65536] = "Null";
3861         TypeFlags[TypeFlags["Never"] = 131072] = "Never";
3862         TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
3863         TypeFlags[TypeFlags["Object"] = 524288] = "Object";
3864         TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
3865         TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
3866         TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
3867         TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
3868         TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
3869         TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
3870         TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
3871         /* @internal */
3872         TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
3873         /* @internal */
3874         TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
3875         TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
3876         TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
3877         TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
3878         /* @internal */
3879         TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
3880         /* @internal */
3881         TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
3882         TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
3883         /* @internal */
3884         TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
3885         /* @internal */
3886         TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
3887         TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike";
3888         TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
3889         TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
3890         TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
3891         TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
3892         TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
3893         TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
3894         /* @internal */
3895         TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains";
3896         TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
3897         TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
3898         TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
3899         TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
3900         TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
3901         TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
3902         TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
3903         /* @internal */
3904         TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
3905         /* @internal */
3906         TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
3907         /* @internal */
3908         TypeFlags[TypeFlags["Substructure"] = 66584576] = "Substructure";
3909         // 'Narrowable' types are types where narrowing actually narrows.
3910         // This *should* be every type other than null, undefined, void, and never
3911         TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
3912         TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
3913         /* @internal */
3914         TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
3915         // The following flags are aggregated during union and intersection type construction
3916         /* @internal */
3917         TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask";
3918         // The following flags are used for different purposes during union and intersection type construction
3919         /* @internal */
3920         TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
3921         /* @internal */
3922         TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType";
3923         /* @internal */
3924         TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard";
3925         /* @internal */
3926         TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject";
3927     })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
3928     var ObjectFlags;
3929     (function (ObjectFlags) {
3930         ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
3931         ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
3932         ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
3933         ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
3934         ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
3935         ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
3936         ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
3937         ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
3938         ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
3939         ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
3940         ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
3941         ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
3942         ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
3943         ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
3944         ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
3945         ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
3946         ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral";
3947         ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType";
3948         /* @internal */
3949         ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion";
3950         /* @internal */
3951         ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType";
3952         /* @internal */
3953         ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral";
3954         /* @internal */
3955         ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType";
3956         /* @internal */
3957         ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed";
3958         /* @internal */
3959         ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
3960         /* @internal */
3961         ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed";
3962         /* @internal */
3963         ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType";
3964         /* @internal */
3965         ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed";
3966         /* @internal */
3967         ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables";
3968         /* @internal */
3969         ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections";
3970         /* @internal */
3971         ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed";
3972         /* @internal */
3973         ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection";
3974         ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
3975         /* @internal */
3976         ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening";
3977         /* @internal */
3978         ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags";
3979     })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
3980     /* @internal */
3981     var VarianceFlags;
3982     (function (VarianceFlags) {
3983         VarianceFlags[VarianceFlags["Invariant"] = 0] = "Invariant";
3984         VarianceFlags[VarianceFlags["Covariant"] = 1] = "Covariant";
3985         VarianceFlags[VarianceFlags["Contravariant"] = 2] = "Contravariant";
3986         VarianceFlags[VarianceFlags["Bivariant"] = 3] = "Bivariant";
3987         VarianceFlags[VarianceFlags["Independent"] = 4] = "Independent";
3988         VarianceFlags[VarianceFlags["VarianceMask"] = 7] = "VarianceMask";
3989         VarianceFlags[VarianceFlags["Unmeasurable"] = 8] = "Unmeasurable";
3990         VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
3991         VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
3992     })(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
3993     /* @internal */
3994     var JsxReferenceKind;
3995     (function (JsxReferenceKind) {
3996         JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
3997         JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
3998         JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
3999     })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
4000     var SignatureKind;
4001     (function (SignatureKind) {
4002         SignatureKind[SignatureKind["Call"] = 0] = "Call";
4003         SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
4004     })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
4005     /* @internal */
4006     var SignatureFlags;
4007     (function (SignatureFlags) {
4008         SignatureFlags[SignatureFlags["None"] = 0] = "None";
4009         SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
4010         SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
4011         SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain";
4012         SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain";
4013         SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 16] = "IsUntypedSignatureInJSFile";
4014         // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us
4015         // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
4016         // instantiating the return type.
4017         SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags";
4018         SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags";
4019     })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
4020     var IndexKind;
4021     (function (IndexKind) {
4022         IndexKind[IndexKind["String"] = 0] = "String";
4023         IndexKind[IndexKind["Number"] = 1] = "Number";
4024     })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
4025     /* @internal */
4026     var TypeMapKind;
4027     (function (TypeMapKind) {
4028         TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple";
4029         TypeMapKind[TypeMapKind["Array"] = 1] = "Array";
4030         TypeMapKind[TypeMapKind["Function"] = 2] = "Function";
4031         TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite";
4032         TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged";
4033     })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {}));
4034     var InferencePriority;
4035     (function (InferencePriority) {
4036         InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
4037         InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
4038         InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 4] = "PartialHomomorphicMappedType";
4039         InferencePriority[InferencePriority["MappedTypeConstraint"] = 8] = "MappedTypeConstraint";
4040         InferencePriority[InferencePriority["ContravariantConditional"] = 16] = "ContravariantConditional";
4041         InferencePriority[InferencePriority["ReturnType"] = 32] = "ReturnType";
4042         InferencePriority[InferencePriority["LiteralKeyof"] = 64] = "LiteralKeyof";
4043         InferencePriority[InferencePriority["NoConstraints"] = 128] = "NoConstraints";
4044         InferencePriority[InferencePriority["AlwaysStrict"] = 256] = "AlwaysStrict";
4045         InferencePriority[InferencePriority["MaxValue"] = 512] = "MaxValue";
4046         InferencePriority[InferencePriority["PriorityImpliesCombination"] = 104] = "PriorityImpliesCombination";
4047         InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
4048     })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
4049     /* @internal */
4050     var InferenceFlags;
4051     (function (InferenceFlags) {
4052         InferenceFlags[InferenceFlags["None"] = 0] = "None";
4053         InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
4054         InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
4055         InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
4056     })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
4057     /**
4058      * Ternary values are defined such that
4059      * x & y is False if either x or y is False.
4060      * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
4061      * x & y is True if both x and y are True.
4062      * x | y is False if both x and y are False.
4063      * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
4064      * x | y is True if either x or y is True.
4065      */
4066     /* @internal */
4067     var Ternary;
4068     (function (Ternary) {
4069         Ternary[Ternary["False"] = 0] = "False";
4070         Ternary[Ternary["Maybe"] = 1] = "Maybe";
4071         Ternary[Ternary["True"] = -1] = "True";
4072     })(Ternary = ts.Ternary || (ts.Ternary = {}));
4073     /* @internal */
4074     var AssignmentDeclarationKind;
4075     (function (AssignmentDeclarationKind) {
4076         AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
4077         /// exports.name = expr
4078         AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
4079         /// module.exports = expr
4080         AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
4081         /// className.prototype.name = expr
4082         AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
4083         /// this.name = expr
4084         AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
4085         // F.name = expr
4086         AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
4087         // F.prototype = { ... }
4088         AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
4089         // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
4090         // Object.defineProperty(x, 'name', { get: Function, set: Function });
4091         // Object.defineProperty(x, 'name', { get: Function });
4092         // Object.defineProperty(x, 'name', { set: Function });
4093         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
4094         // Object.defineProperty(exports || module.exports, 'name', ...);
4095         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
4096         // Object.defineProperty(Foo.prototype, 'name', ...);
4097         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
4098     })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
4099     var DiagnosticCategory;
4100     (function (DiagnosticCategory) {
4101         DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
4102         DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
4103         DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
4104         DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
4105     })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
4106     /* @internal */
4107     function diagnosticCategoryName(d, lowerCase) {
4108         if (lowerCase === void 0) { lowerCase = true; }
4109         var name = DiagnosticCategory[d.category];
4110         return lowerCase ? name.toLowerCase() : name;
4111     }
4112     ts.diagnosticCategoryName = diagnosticCategoryName;
4113     var ModuleResolutionKind;
4114     (function (ModuleResolutionKind) {
4115         ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
4116         ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
4117     })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
4118     var WatchFileKind;
4119     (function (WatchFileKind) {
4120         WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
4121         WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
4122         WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4123         WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents";
4124         WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory";
4125     })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
4126     var WatchDirectoryKind;
4127     (function (WatchDirectoryKind) {
4128         WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
4129         WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
4130         WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4131     })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
4132     var PollingWatchKind;
4133     (function (PollingWatchKind) {
4134         PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
4135         PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
4136         PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
4137     })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
4138     var ModuleKind;
4139     (function (ModuleKind) {
4140         ModuleKind[ModuleKind["None"] = 0] = "None";
4141         ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
4142         ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
4143         ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
4144         ModuleKind[ModuleKind["System"] = 4] = "System";
4145         // NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
4146         //       Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
4147         //       module kind).
4148         ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
4149         ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
4150         ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
4151     })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
4152     var JsxEmit;
4153     (function (JsxEmit) {
4154         JsxEmit[JsxEmit["None"] = 0] = "None";
4155         JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
4156         JsxEmit[JsxEmit["React"] = 2] = "React";
4157         JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
4158     })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
4159     var ImportsNotUsedAsValues;
4160     (function (ImportsNotUsedAsValues) {
4161         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Remove"] = 0] = "Remove";
4162         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Preserve"] = 1] = "Preserve";
4163         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Error"] = 2] = "Error";
4164     })(ImportsNotUsedAsValues = ts.ImportsNotUsedAsValues || (ts.ImportsNotUsedAsValues = {}));
4165     var NewLineKind;
4166     (function (NewLineKind) {
4167         NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
4168         NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
4169     })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
4170     var ScriptKind;
4171     (function (ScriptKind) {
4172         ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
4173         ScriptKind[ScriptKind["JS"] = 1] = "JS";
4174         ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
4175         ScriptKind[ScriptKind["TS"] = 3] = "TS";
4176         ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
4177         ScriptKind[ScriptKind["External"] = 5] = "External";
4178         ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
4179         /**
4180          * Used on extensions that doesn't define the ScriptKind but the content defines it.
4181          * Deferred extensions are going to be included in all project contexts.
4182          */
4183         ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
4184     })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
4185     var ScriptTarget;
4186     (function (ScriptTarget) {
4187         ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
4188         ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
4189         ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
4190         ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
4191         ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
4192         ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
4193         ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
4194         ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
4195         ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
4196         ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
4197         ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
4198     })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
4199     var LanguageVariant;
4200     (function (LanguageVariant) {
4201         LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
4202         LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
4203     })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
4204     var WatchDirectoryFlags;
4205     (function (WatchDirectoryFlags) {
4206         WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
4207         WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
4208     })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
4209     /* @internal */
4210     var CharacterCodes;
4211     (function (CharacterCodes) {
4212         CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
4213         CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
4214         CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
4215         CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
4216         CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
4217         CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
4218         CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
4219         // Unicode 3.0 space characters
4220         CharacterCodes[CharacterCodes["space"] = 32] = "space";
4221         CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
4222         CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
4223         CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
4224         CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
4225         CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
4226         CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
4227         CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
4228         CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
4229         CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
4230         CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
4231         CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
4232         CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
4233         CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
4234         CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
4235         CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
4236         CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
4237         CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
4238         CharacterCodes[CharacterCodes["_"] = 95] = "_";
4239         CharacterCodes[CharacterCodes["$"] = 36] = "$";
4240         CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
4241         CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
4242         CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
4243         CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
4244         CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
4245         CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
4246         CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
4247         CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
4248         CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
4249         CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
4250         CharacterCodes[CharacterCodes["a"] = 97] = "a";
4251         CharacterCodes[CharacterCodes["b"] = 98] = "b";
4252         CharacterCodes[CharacterCodes["c"] = 99] = "c";
4253         CharacterCodes[CharacterCodes["d"] = 100] = "d";
4254         CharacterCodes[CharacterCodes["e"] = 101] = "e";
4255         CharacterCodes[CharacterCodes["f"] = 102] = "f";
4256         CharacterCodes[CharacterCodes["g"] = 103] = "g";
4257         CharacterCodes[CharacterCodes["h"] = 104] = "h";
4258         CharacterCodes[CharacterCodes["i"] = 105] = "i";
4259         CharacterCodes[CharacterCodes["j"] = 106] = "j";
4260         CharacterCodes[CharacterCodes["k"] = 107] = "k";
4261         CharacterCodes[CharacterCodes["l"] = 108] = "l";
4262         CharacterCodes[CharacterCodes["m"] = 109] = "m";
4263         CharacterCodes[CharacterCodes["n"] = 110] = "n";
4264         CharacterCodes[CharacterCodes["o"] = 111] = "o";
4265         CharacterCodes[CharacterCodes["p"] = 112] = "p";
4266         CharacterCodes[CharacterCodes["q"] = 113] = "q";
4267         CharacterCodes[CharacterCodes["r"] = 114] = "r";
4268         CharacterCodes[CharacterCodes["s"] = 115] = "s";
4269         CharacterCodes[CharacterCodes["t"] = 116] = "t";
4270         CharacterCodes[CharacterCodes["u"] = 117] = "u";
4271         CharacterCodes[CharacterCodes["v"] = 118] = "v";
4272         CharacterCodes[CharacterCodes["w"] = 119] = "w";
4273         CharacterCodes[CharacterCodes["x"] = 120] = "x";
4274         CharacterCodes[CharacterCodes["y"] = 121] = "y";
4275         CharacterCodes[CharacterCodes["z"] = 122] = "z";
4276         CharacterCodes[CharacterCodes["A"] = 65] = "A";
4277         CharacterCodes[CharacterCodes["B"] = 66] = "B";
4278         CharacterCodes[CharacterCodes["C"] = 67] = "C";
4279         CharacterCodes[CharacterCodes["D"] = 68] = "D";
4280         CharacterCodes[CharacterCodes["E"] = 69] = "E";
4281         CharacterCodes[CharacterCodes["F"] = 70] = "F";
4282         CharacterCodes[CharacterCodes["G"] = 71] = "G";
4283         CharacterCodes[CharacterCodes["H"] = 72] = "H";
4284         CharacterCodes[CharacterCodes["I"] = 73] = "I";
4285         CharacterCodes[CharacterCodes["J"] = 74] = "J";
4286         CharacterCodes[CharacterCodes["K"] = 75] = "K";
4287         CharacterCodes[CharacterCodes["L"] = 76] = "L";
4288         CharacterCodes[CharacterCodes["M"] = 77] = "M";
4289         CharacterCodes[CharacterCodes["N"] = 78] = "N";
4290         CharacterCodes[CharacterCodes["O"] = 79] = "O";
4291         CharacterCodes[CharacterCodes["P"] = 80] = "P";
4292         CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
4293         CharacterCodes[CharacterCodes["R"] = 82] = "R";
4294         CharacterCodes[CharacterCodes["S"] = 83] = "S";
4295         CharacterCodes[CharacterCodes["T"] = 84] = "T";
4296         CharacterCodes[CharacterCodes["U"] = 85] = "U";
4297         CharacterCodes[CharacterCodes["V"] = 86] = "V";
4298         CharacterCodes[CharacterCodes["W"] = 87] = "W";
4299         CharacterCodes[CharacterCodes["X"] = 88] = "X";
4300         CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
4301         CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
4302         CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
4303         CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
4304         CharacterCodes[CharacterCodes["at"] = 64] = "at";
4305         CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
4306         CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
4307         CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
4308         CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
4309         CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
4310         CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
4311         CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
4312         CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
4313         CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
4314         CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
4315         CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
4316         CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
4317         CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
4318         CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
4319         CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
4320         CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
4321         CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
4322         CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
4323         CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
4324         CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
4325         CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
4326         CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
4327         CharacterCodes[CharacterCodes["question"] = 63] = "question";
4328         CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
4329         CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
4330         CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
4331         CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
4332         CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
4333         CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
4334         CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
4335         CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
4336         CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
4337     })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
4338     var Extension;
4339     (function (Extension) {
4340         Extension["Ts"] = ".ts";
4341         Extension["Tsx"] = ".tsx";
4342         Extension["Dts"] = ".d.ts";
4343         Extension["Js"] = ".js";
4344         Extension["Jsx"] = ".jsx";
4345         Extension["Json"] = ".json";
4346         Extension["TsBuildInfo"] = ".tsbuildinfo";
4347     })(Extension = ts.Extension || (ts.Extension = {}));
4348     /* @internal */
4349     var TransformFlags;
4350     (function (TransformFlags) {
4351         TransformFlags[TransformFlags["None"] = 0] = "None";
4352         // Facts
4353         // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
4354         TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
4355         TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
4356         TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
4357         TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020";
4358         TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019";
4359         TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018";
4360         TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017";
4361         TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016";
4362         TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015";
4363         TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
4364         TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment";
4365         // Markers
4366         // - Flags used to indicate that a subtree contains a specific transformation.
4367         TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax";
4368         TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis";
4369         TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread";
4370         TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread";
4371         TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName";
4372         TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding";
4373         TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern";
4374         TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield";
4375         TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait";
4376         TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion";
4377         TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport";
4378         TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields";
4379         // Please leave this as 1 << 29.
4380         // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
4381         // It is a good reminder of how much room we have left
4382         TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
4383         // Assertions
4384         // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
4385         TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
4386         TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
4387         TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
4388         TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020";
4389         TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019";
4390         TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018";
4391         TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017";
4392         TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016";
4393         TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015";
4394         TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator";
4395         TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment";
4396         // Scope Exclusions
4397         // - Bitmasks that exclude flags from propagating out of a specific context
4398         //   into the subtree flags of their container.
4399         TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
4400         TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
4401         TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
4402         TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 538920960] = "ArrowFunctionExcludes";
4403         TransformFlags[TransformFlags["FunctionExcludes"] = 538925056] = "FunctionExcludes";
4404         TransformFlags[TransformFlags["ConstructorExcludes"] = 538923008] = "ConstructorExcludes";
4405         TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes";
4406         TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes";
4407         TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes";
4408         TransformFlags[TransformFlags["ModuleExcludes"] = 537991168] = "ModuleExcludes";
4409         TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
4410         TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes";
4411         TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes";
4412         TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes";
4413         TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
4414         TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes";
4415         TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes";
4416         // Propagating flags
4417         // - Bitmasks for flags that should propagate from a child
4418         TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags";
4419         // Masks
4420         // - Additional bitmasks
4421     })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
4422     var EmitFlags;
4423     (function (EmitFlags) {
4424         EmitFlags[EmitFlags["None"] = 0] = "None";
4425         EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
4426         EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
4427         EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
4428         EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
4429         EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
4430         EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
4431         EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
4432         EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
4433         EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
4434         EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
4435         EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
4436         EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
4437         EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
4438         EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
4439         EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
4440         EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
4441         EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
4442         EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
4443         EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
4444         EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
4445         EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
4446         EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
4447         EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
4448         EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
4449         EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
4450         EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
4451         EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
4452         EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
4453         /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
4454         /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
4455         /*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines";
4456     })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
4457     /**
4458      * Used by the checker, this enum keeps track of external emit helpers that should be type
4459      * checked.
4460      */
4461     /* @internal */
4462     var ExternalEmitHelpers;
4463     (function (ExternalEmitHelpers) {
4464         ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
4465         ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
4466         ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
4467         ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
4468         ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
4469         ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
4470         ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
4471         ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
4472         ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
4473         ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
4474         ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
4475         ExternalEmitHelpers[ExternalEmitHelpers["SpreadArrays"] = 2048] = "SpreadArrays";
4476         ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 4096] = "Await";
4477         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 8192] = "AsyncGenerator";
4478         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 16384] = "AsyncDelegator";
4479         ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 32768] = "AsyncValues";
4480         ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 65536] = "ExportStar";
4481         ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 131072] = "MakeTemplateObject";
4482         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 262144] = "ClassPrivateFieldGet";
4483         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 524288] = "ClassPrivateFieldSet";
4484         ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 1048576] = "CreateBinding";
4485         ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
4486         ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 1048576] = "LastEmitHelper";
4487         // Helpers included by ES2015 for..of
4488         ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
4489         // Helpers included by ES2017 for..await..of
4490         ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 32768] = "ForAwaitOfIncludes";
4491         // Helpers included by ES2017 async generators
4492         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 12288] = "AsyncGeneratorIncludes";
4493         // Helpers included by yield* in ES2017 async generators
4494         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 53248] = "AsyncDelegatorIncludes";
4495         // Helpers included by ES2015 spread
4496         ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
4497     })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
4498     var EmitHint;
4499     (function (EmitHint) {
4500         EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
4501         EmitHint[EmitHint["Expression"] = 1] = "Expression";
4502         EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
4503         EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
4504         EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
4505         EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
4506         EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
4507     })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
4508     /* @internal */
4509     var LexicalEnvironmentFlags;
4510     (function (LexicalEnvironmentFlags) {
4511         LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None";
4512         LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters";
4513         LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list
4514     })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {}));
4515     /*@internal*/
4516     var BundleFileSectionKind;
4517     (function (BundleFileSectionKind) {
4518         BundleFileSectionKind["Prologue"] = "prologue";
4519         BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
4520         BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
4521         BundleFileSectionKind["Reference"] = "reference";
4522         BundleFileSectionKind["Type"] = "type";
4523         BundleFileSectionKind["Lib"] = "lib";
4524         BundleFileSectionKind["Prepend"] = "prepend";
4525         BundleFileSectionKind["Text"] = "text";
4526         BundleFileSectionKind["Internal"] = "internal";
4527         // comments?
4528     })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
4529     var ListFormat;
4530     (function (ListFormat) {
4531         ListFormat[ListFormat["None"] = 0] = "None";
4532         // Line separators
4533         ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
4534         ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
4535         ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
4536         ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
4537         // Delimiters
4538         ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
4539         ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
4540         ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
4541         ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
4542         ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
4543         ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
4544         ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
4545         // Whitespace
4546         ListFormat[ListFormat["Indented"] = 128] = "Indented";
4547         ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
4548         ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
4549         // Brackets/Braces
4550         ListFormat[ListFormat["Braces"] = 1024] = "Braces";
4551         ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
4552         ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
4553         ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
4554         ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
4555         ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
4556         ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
4557         ListFormat[ListFormat["Optional"] = 49152] = "Optional";
4558         // Other
4559         ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
4560         ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
4561         ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
4562         ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
4563         ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
4564         ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList";
4565         // Precomputed Formats
4566         ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
4567         ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
4568         ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
4569         ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
4570         ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements";
4571         ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
4572         ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
4573         ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
4574         ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
4575         ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
4576         ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
4577         ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
4578         ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
4579         ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
4580         ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
4581         ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
4582         ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
4583         ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
4584         ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
4585         ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
4586         ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
4587         ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
4588         ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
4589         ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
4590         ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
4591         ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
4592         ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
4593         ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
4594         ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
4595         ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
4596         ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
4597         ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators";
4598         ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
4599         ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
4600         ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
4601         ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
4602         ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
4603     })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
4604     /* @internal */
4605     var PragmaKindFlags;
4606     (function (PragmaKindFlags) {
4607         PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
4608         /**
4609          * Triple slash comment of the form
4610          * /// <pragma-name argname="value" />
4611          */
4612         PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
4613         /**
4614          * Single line comment of the form
4615          * // @pragma-name argval1 argval2
4616          * or
4617          * /// @pragma-name argval1 argval2
4618          */
4619         PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
4620         /**
4621          * Multiline non-jsdoc pragma of the form
4622          * /* @pragma-name argval1 argval2 * /
4623          */
4624         PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
4625         PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
4626         PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
4627     })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
4628     // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
4629     //  fancy effectively defining it twice, once in value-space and once in type-space
4630     /* @internal */
4631     ts.commentPragmas = {
4632         "reference": {
4633             args: [
4634                 { name: "types", optional: true, captureSpan: true },
4635                 { name: "lib", optional: true, captureSpan: true },
4636                 { name: "path", optional: true, captureSpan: true },
4637                 { name: "no-default-lib", optional: true }
4638             ],
4639             kind: 1 /* TripleSlashXML */
4640         },
4641         "amd-dependency": {
4642             args: [{ name: "path" }, { name: "name", optional: true }],
4643             kind: 1 /* TripleSlashXML */
4644         },
4645         "amd-module": {
4646             args: [{ name: "name" }],
4647             kind: 1 /* TripleSlashXML */
4648         },
4649         "ts-check": {
4650             kind: 2 /* SingleLine */
4651         },
4652         "ts-nocheck": {
4653             kind: 2 /* SingleLine */
4654         },
4655         "jsx": {
4656             args: [{ name: "factory" }],
4657             kind: 4 /* MultiLine */
4658         },
4659     };
4660 })(ts || (ts = {}));
4661 var ts;
4662 (function (ts) {
4663     /**
4664      * djb2 hashing algorithm
4665      * http://www.cse.yorku.ca/~oz/hash.html
4666      */
4667     /* @internal */
4668     function generateDjb2Hash(data) {
4669         var acc = 5381;
4670         for (var i = 0; i < data.length; i++) {
4671             acc = ((acc << 5) + acc) + data.charCodeAt(i);
4672         }
4673         return acc.toString();
4674     }
4675     ts.generateDjb2Hash = generateDjb2Hash;
4676     /**
4677      * Set a high stack trace limit to provide more information in case of an error.
4678      * Called for command-line and server use cases.
4679      * Not called if TypeScript is used as a library.
4680      */
4681     /* @internal */
4682     function setStackTraceLimit() {
4683         if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
4684             Error.stackTraceLimit = 100;
4685         }
4686     }
4687     ts.setStackTraceLimit = setStackTraceLimit;
4688     var FileWatcherEventKind;
4689     (function (FileWatcherEventKind) {
4690         FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
4691         FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
4692         FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
4693     })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
4694     /* @internal */
4695     var PollingInterval;
4696     (function (PollingInterval) {
4697         PollingInterval[PollingInterval["High"] = 2000] = "High";
4698         PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
4699         PollingInterval[PollingInterval["Low"] = 250] = "Low";
4700     })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
4701     /* @internal */
4702     ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
4703     function createPollingIntervalBasedLevels(levels) {
4704         var _a;
4705         return _a = {},
4706             _a[PollingInterval.Low] = levels.Low,
4707             _a[PollingInterval.Medium] = levels.Medium,
4708             _a[PollingInterval.High] = levels.High,
4709             _a;
4710     }
4711     var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
4712     var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
4713     /* @internal */
4714     ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
4715     /* @internal */
4716     function setCustomPollingValues(system) {
4717         if (!system.getEnvironmentVariable) {
4718             return;
4719         }
4720         var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
4721         pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
4722         ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
4723         function getLevel(envVar, level) {
4724             return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
4725         }
4726         function getCustomLevels(baseVariable) {
4727             var customLevels;
4728             setCustomLevel("Low");
4729             setCustomLevel("Medium");
4730             setCustomLevel("High");
4731             return customLevels;
4732             function setCustomLevel(level) {
4733                 var customLevel = getLevel(baseVariable, level);
4734                 if (customLevel) {
4735                     (customLevels || (customLevels = {}))[level] = Number(customLevel);
4736                 }
4737             }
4738         }
4739         function setCustomLevels(baseVariable, levels) {
4740             var customLevels = getCustomLevels(baseVariable);
4741             if (customLevels) {
4742                 setLevel("Low");
4743                 setLevel("Medium");
4744                 setLevel("High");
4745                 return true;
4746             }
4747             return false;
4748             function setLevel(level) {
4749                 levels[level] = customLevels[level] || levels[level];
4750             }
4751         }
4752         function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
4753             var customLevels = getCustomLevels(baseVariable);
4754             return (pollingIntervalChanged || customLevels) &&
4755                 createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
4756         }
4757     }
4758     ts.setCustomPollingValues = setCustomPollingValues;
4759     /* @internal */
4760     function createDynamicPriorityPollingWatchFile(host) {
4761         var watchedFiles = [];
4762         var changedFilesInLastPoll = [];
4763         var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
4764         var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
4765         var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
4766         return watchFile;
4767         function watchFile(fileName, callback, defaultPollingInterval) {
4768             var file = {
4769                 fileName: fileName,
4770                 callback: callback,
4771                 unchangedPolls: 0,
4772                 mtime: getModifiedTime(fileName)
4773             };
4774             watchedFiles.push(file);
4775             addToPollingIntervalQueue(file, defaultPollingInterval);
4776             return {
4777                 close: function () {
4778                     file.isClosed = true;
4779                     // Remove from watchedFiles
4780                     ts.unorderedRemoveItem(watchedFiles, file);
4781                     // Do not update polling interval queue since that will happen as part of polling
4782                 }
4783             };
4784         }
4785         function createPollingIntervalQueue(pollingInterval) {
4786             var queue = [];
4787             queue.pollingInterval = pollingInterval;
4788             queue.pollIndex = 0;
4789             queue.pollScheduled = false;
4790             return queue;
4791         }
4792         function pollPollingIntervalQueue(queue) {
4793             queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
4794             // Set the next polling index and timeout
4795             if (queue.length) {
4796                 scheduleNextPoll(queue.pollingInterval);
4797             }
4798             else {
4799                 ts.Debug.assert(queue.pollIndex === 0);
4800                 queue.pollScheduled = false;
4801             }
4802         }
4803         function pollLowPollingIntervalQueue(queue) {
4804             // Always poll complete list of changedFilesInLastPoll
4805             pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
4806             // Finally do the actual polling of the queue
4807             pollPollingIntervalQueue(queue);
4808             // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
4809             // as pollPollingIntervalQueue wont schedule for next poll
4810             if (!queue.pollScheduled && changedFilesInLastPoll.length) {
4811                 scheduleNextPoll(PollingInterval.Low);
4812             }
4813         }
4814         function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
4815             // Max visit would be all elements of the queue
4816             var needsVisit = queue.length;
4817             var definedValueCopyToIndex = pollIndex;
4818             for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
4819                 var watchedFile = queue[pollIndex];
4820                 if (!watchedFile) {
4821                     continue;
4822                 }
4823                 else if (watchedFile.isClosed) {
4824                     queue[pollIndex] = undefined;
4825                     continue;
4826                 }
4827                 polled++;
4828                 var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
4829                 if (watchedFile.isClosed) {
4830                     // Closed watcher as part of callback
4831                     queue[pollIndex] = undefined;
4832                 }
4833                 else if (fileChanged) {
4834                     watchedFile.unchangedPolls = 0;
4835                     // Changed files go to changedFilesInLastPoll queue
4836                     if (queue !== changedFilesInLastPoll) {
4837                         queue[pollIndex] = undefined;
4838                         addChangedFileToLowPollingIntervalQueue(watchedFile);
4839                     }
4840                 }
4841                 else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
4842                     watchedFile.unchangedPolls++;
4843                 }
4844                 else if (queue === changedFilesInLastPoll) {
4845                     // Restart unchangedPollCount for unchanged file and move to low polling interval queue
4846                     watchedFile.unchangedPolls = 1;
4847                     queue[pollIndex] = undefined;
4848                     addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
4849                 }
4850                 else if (pollingInterval !== PollingInterval.High) {
4851                     watchedFile.unchangedPolls++;
4852                     queue[pollIndex] = undefined;
4853                     addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
4854                 }
4855                 if (queue[pollIndex]) {
4856                     // Copy this file to the non hole location
4857                     if (definedValueCopyToIndex < pollIndex) {
4858                         queue[definedValueCopyToIndex] = watchedFile;
4859                         queue[pollIndex] = undefined;
4860                     }
4861                     definedValueCopyToIndex++;
4862                 }
4863             }
4864             // Return next poll index
4865             return pollIndex;
4866             function nextPollIndex() {
4867                 pollIndex++;
4868                 if (pollIndex === queue.length) {
4869                     if (definedValueCopyToIndex < pollIndex) {
4870                         // There are holes from nextDefinedValueIndex to end of queue, change queue size
4871                         queue.length = definedValueCopyToIndex;
4872                     }
4873                     pollIndex = 0;
4874                     definedValueCopyToIndex = 0;
4875                 }
4876             }
4877         }
4878         function pollingIntervalQueue(pollingInterval) {
4879             switch (pollingInterval) {
4880                 case PollingInterval.Low:
4881                     return lowPollingIntervalQueue;
4882                 case PollingInterval.Medium:
4883                     return mediumPollingIntervalQueue;
4884                 case PollingInterval.High:
4885                     return highPollingIntervalQueue;
4886             }
4887         }
4888         function addToPollingIntervalQueue(file, pollingInterval) {
4889             pollingIntervalQueue(pollingInterval).push(file);
4890             scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
4891         }
4892         function addChangedFileToLowPollingIntervalQueue(file) {
4893             changedFilesInLastPoll.push(file);
4894             scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
4895         }
4896         function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
4897             if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
4898                 scheduleNextPoll(pollingInterval);
4899             }
4900         }
4901         function scheduleNextPoll(pollingInterval) {
4902             pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
4903         }
4904         function getModifiedTime(fileName) {
4905             return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
4906         }
4907     }
4908     ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
4909     function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
4910         // One file can have multiple watchers
4911         var fileWatcherCallbacks = ts.createMultiMap();
4912         var dirWatchers = ts.createMap();
4913         var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
4914         return nonPollingWatchFile;
4915         function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
4916             var filePath = toCanonicalName(fileName);
4917             fileWatcherCallbacks.add(filePath, callback);
4918             var dirPath = ts.getDirectoryPath(filePath) || ".";
4919             var watcher = dirWatchers.get(dirPath) ||
4920                 createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
4921             watcher.referenceCount++;
4922             return {
4923                 close: function () {
4924                     if (watcher.referenceCount === 1) {
4925                         watcher.close();
4926                         dirWatchers.delete(dirPath);
4927                     }
4928                     else {
4929                         watcher.referenceCount--;
4930                     }
4931                     fileWatcherCallbacks.remove(filePath, callback);
4932                 }
4933             };
4934         }
4935         function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
4936             var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
4937                 // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
4938                 if (!ts.isString(relativeFileName)) {
4939                     return;
4940                 }
4941                 var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
4942                 // Some applications save a working file via rename operations
4943                 var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
4944                 if (callbacks) {
4945                     for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
4946                         var fileCallback = callbacks_1[_i];
4947                         fileCallback(fileName, FileWatcherEventKind.Changed);
4948                     }
4949                 }
4950             }, 
4951             /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
4952             watcher.referenceCount = 0;
4953             dirWatchers.set(dirPath, watcher);
4954             return watcher;
4955         }
4956     }
4957     /* @internal */
4958     function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
4959         var cache = ts.createMap();
4960         var callbacksCache = ts.createMultiMap();
4961         var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
4962         return function (fileName, callback, pollingInterval, options) {
4963             var path = toCanonicalFileName(fileName);
4964             var existing = cache.get(path);
4965             if (existing) {
4966                 existing.refCount++;
4967             }
4968             else {
4969                 cache.set(path, {
4970                     watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
4971                     refCount: 1
4972                 });
4973             }
4974             callbacksCache.add(path, callback);
4975             return {
4976                 close: function () {
4977                     var watcher = ts.Debug.checkDefined(cache.get(path));
4978                     callbacksCache.remove(path, callback);
4979                     watcher.refCount--;
4980                     if (watcher.refCount)
4981                         return;
4982                     cache.delete(path);
4983                     ts.closeFileWatcherOf(watcher);
4984                 }
4985             };
4986         };
4987     }
4988     ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
4989     /**
4990      * Returns true if file status changed
4991      */
4992     /*@internal*/
4993     function onWatchedFileStat(watchedFile, modifiedTime) {
4994         var oldTime = watchedFile.mtime.getTime();
4995         var newTime = modifiedTime.getTime();
4996         if (oldTime !== newTime) {
4997             watchedFile.mtime = modifiedTime;
4998             watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
4999             return true;
5000         }
5001         return false;
5002     }
5003     ts.onWatchedFileStat = onWatchedFileStat;
5004     /*@internal*/
5005     function getFileWatcherEventKind(oldTime, newTime) {
5006         return oldTime === 0
5007             ? FileWatcherEventKind.Created
5008             : newTime === 0
5009                 ? FileWatcherEventKind.Deleted
5010                 : FileWatcherEventKind.Changed;
5011     }
5012     ts.getFileWatcherEventKind = getFileWatcherEventKind;
5013     /*@internal*/
5014     ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
5015     /*@internal*/
5016     ts.sysLog = ts.noop; // eslint-disable-line prefer-const
5017     /*@internal*/
5018     function setSysLog(logger) {
5019         ts.sysLog = logger;
5020     }
5021     ts.setSysLog = setSysLog;
5022     /**
5023      * Watch the directory recursively using host provided method to watch child directories
5024      * that means if this is recursive watcher, watch the children directories as well
5025      * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
5026      */
5027     /*@internal*/
5028     function createDirectoryWatcherSupportingRecursive(host) {
5029         var cache = ts.createMap();
5030         var callbackCache = ts.createMultiMap();
5031         var cacheToUpdateChildWatches = ts.createMap();
5032         var timerToUpdateChildWatches;
5033         var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
5034         var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
5035         return function (dirName, callback, recursive, options) { return recursive ?
5036             createDirectoryWatcher(dirName, options, callback) :
5037             host.watchDirectory(dirName, callback, recursive, options); };
5038         /**
5039          * Create the directory watcher for the dirPath.
5040          */
5041         function createDirectoryWatcher(dirName, options, callback) {
5042             var dirPath = toCanonicalFilePath(dirName);
5043             var directoryWatcher = cache.get(dirPath);
5044             if (directoryWatcher) {
5045                 directoryWatcher.refCount++;
5046             }
5047             else {
5048                 directoryWatcher = {
5049                     watcher: host.watchDirectory(dirName, function (fileName) {
5050                         if (isIgnoredPath(fileName))
5051                             return;
5052                         if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
5053                             // Call the actual callback
5054                             invokeCallbacks(dirPath, fileName);
5055                             // Iterate through existing children and update the watches if needed
5056                             updateChildWatches(dirName, dirPath, options);
5057                         }
5058                         else {
5059                             nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
5060                         }
5061                     }, /*recursive*/ false, options),
5062                     refCount: 1,
5063                     childWatches: ts.emptyArray
5064                 };
5065                 cache.set(dirPath, directoryWatcher);
5066                 updateChildWatches(dirName, dirPath, options);
5067             }
5068             var callbackToAdd = callback && { dirName: dirName, callback: callback };
5069             if (callbackToAdd) {
5070                 callbackCache.add(dirPath, callbackToAdd);
5071             }
5072             return {
5073                 dirName: dirName,
5074                 close: function () {
5075                     var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
5076                     if (callbackToAdd)
5077                         callbackCache.remove(dirPath, callbackToAdd);
5078                     directoryWatcher.refCount--;
5079                     if (directoryWatcher.refCount)
5080                         return;
5081                     cache.delete(dirPath);
5082                     ts.closeFileWatcherOf(directoryWatcher);
5083                     directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
5084                 }
5085             };
5086         }
5087         function invokeCallbacks(dirPath, fileNameOrInvokeMap) {
5088             var fileName;
5089             var invokeMap;
5090             if (ts.isString(fileNameOrInvokeMap)) {
5091                 fileName = fileNameOrInvokeMap;
5092             }
5093             else {
5094                 invokeMap = fileNameOrInvokeMap;
5095             }
5096             // Call the actual callback
5097             callbackCache.forEach(function (callbacks, rootDirName) {
5098                 if (invokeMap && invokeMap.has(rootDirName))
5099                     return;
5100                 if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
5101                     if (invokeMap) {
5102                         invokeMap.set(rootDirName, true);
5103                     }
5104                     else {
5105                         callbacks.forEach(function (_a) {
5106                             var callback = _a.callback;
5107                             return callback(fileName);
5108                         });
5109                     }
5110                 }
5111             });
5112         }
5113         function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
5114             // Iterate through existing children and update the watches if needed
5115             var parentWatcher = cache.get(dirPath);
5116             if (parentWatcher && host.directoryExists(dirName)) {
5117                 // Schedule the update and postpone invoke for callbacks
5118                 scheduleUpdateChildWatches(dirName, dirPath, options);
5119                 return;
5120             }
5121             // Call the actual callbacks and remove child watches
5122             invokeCallbacks(dirPath, fileName);
5123             removeChildWatches(parentWatcher);
5124         }
5125         function scheduleUpdateChildWatches(dirName, dirPath, options) {
5126             if (!cacheToUpdateChildWatches.has(dirPath)) {
5127                 cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options });
5128             }
5129             if (timerToUpdateChildWatches) {
5130                 host.clearTimeout(timerToUpdateChildWatches);
5131                 timerToUpdateChildWatches = undefined;
5132             }
5133             timerToUpdateChildWatches = host.setTimeout(onTimerToUpdateChildWatches, 1000);
5134         }
5135         function onTimerToUpdateChildWatches() {
5136             timerToUpdateChildWatches = undefined;
5137             ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size);
5138             var start = ts.timestamp();
5139             var invokeMap = ts.createMap();
5140             while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
5141                 var _a = cacheToUpdateChildWatches.entries().next(), _b = _a.value, dirPath = _b[0], _c = _b[1], dirName = _c.dirName, options = _c.options, done = _a.done;
5142                 ts.Debug.assert(!done);
5143                 cacheToUpdateChildWatches.delete(dirPath);
5144                 // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
5145                 // to ensure that all the changes are reflected at this time
5146                 invokeCallbacks(dirPath, invokeMap);
5147                 updateChildWatches(dirName, dirPath, options);
5148             }
5149             ts.sysLog("sysLog:: invokingWatchers:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
5150             callbackCache.forEach(function (callbacks, rootDirName) {
5151                 if (invokeMap.has(rootDirName)) {
5152                     callbacks.forEach(function (_a) {
5153                         var callback = _a.callback, dirName = _a.dirName;
5154                         return callback(dirName);
5155                     });
5156                 }
5157             });
5158             var elapsed = ts.timestamp() - start;
5159             ts.sysLog("sysLog:: Elapsed " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
5160         }
5161         function removeChildWatches(parentWatcher) {
5162             if (!parentWatcher)
5163                 return;
5164             var existingChildWatches = parentWatcher.childWatches;
5165             parentWatcher.childWatches = ts.emptyArray;
5166             for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
5167                 var childWatcher = existingChildWatches_1[_i];
5168                 childWatcher.close();
5169                 removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
5170             }
5171         }
5172         function updateChildWatches(dirName, dirPath, options) {
5173             // Iterate through existing children and update the watches if needed
5174             var parentWatcher = cache.get(dirPath);
5175             if (parentWatcher) {
5176                 parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches, options);
5177             }
5178         }
5179         /**
5180          * Watch the directories in the parentDir
5181          */
5182         function watchChildDirectories(parentDir, existingChildWatches, options) {
5183             var newChildWatches;
5184             ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
5185                 var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
5186                 // Filter our the symbolic link directories since those arent included in recursive watch
5187                 // which is same behaviour when recursive: true is passed to fs.watch
5188                 return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
5189             }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
5190             return newChildWatches || ts.emptyArray;
5191             /**
5192              * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
5193              */
5194             function createAndAddChildDirectoryWatcher(childName) {
5195                 var result = createDirectoryWatcher(childName, options);
5196                 addChildDirectoryWatcher(result);
5197             }
5198             /**
5199              * Add child directory watcher to the new ChildDirectoryWatcher list
5200              */
5201             function addChildDirectoryWatcher(childWatcher) {
5202                 (newChildWatches || (newChildWatches = [])).push(childWatcher);
5203             }
5204         }
5205         function isIgnoredPath(path) {
5206             return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
5207         }
5208         function isInPath(path, searchPath) {
5209             if (ts.stringContains(path, searchPath))
5210                 return true;
5211             if (host.useCaseSensitiveFileNames)
5212                 return false;
5213             return ts.stringContains(toCanonicalFilePath(path), searchPath);
5214         }
5215     }
5216     ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
5217     /*@internal*/
5218     var FileSystemEntryKind;
5219     (function (FileSystemEntryKind) {
5220         FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
5221         FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
5222     })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
5223     /*@internal*/
5224     function createFileWatcherCallback(callback) {
5225         return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
5226     }
5227     ts.createFileWatcherCallback = createFileWatcherCallback;
5228     function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
5229         return function (eventName) {
5230             if (eventName === "rename") {
5231                 callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
5232             }
5233             else {
5234                 // Change
5235                 callback(fileName, FileWatcherEventKind.Changed);
5236             }
5237         };
5238     }
5239     function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
5240         return function (eventName, relativeFileName) {
5241             // In watchDirectory we only care about adding and removing files (when event name is
5242             // "rename"); changes made within files are handled by corresponding fileWatchers (when
5243             // event name is "change")
5244             if (eventName === "rename") {
5245                 // When deleting a file, the passed baseFileName is null
5246                 callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
5247             }
5248         };
5249     }
5250     /*@internal*/
5251     function createSystemWatchFunctions(_a) {
5252         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;
5253         var dynamicPollingWatchFile;
5254         var nonPollingWatchFile;
5255         var hostRecursiveDirectoryWatcher;
5256         return {
5257             watchFile: watchFile,
5258             watchDirectory: watchDirectory
5259         };
5260         function watchFile(fileName, callback, pollingInterval, options) {
5261             options = updateOptionsForWatchFile(options, useNonPollingWatchers);
5262             var watchFileKind = ts.Debug.checkDefined(options.watchFile);
5263             switch (watchFileKind) {
5264                 case ts.WatchFileKind.FixedPollingInterval:
5265                     return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
5266                 case ts.WatchFileKind.PriorityPollingInterval:
5267                     return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
5268                 case ts.WatchFileKind.DynamicPriorityPolling:
5269                     return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
5270                 case ts.WatchFileKind.UseFsEvents:
5271                     return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), 
5272                     /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
5273                 case ts.WatchFileKind.UseFsEventsOnParentDirectory:
5274                     if (!nonPollingWatchFile) {
5275                         nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
5276                     }
5277                     return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
5278                 default:
5279                     ts.Debug.assertNever(watchFileKind);
5280             }
5281         }
5282         function ensureDynamicPollingWatchFile() {
5283             return dynamicPollingWatchFile ||
5284                 (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
5285         }
5286         function updateOptionsForWatchFile(options, useNonPollingWatchers) {
5287             if (options && options.watchFile !== undefined)
5288                 return options;
5289             switch (tscWatchFile) {
5290                 case "PriorityPollingInterval":
5291                     // Use polling interval based on priority when create watch using host.watchFile
5292                     return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
5293                 case "DynamicPriorityPolling":
5294                     // Use polling interval but change the interval depending on file changes and their default polling interval
5295                     return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
5296                 case "UseFsEvents":
5297                     // Use notifications from FS to watch with falling back to fs.watchFile
5298                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
5299                 case "UseFsEventsWithFallbackDynamicPolling":
5300                     // Use notifications from FS to watch with falling back to dynamic watch file
5301                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
5302                 case "UseFsEventsOnParentDirectory":
5303                     useNonPollingWatchers = true;
5304                 // fall through
5305                 default:
5306                     return useNonPollingWatchers ?
5307                         // Use notifications from FS to watch with falling back to fs.watchFile
5308                         generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
5309                         // Default to do not use fixed polling interval
5310                         { watchFile: ts.WatchFileKind.FixedPollingInterval };
5311             }
5312         }
5313         function generateWatchFileOptions(watchFile, fallbackPolling, options) {
5314             var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5315             return {
5316                 watchFile: watchFile,
5317                 fallbackPolling: defaultFallbackPolling === undefined ?
5318                     fallbackPolling :
5319                     defaultFallbackPolling
5320             };
5321         }
5322         function watchDirectory(directoryName, callback, recursive, options) {
5323             if (fsSupportsRecursiveFsWatch) {
5324                 return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5325             }
5326             if (!hostRecursiveDirectoryWatcher) {
5327                 hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
5328                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5329                     directoryExists: directoryExists,
5330                     getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
5331                     watchDirectory: nonRecursiveWatchDirectory,
5332                     realpath: realpath,
5333                     setTimeout: setTimeout,
5334                     clearTimeout: clearTimeout
5335                 });
5336             }
5337             return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
5338         }
5339         function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
5340             ts.Debug.assert(!recursive);
5341             options = updateOptionsForWatchDirectory(options);
5342             var watchDirectoryKind = ts.Debug.checkDefined(options.watchDirectory);
5343             switch (watchDirectoryKind) {
5344                 case ts.WatchDirectoryKind.FixedPollingInterval:
5345                     return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
5346                     /*options*/ undefined);
5347                 case ts.WatchDirectoryKind.DynamicPriorityPolling:
5348                     return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
5349                     /*options*/ undefined);
5350                 case ts.WatchDirectoryKind.UseFsEvents:
5351                     return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5352                 default:
5353                     ts.Debug.assertNever(watchDirectoryKind);
5354             }
5355         }
5356         function updateOptionsForWatchDirectory(options) {
5357             if (options && options.watchDirectory !== undefined)
5358                 return options;
5359             switch (tscWatchDirectory) {
5360                 case "RecursiveDirectoryUsingFsWatchFile":
5361                     // Use polling interval based on priority when create watch using host.watchFile
5362                     return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
5363                 case "RecursiveDirectoryUsingDynamicPriorityPolling":
5364                     // Use polling interval but change the interval depending on file changes and their default polling interval
5365                     return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
5366                 default:
5367                     var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5368                     return {
5369                         watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
5370                         fallbackPolling: defaultFallbackPolling !== undefined ?
5371                             defaultFallbackPolling :
5372                             undefined
5373                     };
5374             }
5375         }
5376     }
5377     ts.createSystemWatchFunctions = createSystemWatchFunctions;
5378     /**
5379      * patch writefile to create folder before writing the file
5380      */
5381     /*@internal*/
5382     function patchWriteFileEnsuringDirectory(sys) {
5383         // patch writefile to create folder before writing the file
5384         var originalWriteFile = sys.writeFile;
5385         sys.writeFile = function (path, data, writeBom) {
5386             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); });
5387         };
5388     }
5389     ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
5390     function getNodeMajorVersion() {
5391         if (typeof process === "undefined") {
5392             return undefined;
5393         }
5394         var version = process.version;
5395         if (!version) {
5396             return undefined;
5397         }
5398         var dot = version.indexOf(".");
5399         if (dot === -1) {
5400             return undefined;
5401         }
5402         return parseInt(version.substring(1, dot));
5403     }
5404     ts.getNodeMajorVersion = getNodeMajorVersion;
5405     // TODO: GH#18217 this is used as if it's certainly defined in many places.
5406     // eslint-disable-next-line prefer-const
5407     ts.sys = (function () {
5408         // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
5409         // byte order mark from the specified encoding. Using any other byte order mark does
5410         // not actually work.
5411         var byteOrderMarkIndicator = "\uFEFF";
5412         function getNodeSystem() {
5413             var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
5414             var _fs = require("fs");
5415             var _path = require("path");
5416             var _os = require("os");
5417             // crypto can be absent on reduced node installations
5418             var _crypto;
5419             try {
5420                 _crypto = require("crypto");
5421             }
5422             catch (_a) {
5423                 _crypto = undefined;
5424             }
5425             var activeSession;
5426             var profilePath = "./profile.cpuprofile";
5427             var Buffer = require("buffer").Buffer;
5428             var nodeVersion = getNodeMajorVersion();
5429             var isNode4OrLater = nodeVersion >= 4;
5430             var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
5431             var platform = _os.platform();
5432             var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
5433             var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
5434             var _b = createSystemWatchFunctions({
5435                 pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
5436                 getModifiedTime: getModifiedTime,
5437                 setTimeout: setTimeout,
5438                 clearTimeout: clearTimeout,
5439                 fsWatch: fsWatch,
5440                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5441                 fileExists: fileExists,
5442                 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
5443                 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
5444                 fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
5445                 directoryExists: directoryExists,
5446                 getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
5447                 realpath: realpath,
5448                 tscWatchFile: process.env.TSC_WATCHFILE,
5449                 useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
5450                 tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
5451             }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory;
5452             var nodeSystem = {
5453                 args: process.argv.slice(2),
5454                 newLine: _os.EOL,
5455                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5456                 write: function (s) {
5457                     process.stdout.write(s);
5458                 },
5459                 writeOutputIsTTY: function () {
5460                     return process.stdout.isTTY;
5461                 },
5462                 readFile: readFile,
5463                 writeFile: writeFile,
5464                 watchFile: watchFile,
5465                 watchDirectory: watchDirectory,
5466                 resolvePath: function (path) { return _path.resolve(path); },
5467                 fileExists: fileExists,
5468                 directoryExists: directoryExists,
5469                 createDirectory: function (directoryName) {
5470                     if (!nodeSystem.directoryExists(directoryName)) {
5471                         // Wrapped in a try-catch to prevent crashing if we are in a race
5472                         // with another copy of ourselves to create the same directory
5473                         try {
5474                             _fs.mkdirSync(directoryName);
5475                         }
5476                         catch (e) {
5477                             if (e.code !== "EEXIST") {
5478                                 // Failed for some other reason (access denied?); still throw
5479                                 throw e;
5480                             }
5481                         }
5482                     }
5483                 },
5484                 getExecutingFilePath: function () {
5485                     return __filename;
5486                 },
5487                 getCurrentDirectory: function () {
5488                     return process.cwd();
5489                 },
5490                 getDirectories: getDirectories,
5491                 getEnvironmentVariable: function (name) {
5492                     return process.env[name] || "";
5493                 },
5494                 readDirectory: readDirectory,
5495                 getModifiedTime: getModifiedTime,
5496                 setModifiedTime: setModifiedTime,
5497                 deleteFile: deleteFile,
5498                 createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
5499                 createSHA256Hash: _crypto ? createSHA256Hash : undefined,
5500                 getMemoryUsage: function () {
5501                     if (global.gc) {
5502                         global.gc();
5503                     }
5504                     return process.memoryUsage().heapUsed;
5505                 },
5506                 getFileSize: function (path) {
5507                     try {
5508                         var stat = _fs.statSync(path);
5509                         if (stat.isFile()) {
5510                             return stat.size;
5511                         }
5512                     }
5513                     catch ( /*ignore*/_a) { /*ignore*/ }
5514                     return 0;
5515                 },
5516                 exit: function (exitCode) {
5517                     disableCPUProfiler(function () { return process.exit(exitCode); });
5518                 },
5519                 enableCPUProfiler: enableCPUProfiler,
5520                 disableCPUProfiler: disableCPUProfiler,
5521                 realpath: realpath,
5522                 debugMode: !!process.env.NODE_INSPECTOR_IPC || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
5523                 tryEnableSourceMapsForHost: function () {
5524                     try {
5525                         require("source-map-support").install();
5526                     }
5527                     catch (_a) {
5528                         // Could not enable source maps.
5529                     }
5530                 },
5531                 setTimeout: setTimeout,
5532                 clearTimeout: clearTimeout,
5533                 clearScreen: function () {
5534                     process.stdout.write("\x1Bc");
5535                 },
5536                 setBlocking: function () {
5537                     if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
5538                         process.stdout._handle.setBlocking(true);
5539                     }
5540                 },
5541                 bufferFrom: bufferFrom,
5542                 base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
5543                 base64encode: function (input) { return bufferFrom(input).toString("base64"); },
5544                 require: function (baseDir, moduleName) {
5545                     try {
5546                         var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
5547                         return { module: require(modulePath), modulePath: modulePath, error: undefined };
5548                     }
5549                     catch (error) {
5550                         return { module: undefined, modulePath: undefined, error: error };
5551                     }
5552                 }
5553             };
5554             return nodeSystem;
5555             /**
5556              * Uses the builtin inspector APIs to capture a CPU profile
5557              * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
5558              */
5559             function enableCPUProfiler(path, cb) {
5560                 if (activeSession) {
5561                     cb();
5562                     return false;
5563                 }
5564                 var inspector = require("inspector");
5565                 if (!inspector || !inspector.Session) {
5566                     cb();
5567                     return false;
5568                 }
5569                 var session = new inspector.Session();
5570                 session.connect();
5571                 session.post("Profiler.enable", function () {
5572                     session.post("Profiler.start", function () {
5573                         activeSession = session;
5574                         profilePath = path;
5575                         cb();
5576                     });
5577                 });
5578                 return true;
5579             }
5580             /**
5581              * Strips non-TS paths from the profile, so users with private projects shouldn't
5582              * need to worry about leaking paths by submitting a cpu profile to us
5583              */
5584             function cleanupPaths(profile) {
5585                 var externalFileCounter = 0;
5586                 var remappedPaths = ts.createMap();
5587                 var normalizedDir = ts.normalizeSlashes(__dirname);
5588                 // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
5589                 var fileUrlRoot = "file://" + (ts.getRootLength(normalizedDir) === 1 ? "" : "/") + normalizedDir;
5590                 for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
5591                     var node = _a[_i];
5592                     if (node.callFrame.url) {
5593                         var url = ts.normalizeSlashes(node.callFrame.url);
5594                         if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
5595                             node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
5596                         }
5597                         else if (!nativePattern.test(url)) {
5598                             node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external" + externalFileCounter + ".js")).get(url);
5599                             externalFileCounter++;
5600                         }
5601                     }
5602                 }
5603                 return profile;
5604             }
5605             function disableCPUProfiler(cb) {
5606                 if (activeSession && activeSession !== "stopping") {
5607                     var s_1 = activeSession;
5608                     activeSession.post("Profiler.stop", function (err, _a) {
5609                         var profile = _a.profile;
5610                         if (!err) {
5611                             try {
5612                                 if (_fs.statSync(profilePath).isDirectory()) {
5613                                     profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile");
5614                                 }
5615                             }
5616                             catch (_b) {
5617                                 // do nothing and ignore fallible fs operation
5618                             }
5619                             try {
5620                                 _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
5621                             }
5622                             catch (_c) {
5623                                 // do nothing and ignore fallible fs operation
5624                             }
5625                             _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
5626                         }
5627                         activeSession = undefined;
5628                         s_1.disconnect();
5629                         cb();
5630                     });
5631                     activeSession = "stopping";
5632                     return true;
5633                 }
5634                 else {
5635                     cb();
5636                     return false;
5637                 }
5638             }
5639             function bufferFrom(input, encoding) {
5640                 // See https://github.com/Microsoft/TypeScript/issues/25652
5641                 return Buffer.from && Buffer.from !== Int8Array.from
5642                     ? Buffer.from(input, encoding)
5643                     : new Buffer(input, encoding);
5644             }
5645             function isFileSystemCaseSensitive() {
5646                 // win32\win64 are case insensitive platforms
5647                 if (platform === "win32" || platform === "win64") {
5648                     return false;
5649                 }
5650                 // If this file exists under a different case, we must be case-insensitve.
5651                 return !fileExists(swapCase(__filename));
5652             }
5653             /** Convert all lowercase chars to uppercase, and vice-versa */
5654             function swapCase(s) {
5655                 return s.replace(/\w/g, function (ch) {
5656                     var up = ch.toUpperCase();
5657                     return ch === up ? ch.toLowerCase() : up;
5658                 });
5659             }
5660             function fsWatchFileWorker(fileName, callback, pollingInterval) {
5661                 _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
5662                 var eventKind;
5663                 return {
5664                     close: function () { return _fs.unwatchFile(fileName, fileChanged); }
5665                 };
5666                 function fileChanged(curr, prev) {
5667                     // 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)
5668                     // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
5669                     var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
5670                     if (+curr.mtime === 0) {
5671                         if (isPreviouslyDeleted) {
5672                             // Already deleted file, no need to callback again
5673                             return;
5674                         }
5675                         eventKind = FileWatcherEventKind.Deleted;
5676                     }
5677                     else if (isPreviouslyDeleted) {
5678                         eventKind = FileWatcherEventKind.Created;
5679                     }
5680                     // If there is no change in modified time, ignore the event
5681                     else if (+curr.mtime === +prev.mtime) {
5682                         return;
5683                     }
5684                     else {
5685                         // File changed
5686                         eventKind = FileWatcherEventKind.Changed;
5687                     }
5688                     callback(fileName, eventKind);
5689                 }
5690             }
5691             function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
5692                 var options;
5693                 var lastDirectoryPartWithDirectorySeparator;
5694                 var lastDirectoryPart;
5695                 if (isLinuxOrMacOs) {
5696                     lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
5697                     lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
5698                 }
5699                 /** Watcher for the file system entry depending on whether it is missing or present */
5700                 var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
5701                     watchMissingFileSystemEntry() :
5702                     watchPresentFileSystemEntry();
5703                 return {
5704                     close: function () {
5705                         // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
5706                         watcher.close();
5707                         watcher = undefined;
5708                     }
5709                 };
5710                 /**
5711                  * Invoke the callback with rename and update the watcher if not closed
5712                  * @param createWatcher
5713                  */
5714                 function invokeCallbackAndUpdateWatcher(createWatcher) {
5715                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing watcher to " + (createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing") + "FileSystemEntryWatcher");
5716                     // Call the callback for current directory
5717                     callback("rename", "");
5718                     // If watcher is not closed, update it
5719                     if (watcher) {
5720                         watcher.close();
5721                         watcher = createWatcher();
5722                     }
5723                 }
5724                 /**
5725                  * Watch the file or directory that is currently present
5726                  * and when the watched file or directory is deleted, switch to missing file system entry watcher
5727                  */
5728                 function watchPresentFileSystemEntry() {
5729                     // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
5730                     // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
5731                     if (options === undefined) {
5732                         if (fsSupportsRecursiveFsWatch) {
5733                             options = { persistent: true, recursive: !!recursive };
5734                         }
5735                         else {
5736                             options = { persistent: true };
5737                         }
5738                     }
5739                     try {
5740                         var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
5741                             callbackChangingToMissingFileSystemEntry :
5742                             callback);
5743                         // Watch the missing file or directory or error
5744                         presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
5745                         return presentWatcher;
5746                     }
5747                     catch (e) {
5748                         // Catch the exception and use polling instead
5749                         // 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
5750                         // so instead of throwing error, use fs.watchFile
5751                         return watchPresentFileSystemEntryWithFsWatchFile();
5752                     }
5753                 }
5754                 function callbackChangingToMissingFileSystemEntry(event, relativeName) {
5755                     // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
5756                     // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
5757                     return event === "rename" &&
5758                         (!relativeName ||
5759                             relativeName === lastDirectoryPart ||
5760                             relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) &&
5761                         !fileSystemEntryExists(fileOrDirectory, entryKind) ?
5762                         invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
5763                         callback(event, relativeName);
5764                 }
5765                 /**
5766                  * Watch the file or directory using fs.watchFile since fs.watch threw exception
5767                  * 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
5768                  */
5769                 function watchPresentFileSystemEntryWithFsWatchFile() {
5770                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing to fsWatchFile");
5771                     return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
5772                 }
5773                 /**
5774                  * Watch the file or directory that is missing
5775                  * and switch to existing file or directory when the missing filesystem entry is created
5776                  */
5777                 function watchMissingFileSystemEntry() {
5778                     return watchFile(fileOrDirectory, function (_fileName, eventKind) {
5779                         if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
5780                             // Call the callback for current file or directory
5781                             // For now it could be callback for the inner directory creation,
5782                             // but just return current directory, better than current no-op
5783                             invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
5784                         }
5785                     }, fallbackPollingInterval, fallbackOptions);
5786                 }
5787             }
5788             function readFileWorker(fileName, _encoding) {
5789                 var buffer;
5790                 try {
5791                     buffer = _fs.readFileSync(fileName);
5792                 }
5793                 catch (e) {
5794                     return undefined;
5795                 }
5796                 var len = buffer.length;
5797                 if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
5798                     // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
5799                     // flip all byte pairs and treat as little endian.
5800                     len &= ~1; // Round down to a multiple of 2
5801                     for (var i = 0; i < len; i += 2) {
5802                         var temp = buffer[i];
5803                         buffer[i] = buffer[i + 1];
5804                         buffer[i + 1] = temp;
5805                     }
5806                     return buffer.toString("utf16le", 2);
5807                 }
5808                 if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
5809                     // Little endian UTF-16 byte order mark detected
5810                     return buffer.toString("utf16le", 2);
5811                 }
5812                 if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
5813                     // UTF-8 byte order mark detected
5814                     return buffer.toString("utf8", 3);
5815                 }
5816                 // Default is UTF-8 with no byte order mark
5817                 return buffer.toString("utf8");
5818             }
5819             function readFile(fileName, _encoding) {
5820                 ts.perfLogger.logStartReadFile(fileName);
5821                 var file = readFileWorker(fileName, _encoding);
5822                 ts.perfLogger.logStopReadFile();
5823                 return file;
5824             }
5825             function writeFile(fileName, data, writeByteOrderMark) {
5826                 ts.perfLogger.logEvent("WriteFile: " + fileName);
5827                 // If a BOM is required, emit one
5828                 if (writeByteOrderMark) {
5829                     data = byteOrderMarkIndicator + data;
5830                 }
5831                 var fd;
5832                 try {
5833                     fd = _fs.openSync(fileName, "w");
5834                     _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
5835                 }
5836                 finally {
5837                     if (fd !== undefined) {
5838                         _fs.closeSync(fd);
5839                     }
5840                 }
5841             }
5842             function getAccessibleFileSystemEntries(path) {
5843                 ts.perfLogger.logEvent("ReadDir: " + (path || "."));
5844                 try {
5845                     var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
5846                     var files = [];
5847                     var directories = [];
5848                     for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) {
5849                         var dirent = entries_2[_i];
5850                         // withFileTypes is not supported before Node 10.10.
5851                         var entry = typeof dirent === "string" ? dirent : dirent.name;
5852                         // This is necessary because on some file system node fails to exclude
5853                         // "." and "..". See https://github.com/nodejs/node/issues/4002
5854                         if (entry === "." || entry === "..") {
5855                             continue;
5856                         }
5857                         var stat = void 0;
5858                         if (typeof dirent === "string" || dirent.isSymbolicLink()) {
5859                             var name = ts.combinePaths(path, entry);
5860                             try {
5861                                 stat = _fs.statSync(name);
5862                             }
5863                             catch (e) {
5864                                 continue;
5865                             }
5866                         }
5867                         else {
5868                             stat = dirent;
5869                         }
5870                         if (stat.isFile()) {
5871                             files.push(entry);
5872                         }
5873                         else if (stat.isDirectory()) {
5874                             directories.push(entry);
5875                         }
5876                     }
5877                     files.sort();
5878                     directories.sort();
5879                     return { files: files, directories: directories };
5880                 }
5881                 catch (e) {
5882                     return ts.emptyFileSystemEntries;
5883                 }
5884             }
5885             function readDirectory(path, extensions, excludes, includes, depth) {
5886                 return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
5887             }
5888             function fileSystemEntryExists(path, entryKind) {
5889                 try {
5890                     var stat = _fs.statSync(path);
5891                     switch (entryKind) {
5892                         case 0 /* File */: return stat.isFile();
5893                         case 1 /* Directory */: return stat.isDirectory();
5894                         default: return false;
5895                     }
5896                 }
5897                 catch (e) {
5898                     return false;
5899                 }
5900             }
5901             function fileExists(path) {
5902                 return fileSystemEntryExists(path, 0 /* File */);
5903             }
5904             function directoryExists(path) {
5905                 return fileSystemEntryExists(path, 1 /* Directory */);
5906             }
5907             function getDirectories(path) {
5908                 return getAccessibleFileSystemEntries(path).directories.slice();
5909             }
5910             function realpath(path) {
5911                 try {
5912                     return _fs.realpathSync(path);
5913                 }
5914                 catch (_a) {
5915                     return path;
5916                 }
5917             }
5918             function getModifiedTime(path) {
5919                 try {
5920                     return _fs.statSync(path).mtime;
5921                 }
5922                 catch (e) {
5923                     return undefined;
5924                 }
5925             }
5926             function setModifiedTime(path, time) {
5927                 try {
5928                     _fs.utimesSync(path, time, time);
5929                 }
5930                 catch (e) {
5931                     return;
5932                 }
5933             }
5934             function deleteFile(path) {
5935                 try {
5936                     return _fs.unlinkSync(path);
5937                 }
5938                 catch (e) {
5939                     return;
5940                 }
5941             }
5942             function createSHA256Hash(data) {
5943                 var hash = _crypto.createHash("sha256");
5944                 hash.update(data);
5945                 return hash.digest("hex");
5946             }
5947         }
5948         var sys;
5949         if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
5950             // process and process.nextTick checks if current environment is node-like
5951             // process.browser check excludes webpack and browserify
5952             sys = getNodeSystem();
5953         }
5954         if (sys) {
5955             // patch writefile to create folder before writing the file
5956             patchWriteFileEnsuringDirectory(sys);
5957         }
5958         return sys;
5959     })();
5960     if (ts.sys && ts.sys.getEnvironmentVariable) {
5961         setCustomPollingValues(ts.sys);
5962         ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
5963             ? 1 /* Normal */
5964             : 0 /* None */);
5965     }
5966     if (ts.sys && ts.sys.debugMode) {
5967         ts.Debug.isDebugging = true;
5968     }
5969 })(ts || (ts = {}));
5970 /* @internal */
5971 var ts;
5972 (function (ts) {
5973     /**
5974      * Internally, we represent paths as strings with '/' as the directory separator.
5975      * When we make system calls (eg: LanguageServiceHost.getDirectory()),
5976      * we expect the host to correctly handle paths in our specified format.
5977      */
5978     ts.directorySeparator = "/";
5979     var altDirectorySeparator = "\\";
5980     var urlSchemeSeparator = "://";
5981     var backslashRegExp = /\\/g;
5982     //// Path Tests
5983     /**
5984      * Determines whether a charCode corresponds to `/` or `\`.
5985      */
5986     function isAnyDirectorySeparator(charCode) {
5987         return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
5988     }
5989     ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
5990     /**
5991      * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
5992      */
5993     function isUrl(path) {
5994         return getEncodedRootLength(path) < 0;
5995     }
5996     ts.isUrl = isUrl;
5997     /**
5998      * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
5999      * like `c:`, `c:\` or `c:/`).
6000      */
6001     function isRootedDiskPath(path) {
6002         return getEncodedRootLength(path) > 0;
6003     }
6004     ts.isRootedDiskPath = isRootedDiskPath;
6005     /**
6006      * Determines whether a path consists only of a path root.
6007      */
6008     function isDiskPathRoot(path) {
6009         var rootLength = getEncodedRootLength(path);
6010         return rootLength > 0 && rootLength === path.length;
6011     }
6012     ts.isDiskPathRoot = isDiskPathRoot;
6013     /**
6014      * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
6015      *
6016      * ```ts
6017      * // POSIX
6018      * pathIsAbsolute("/path/to/file.ext") === true
6019      * // DOS
6020      * pathIsAbsolute("c:/path/to/file.ext") === true
6021      * // URL
6022      * pathIsAbsolute("file:///path/to/file.ext") === true
6023      * // Non-absolute
6024      * pathIsAbsolute("path/to/file.ext") === false
6025      * pathIsAbsolute("./path/to/file.ext") === false
6026      * ```
6027      */
6028     function pathIsAbsolute(path) {
6029         return getEncodedRootLength(path) !== 0;
6030     }
6031     ts.pathIsAbsolute = pathIsAbsolute;
6032     /**
6033      * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
6034      */
6035     function pathIsRelative(path) {
6036         return /^\.\.?($|[\\/])/.test(path);
6037     }
6038     ts.pathIsRelative = pathIsRelative;
6039     function hasExtension(fileName) {
6040         return ts.stringContains(getBaseFileName(fileName), ".");
6041     }
6042     ts.hasExtension = hasExtension;
6043     function fileExtensionIs(path, extension) {
6044         return path.length > extension.length && ts.endsWith(path, extension);
6045     }
6046     ts.fileExtensionIs = fileExtensionIs;
6047     function fileExtensionIsOneOf(path, extensions) {
6048         for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
6049             var extension = extensions_1[_i];
6050             if (fileExtensionIs(path, extension)) {
6051                 return true;
6052             }
6053         }
6054         return false;
6055     }
6056     ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
6057     /**
6058      * Determines whether a path has a trailing separator (`/` or `\\`).
6059      */
6060     function hasTrailingDirectorySeparator(path) {
6061         return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
6062     }
6063     ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
6064     //// Path Parsing
6065     function isVolumeCharacter(charCode) {
6066         return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
6067             (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
6068     }
6069     function getFileUrlVolumeSeparatorEnd(url, start) {
6070         var ch0 = url.charCodeAt(start);
6071         if (ch0 === 58 /* colon */)
6072             return start + 1;
6073         if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
6074             var ch2 = url.charCodeAt(start + 2);
6075             if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
6076                 return start + 3;
6077         }
6078         return -1;
6079     }
6080     /**
6081      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6082      * If the root is part of a URL, the twos-complement of the root length is returned.
6083      */
6084     function getEncodedRootLength(path) {
6085         if (!path)
6086             return 0;
6087         var ch0 = path.charCodeAt(0);
6088         // POSIX or UNC
6089         if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
6090             if (path.charCodeAt(1) !== ch0)
6091                 return 1; // POSIX: "/" (or non-normalized "\")
6092             var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
6093             if (p1 < 0)
6094                 return path.length; // UNC: "//server" or "\\server"
6095             return p1 + 1; // UNC: "//server/" or "\\server\"
6096         }
6097         // DOS
6098         if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
6099             var ch2 = path.charCodeAt(2);
6100             if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
6101                 return 3; // DOS: "c:/" or "c:\"
6102             if (path.length === 2)
6103                 return 2; // DOS: "c:" (but not "c:d")
6104         }
6105         // URL
6106         var schemeEnd = path.indexOf(urlSchemeSeparator);
6107         if (schemeEnd !== -1) {
6108             var authorityStart = schemeEnd + urlSchemeSeparator.length;
6109             var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
6110             if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
6111                 // For local "file" URLs, include the leading DOS volume (if present).
6112                 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
6113                 // special case interpreted as "the machine from which the URL is being interpreted".
6114                 var scheme = path.slice(0, schemeEnd);
6115                 var authority = path.slice(authorityStart, authorityEnd);
6116                 if (scheme === "file" && (authority === "" || authority === "localhost") &&
6117                     isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
6118                     var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
6119                     if (volumeSeparatorEnd !== -1) {
6120                         if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
6121                             // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
6122                             return ~(volumeSeparatorEnd + 1);
6123                         }
6124                         if (volumeSeparatorEnd === path.length) {
6125                             // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
6126                             // but not "file:///c:d" or "file:///c%3ad"
6127                             return ~volumeSeparatorEnd;
6128                         }
6129                     }
6130                 }
6131                 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
6132             }
6133             return ~path.length; // URL: "file://server", "http://server"
6134         }
6135         // relative
6136         return 0;
6137     }
6138     /**
6139      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6140      *
6141      * For example:
6142      * ```ts
6143      * getRootLength("a") === 0                   // ""
6144      * getRootLength("/") === 1                   // "/"
6145      * getRootLength("c:") === 2                  // "c:"
6146      * getRootLength("c:d") === 0                 // ""
6147      * getRootLength("c:/") === 3                 // "c:/"
6148      * getRootLength("c:\\") === 3                // "c:\\"
6149      * getRootLength("//server") === 7            // "//server"
6150      * getRootLength("//server/share") === 8      // "//server/"
6151      * getRootLength("\\\\server") === 7          // "\\\\server"
6152      * getRootLength("\\\\server\\share") === 8   // "\\\\server\\"
6153      * getRootLength("file:///path") === 8        // "file:///"
6154      * getRootLength("file:///c:") === 10         // "file:///c:"
6155      * getRootLength("file:///c:d") === 8         // "file:///"
6156      * getRootLength("file:///c:/path") === 11    // "file:///c:/"
6157      * getRootLength("file://server") === 13      // "file://server"
6158      * getRootLength("file://server/path") === 14 // "file://server/"
6159      * getRootLength("http://server") === 13      // "http://server"
6160      * getRootLength("http://server/path") === 14 // "http://server/"
6161      * ```
6162      */
6163     function getRootLength(path) {
6164         var rootLength = getEncodedRootLength(path);
6165         return rootLength < 0 ? ~rootLength : rootLength;
6166     }
6167     ts.getRootLength = getRootLength;
6168     function getDirectoryPath(path) {
6169         path = normalizeSlashes(path);
6170         // If the path provided is itself the root, then return it.
6171         var rootLength = getRootLength(path);
6172         if (rootLength === path.length)
6173             return path;
6174         // return the leading portion of the path up to the last (non-terminal) directory separator
6175         // but not including any trailing directory separator.
6176         path = removeTrailingDirectorySeparator(path);
6177         return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
6178     }
6179     ts.getDirectoryPath = getDirectoryPath;
6180     function getBaseFileName(path, extensions, ignoreCase) {
6181         path = normalizeSlashes(path);
6182         // if the path provided is itself the root, then it has not file name.
6183         var rootLength = getRootLength(path);
6184         if (rootLength === path.length)
6185             return "";
6186         // return the trailing portion of the path starting after the last (non-terminal) directory
6187         // separator but not including any trailing directory separator.
6188         path = removeTrailingDirectorySeparator(path);
6189         var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
6190         var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
6191         return extension ? name.slice(0, name.length - extension.length) : name;
6192     }
6193     ts.getBaseFileName = getBaseFileName;
6194     function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
6195         if (!ts.startsWith(extension, "."))
6196             extension = "." + extension;
6197         if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
6198             var pathExtension = path.slice(path.length - extension.length);
6199             if (stringEqualityComparer(pathExtension, extension)) {
6200                 return pathExtension;
6201             }
6202         }
6203     }
6204     function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
6205         if (typeof extensions === "string") {
6206             return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
6207         }
6208         for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
6209             var extension = extensions_2[_i];
6210             var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
6211             if (result)
6212                 return result;
6213         }
6214         return "";
6215     }
6216     function getAnyExtensionFromPath(path, extensions, ignoreCase) {
6217         // Retrieves any string from the final "." onwards from a base file name.
6218         // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
6219         if (extensions) {
6220             return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
6221         }
6222         var baseFileName = getBaseFileName(path);
6223         var extensionIndex = baseFileName.lastIndexOf(".");
6224         if (extensionIndex >= 0) {
6225             return baseFileName.substring(extensionIndex);
6226         }
6227         return "";
6228     }
6229     ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
6230     function pathComponents(path, rootLength) {
6231         var root = path.substring(0, rootLength);
6232         var rest = path.substring(rootLength).split(ts.directorySeparator);
6233         if (rest.length && !ts.lastOrUndefined(rest))
6234             rest.pop();
6235         return __spreadArrays([root], rest);
6236     }
6237     /**
6238      * Parse a path into an array containing a root component (at index 0) and zero or more path
6239      * components (at indices > 0). The result is not normalized.
6240      * If the path is relative, the root component is `""`.
6241      * If the path is absolute, the root component includes the first path separator (`/`).
6242      *
6243      * ```ts
6244      * // POSIX
6245      * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
6246      * getPathComponents("/path/to/") === ["/", "path", "to"]
6247      * getPathComponents("/") === ["/"]
6248      * // DOS
6249      * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
6250      * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
6251      * getPathComponents("c:/") === ["c:/"]
6252      * getPathComponents("c:") === ["c:"]
6253      * // URL
6254      * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
6255      * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
6256      * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
6257      * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
6258      * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
6259      * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
6260      * getPathComponents("file://server/") === ["file://server/"]
6261      * getPathComponents("file://server") === ["file://server"]
6262      * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
6263      * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
6264      * getPathComponents("file:///") === ["file:///"]
6265      * getPathComponents("file://") === ["file://"]
6266      */
6267     function getPathComponents(path, currentDirectory) {
6268         if (currentDirectory === void 0) { currentDirectory = ""; }
6269         path = combinePaths(currentDirectory, path);
6270         return pathComponents(path, getRootLength(path));
6271     }
6272     ts.getPathComponents = getPathComponents;
6273     //// Path Formatting
6274     /**
6275      * Formats a parsed path consisting of a root component (at index 0) and zero or more path
6276      * segments (at indices > 0).
6277      *
6278      * ```ts
6279      * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
6280      * ```
6281      */
6282     function getPathFromPathComponents(pathComponents) {
6283         if (pathComponents.length === 0)
6284             return "";
6285         var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
6286         return root + pathComponents.slice(1).join(ts.directorySeparator);
6287     }
6288     ts.getPathFromPathComponents = getPathFromPathComponents;
6289     //// Path Normalization
6290     /**
6291      * Normalize path separators, converting `\` into `/`.
6292      */
6293     function normalizeSlashes(path) {
6294         return path.replace(backslashRegExp, ts.directorySeparator);
6295     }
6296     ts.normalizeSlashes = normalizeSlashes;
6297     /**
6298      * Reduce an array of path components to a more simplified path by navigating any
6299      * `"."` or `".."` entries in the path.
6300      */
6301     function reducePathComponents(components) {
6302         if (!ts.some(components))
6303             return [];
6304         var reduced = [components[0]];
6305         for (var i = 1; i < components.length; i++) {
6306             var component = components[i];
6307             if (!component)
6308                 continue;
6309             if (component === ".")
6310                 continue;
6311             if (component === "..") {
6312                 if (reduced.length > 1) {
6313                     if (reduced[reduced.length - 1] !== "..") {
6314                         reduced.pop();
6315                         continue;
6316                     }
6317                 }
6318                 else if (reduced[0])
6319                     continue;
6320             }
6321             reduced.push(component);
6322         }
6323         return reduced;
6324     }
6325     ts.reducePathComponents = reducePathComponents;
6326     /**
6327      * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
6328      *
6329      * ```ts
6330      * // Non-rooted
6331      * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
6332      * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
6333      * // POSIX
6334      * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
6335      * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
6336      * // DOS
6337      * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
6338      * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
6339      * // URL
6340      * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
6341      * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
6342      * ```
6343      */
6344     function combinePaths(path) {
6345         var paths = [];
6346         for (var _i = 1; _i < arguments.length; _i++) {
6347             paths[_i - 1] = arguments[_i];
6348         }
6349         if (path)
6350             path = normalizeSlashes(path);
6351         for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
6352             var relativePath = paths_1[_a];
6353             if (!relativePath)
6354                 continue;
6355             relativePath = normalizeSlashes(relativePath);
6356             if (!path || getRootLength(relativePath) !== 0) {
6357                 path = relativePath;
6358             }
6359             else {
6360                 path = ensureTrailingDirectorySeparator(path) + relativePath;
6361             }
6362         }
6363         return path;
6364     }
6365     ts.combinePaths = combinePaths;
6366     /**
6367      * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
6368      * `.` and `..` path components are resolved. Trailing directory separators are preserved.
6369      *
6370      * ```ts
6371      * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
6372      * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
6373      * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
6374      * ```
6375      */
6376     function resolvePath(path) {
6377         var paths = [];
6378         for (var _i = 1; _i < arguments.length; _i++) {
6379             paths[_i - 1] = arguments[_i];
6380         }
6381         return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path));
6382     }
6383     ts.resolvePath = resolvePath;
6384     /**
6385      * Parse a path into an array containing a root component (at index 0) and zero or more path
6386      * components (at indices > 0). The result is normalized.
6387      * If the path is relative, the root component is `""`.
6388      * If the path is absolute, the root component includes the first path separator (`/`).
6389      *
6390      * ```ts
6391      * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
6392      * ```
6393      */
6394     function getNormalizedPathComponents(path, currentDirectory) {
6395         return reducePathComponents(getPathComponents(path, currentDirectory));
6396     }
6397     ts.getNormalizedPathComponents = getNormalizedPathComponents;
6398     function getNormalizedAbsolutePath(fileName, currentDirectory) {
6399         return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
6400     }
6401     ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
6402     function normalizePath(path) {
6403         path = normalizeSlashes(path);
6404         var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
6405         return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
6406     }
6407     ts.normalizePath = normalizePath;
6408     function getPathWithoutRoot(pathComponents) {
6409         if (pathComponents.length === 0)
6410             return "";
6411         return pathComponents.slice(1).join(ts.directorySeparator);
6412     }
6413     function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
6414         return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
6415     }
6416     ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
6417     function toPath(fileName, basePath, getCanonicalFileName) {
6418         var nonCanonicalizedPath = isRootedDiskPath(fileName)
6419             ? normalizePath(fileName)
6420             : getNormalizedAbsolutePath(fileName, basePath);
6421         return getCanonicalFileName(nonCanonicalizedPath);
6422     }
6423     ts.toPath = toPath;
6424     function normalizePathAndParts(path) {
6425         path = normalizeSlashes(path);
6426         var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
6427         if (parts.length) {
6428             var joinedParts = root + parts.join(ts.directorySeparator);
6429             return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
6430         }
6431         else {
6432             return { path: root, parts: parts };
6433         }
6434     }
6435     ts.normalizePathAndParts = normalizePathAndParts;
6436     function removeTrailingDirectorySeparator(path) {
6437         if (hasTrailingDirectorySeparator(path)) {
6438             return path.substr(0, path.length - 1);
6439         }
6440         return path;
6441     }
6442     ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
6443     function ensureTrailingDirectorySeparator(path) {
6444         if (!hasTrailingDirectorySeparator(path)) {
6445             return path + ts.directorySeparator;
6446         }
6447         return path;
6448     }
6449     ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
6450     /**
6451      * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
6452      * with `./` or `../`) so as not to be confused with an unprefixed module name.
6453      *
6454      * ```ts
6455      * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
6456      * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
6457      * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
6458      * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
6459      * ```
6460      */
6461     function ensurePathIsNonModuleName(path) {
6462         return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
6463     }
6464     ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
6465     function changeAnyExtension(path, ext, extensions, ignoreCase) {
6466         var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
6467         return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
6468     }
6469     ts.changeAnyExtension = changeAnyExtension;
6470     //// Path Comparisons
6471     // check path for these segments: '', '.'. '..'
6472     var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
6473     function comparePathsWorker(a, b, componentComparer) {
6474         if (a === b)
6475             return 0 /* EqualTo */;
6476         if (a === undefined)
6477             return -1 /* LessThan */;
6478         if (b === undefined)
6479             return 1 /* GreaterThan */;
6480         // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
6481         //       need to perform path reduction.
6482         var aRoot = a.substring(0, getRootLength(a));
6483         var bRoot = b.substring(0, getRootLength(b));
6484         var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
6485         if (result !== 0 /* EqualTo */) {
6486             return result;
6487         }
6488         // NOTE: Performance optimization - shortcut if there are no relative path segments in
6489         //       the non-root portion of the path
6490         var aRest = a.substring(aRoot.length);
6491         var bRest = b.substring(bRoot.length);
6492         if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
6493             return componentComparer(aRest, bRest);
6494         }
6495         // The path contains a relative path segment. Normalize the paths and perform a slower component
6496         // by component comparison.
6497         var aComponents = reducePathComponents(getPathComponents(a));
6498         var bComponents = reducePathComponents(getPathComponents(b));
6499         var sharedLength = Math.min(aComponents.length, bComponents.length);
6500         for (var i = 1; i < sharedLength; i++) {
6501             var result_1 = componentComparer(aComponents[i], bComponents[i]);
6502             if (result_1 !== 0 /* EqualTo */) {
6503                 return result_1;
6504             }
6505         }
6506         return ts.compareValues(aComponents.length, bComponents.length);
6507     }
6508     /**
6509      * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
6510      */
6511     function comparePathsCaseSensitive(a, b) {
6512         return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
6513     }
6514     ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
6515     /**
6516      * Performs a case-insensitive comparison of two paths.
6517      */
6518     function comparePathsCaseInsensitive(a, b) {
6519         return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
6520     }
6521     ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
6522     function comparePaths(a, b, currentDirectory, ignoreCase) {
6523         if (typeof currentDirectory === "string") {
6524             a = combinePaths(currentDirectory, a);
6525             b = combinePaths(currentDirectory, b);
6526         }
6527         else if (typeof currentDirectory === "boolean") {
6528             ignoreCase = currentDirectory;
6529         }
6530         return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
6531     }
6532     ts.comparePaths = comparePaths;
6533     function containsPath(parent, child, currentDirectory, ignoreCase) {
6534         if (typeof currentDirectory === "string") {
6535             parent = combinePaths(currentDirectory, parent);
6536             child = combinePaths(currentDirectory, child);
6537         }
6538         else if (typeof currentDirectory === "boolean") {
6539             ignoreCase = currentDirectory;
6540         }
6541         if (parent === undefined || child === undefined)
6542             return false;
6543         if (parent === child)
6544             return true;
6545         var parentComponents = reducePathComponents(getPathComponents(parent));
6546         var childComponents = reducePathComponents(getPathComponents(child));
6547         if (childComponents.length < parentComponents.length) {
6548             return false;
6549         }
6550         var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
6551         for (var i = 0; i < parentComponents.length; i++) {
6552             var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
6553             if (!equalityComparer(parentComponents[i], childComponents[i])) {
6554                 return false;
6555             }
6556         }
6557         return true;
6558     }
6559     ts.containsPath = containsPath;
6560     /**
6561      * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
6562      * Comparison is case-sensitive between the canonical paths.
6563      *
6564      * @deprecated Use `containsPath` if possible.
6565      */
6566     function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
6567         var canonicalFileName = getCanonicalFileName(fileName);
6568         var canonicalDirectoryName = getCanonicalFileName(directoryName);
6569         return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
6570     }
6571     ts.startsWithDirectory = startsWithDirectory;
6572     //// Relative Paths
6573     function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
6574         var fromComponents = reducePathComponents(getPathComponents(from));
6575         var toComponents = reducePathComponents(getPathComponents(to));
6576         var start;
6577         for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
6578             var fromComponent = getCanonicalFileName(fromComponents[start]);
6579             var toComponent = getCanonicalFileName(toComponents[start]);
6580             var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
6581             if (!comparer(fromComponent, toComponent))
6582                 break;
6583         }
6584         if (start === 0) {
6585             return toComponents;
6586         }
6587         var components = toComponents.slice(start);
6588         var relative = [];
6589         for (; start < fromComponents.length; start++) {
6590             relative.push("..");
6591         }
6592         return __spreadArrays([""], relative, components);
6593     }
6594     ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
6595     function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
6596         ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
6597         var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
6598         var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
6599         var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
6600         return getPathFromPathComponents(pathComponents);
6601     }
6602     ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
6603     function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
6604         return !isRootedDiskPath(absoluteOrRelativePath)
6605             ? absoluteOrRelativePath
6606             : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
6607     }
6608     ts.convertToRelativePath = convertToRelativePath;
6609     function getRelativePathFromFile(from, to, getCanonicalFileName) {
6610         return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
6611     }
6612     ts.getRelativePathFromFile = getRelativePathFromFile;
6613     function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
6614         var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
6615         var firstComponent = pathComponents[0];
6616         if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
6617             var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
6618             pathComponents[0] = prefix + firstComponent;
6619         }
6620         return getPathFromPathComponents(pathComponents);
6621     }
6622     ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
6623     function forEachAncestorDirectory(directory, callback) {
6624         while (true) {
6625             var result = callback(directory);
6626             if (result !== undefined) {
6627                 return result;
6628             }
6629             var parentPath = getDirectoryPath(directory);
6630             if (parentPath === directory) {
6631                 return undefined;
6632             }
6633             directory = parentPath;
6634         }
6635     }
6636     ts.forEachAncestorDirectory = forEachAncestorDirectory;
6637     function isNodeModulesDirectory(dirPath) {
6638         return ts.endsWith(dirPath, "/node_modules");
6639     }
6640     ts.isNodeModulesDirectory = isNodeModulesDirectory;
6641 })(ts || (ts = {}));
6642 // <auto-generated />
6643 // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
6644 /* @internal */
6645 var ts;
6646 (function (ts) {
6647     function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid) {
6648         return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid };
6649     }
6650     ts.Diagnostics = {
6651         Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
6652         Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
6653         _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
6654         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."),
6655         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."),
6656         Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
6657         Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
6658         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."),
6659         Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
6660         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."),
6661         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."),
6662         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."),
6663         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."),
6664         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."),
6665         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."),
6666         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."),
6667         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."),
6668         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."),
6669         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."),
6670         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'."),
6671         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."),
6672         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."),
6673         Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
6674         _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
6675         _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
6676         _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."),
6677         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."),
6678         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."),
6679         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."),
6680         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."),
6681         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."),
6682         _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."),
6683         _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."),
6684         _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
6685         _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."),
6686         _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."),
6687         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."),
6688         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."),
6689         A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
6690         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."),
6691         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."),
6692         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."),
6693         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."),
6694         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."),
6695         A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
6696         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."),
6697         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."),
6698         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."),
6699         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."),
6700         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."),
6701         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."),
6702         Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
6703         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."),
6704         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."),
6705         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."),
6706         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."),
6707         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."),
6708         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."),
6709         _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."),
6710         _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."),
6711         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."),
6712         Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
6713         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}'."),
6714         _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."),
6715         _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."),
6716         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."),
6717         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."),
6718         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."),
6719         An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
6720         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."),
6721         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."),
6722         _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
6723         Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
6724         Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
6725         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."),
6726         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."),
6727         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."),
6728         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."),
6729         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."),
6730         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."),
6731         Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
6732         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."),
6733         Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
6734         Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
6735         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."),
6736         Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
6737         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."),
6738         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."),
6739         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."),
6740         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."),
6741         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."),
6742         An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
6743         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."),
6744         Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
6745         Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
6746         Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
6747         Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
6748         Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
6749         Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
6750         Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
6751         case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
6752         Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
6753         Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
6754         Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
6755         Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
6756         Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
6757         Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
6758         Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
6759         Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
6760         Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
6761         String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
6762         Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
6763         or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
6764         Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
6765         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."),
6766         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'."),
6767         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."),
6768         const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
6769         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."),
6770         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."),
6771         Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
6772         Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
6773         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."),
6774         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."),
6775         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."),
6776         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."),
6777         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."),
6778         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."),
6779         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."),
6780         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."),
6781         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."),
6782         extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
6783         extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
6784         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."),
6785         implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
6786         Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
6787         Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
6788         Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
6789         Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
6790         Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
6791         Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
6792         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."),
6793         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."),
6794         Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
6795         Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
6796         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."),
6797         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."),
6798         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."),
6799         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."),
6800         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."),
6801         An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
6802         Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
6803         An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
6804         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."),
6805         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."),
6806         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."),
6807         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."),
6808         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."),
6809         Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
6810         Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
6811         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."),
6812         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."),
6813         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'."),
6814         Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
6815         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."),
6816         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."),
6817         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."),
6818         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."),
6819         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."),
6820         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."),
6821         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."),
6822         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."),
6823         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."),
6824         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'."),
6825         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."),
6826         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."),
6827         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."),
6828         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."),
6829         _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
6830         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."),
6831         Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
6832         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}'."),
6833         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}'."),
6834         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."),
6835         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."),
6836         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."),
6837         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."),
6838         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."),
6839         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."),
6840         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."),
6841         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."),
6842         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'."),
6843         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'."),
6844         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."),
6845         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."),
6846         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."),
6847         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."),
6848         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."),
6849         _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."),
6850         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."),
6851         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."),
6852         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."),
6853         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."),
6854         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."),
6855         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."),
6856         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'."),
6857         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."),
6858         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."),
6859         _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."),
6860         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."),
6861         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."),
6862         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."),
6863         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."),
6864         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."),
6865         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"),
6866         Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
6867         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."),
6868         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."),
6869         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."),
6870         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."),
6871         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."),
6872         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."),
6873         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."),
6874         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."),
6875         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."),
6876         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."),
6877         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."),
6878         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."),
6879         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."),
6880         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."),
6881         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'."),
6882         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."),
6883         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."),
6884         Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
6885         String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
6886         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."),
6887         _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}()'?"),
6888         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'."),
6889         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'."),
6890         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'."),
6891         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."),
6892         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."),
6893         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."),
6894         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."),
6895         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."),
6896         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."),
6897         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."),
6898         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}')'?"),
6899         Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
6900         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'."),
6901         A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
6902         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"),
6903         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."),
6904         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."),
6905         Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
6906         use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
6907         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."),
6908         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."),
6909         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."),
6910         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."),
6911         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."),
6912         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."),
6913         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'?"),
6914         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 '}'."),
6915         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."),
6916         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."),
6917         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?"),
6918         _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'."),
6919         _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'."),
6920         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."),
6921         Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
6922         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"),
6923         Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
6924         Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
6925         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"),
6926         Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
6927         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'."),
6928         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'."),
6929         Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
6930         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"),
6931         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."),
6932         _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
6933         _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
6934         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."),
6935         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'."),
6936         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'."),
6937         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;`?"),
6938         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;`?"),
6939         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'."),
6940         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."),
6941         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."),
6942         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."),
6943         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),
6944         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),
6945         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),
6946         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),
6947         Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
6948         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."),
6949         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."),
6950         Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
6951         Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
6952         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}'."),
6953         File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
6954         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."),
6955         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."),
6956         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."),
6957         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."),
6958         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."),
6959         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."),
6960         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."),
6961         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)."),
6962         Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
6963         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."),
6964         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)."),
6965         Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
6966         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."),
6967         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}'."),
6968         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}'."),
6969         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}'."),
6970         Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
6971         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}'."),
6972         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}'."),
6973         Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
6974         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}'."),
6975         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."),
6976         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}'."),
6977         Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
6978         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."),
6979         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."),
6980         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."),
6981         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."),
6982         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."),
6983         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."),
6984         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."),
6985         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."),
6986         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}'."),
6987         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."),
6988         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}'."),
6989         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'."),
6990         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}'."),
6991         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}'."),
6992         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}'."),
6993         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."),
6994         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."),
6995         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'?"),
6996         This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
6997         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."),
6998         This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
6999         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."),
7000         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}'."),
7001         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."),
7002         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."),
7003         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."),
7004         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."),
7005         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."),
7006         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."),
7007         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'."),
7008         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."),
7009         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."),
7010         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."),
7011         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."),
7012         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}'."),
7013         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'."),
7014         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."),
7015         Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
7016         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."),
7017         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."),
7018         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."),
7019         Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
7020         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."),
7021         Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
7022         Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
7023         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."),
7024         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."),
7025         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."),
7026         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."),
7027         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."),
7028         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."),
7029         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."),
7030         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."),
7031         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."),
7032         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."),
7033         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."),
7034         Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
7035         Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
7036         Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
7037         Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
7038         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."),
7039         Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
7040         Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
7041         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."),
7042         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."),
7043         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."),
7044         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}'."),
7045         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."),
7046         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."),
7047         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."),
7048         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."),
7049         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."),
7050         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}'."),
7051         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."),
7052         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'."),
7053         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."),
7054         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}'."),
7055         Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
7056         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."),
7057         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'."),
7058         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}'."),
7059         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}'."),
7060         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}'."),
7061         Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
7062         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}'."),
7063         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}'."),
7064         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}'."),
7065         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}'."),
7066         Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
7067         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."),
7068         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."),
7069         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."),
7070         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."),
7071         Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
7072         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."),
7073         Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
7074         Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
7075         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."),
7076         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."),
7077         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."),
7078         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."),
7079         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."),
7080         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."),
7081         Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
7082         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."),
7083         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}'."),
7084         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."),
7085         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}'."),
7086         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}'."),
7087         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}'."),
7088         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."),
7089         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}'."),
7090         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."),
7091         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."),
7092         Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
7093         Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
7094         Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
7095         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."),
7096         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."),
7097         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."),
7098         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}'."),
7099         Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
7100         Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
7101         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."),
7102         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."),
7103         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}'."),
7104         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."),
7105         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."),
7106         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."),
7107         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'."),
7108         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."),
7109         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."),
7110         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."),
7111         Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
7112         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'."),
7113         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."),
7114         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'."),
7115         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."),
7116         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."),
7117         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."),
7118         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."),
7119         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."),
7120         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."),
7121         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'."),
7122         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}'."),
7123         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."),
7124         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}'."),
7125         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."),
7126         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}'."),
7127         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."),
7128         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."),
7129         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."),
7130         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."),
7131         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."),
7132         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."),
7133         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}'."),
7134         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."),
7135         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."),
7136         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."),
7137         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."),
7138         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 *'."),
7139         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."),
7140         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."),
7141         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."),
7142         _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."),
7143         Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
7144         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."),
7145         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."),
7146         _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."),
7147         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."),
7148         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."),
7149         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."),
7150         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."),
7151         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."),
7152         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."),
7153         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."),
7154         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."),
7155         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}'."),
7156         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."),
7157         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."),
7158         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."),
7159         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."),
7160         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."),
7161         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."),
7162         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."),
7163         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."),
7164         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."),
7165         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."),
7166         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."),
7167         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."),
7168         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."),
7169         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."),
7170         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."),
7171         Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
7172         Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
7173         Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
7174         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."),
7175         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."),
7176         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}'."),
7177         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}'."),
7178         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."),
7179         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."),
7180         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."),
7181         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."),
7182         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."),
7183         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."),
7184         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."),
7185         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[]'."),
7186         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."),
7187         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."),
7188         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."),
7189         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}'?"),
7190         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}'?"),
7191         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."),
7192         Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
7193         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}."),
7194         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."),
7195         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."),
7196         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}."),
7197         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}'."),
7198         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?"),
7199         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}'?"),
7200         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."),
7201         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."),
7202         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."),
7203         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."),
7204         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."),
7205         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."),
7206         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."),
7207         Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
7208         Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
7209         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."),
7210         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."),
7211         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."),
7212         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}'"),
7213         Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
7214         Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
7215         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`."),
7216         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`."),
7217         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`."),
7218         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."),
7219         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'."),
7220         _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."),
7221         Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
7222         JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
7223         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."),
7224         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."),
7225         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."),
7226         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."),
7227         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."),
7228         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."),
7229         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."),
7230         _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."),
7231         _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."),
7232         _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."),
7233         _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."),
7234         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."),
7235         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."),
7236         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."),
7237         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}'."),
7238         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."),
7239         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."),
7240         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."),
7241         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."),
7242         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."),
7243         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."),
7244         _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."),
7245         _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."),
7246         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."),
7247         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?"),
7248         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?"),
7249         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}'."),
7250         _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."),
7251         _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."),
7252         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."),
7253         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."),
7254         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."),
7255         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}'."),
7256         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."),
7257         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."),
7258         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."),
7259         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}'."),
7260         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."),
7261         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."),
7262         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."),
7263         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}'?"),
7264         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}'?"),
7265         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."),
7266         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."),
7267         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."),
7268         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."),
7269         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."),
7270         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."),
7271         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."),
7272         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."),
7273         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."),
7274         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."),
7275         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."),
7276         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."),
7277         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."),
7278         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."),
7279         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}'."),
7280         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'."),
7281         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."),
7282         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."),
7283         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."),
7284         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."),
7285         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}'."),
7286         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."),
7287         _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."),
7288         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."),
7289         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}'."),
7290         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'?"),
7291         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."),
7292         _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."),
7293         _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."),
7294         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}'."),
7295         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),
7296         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?"),
7297         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."),
7298         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."),
7299         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}'."),
7300         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."),
7301         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."),
7302         _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."),
7303         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."),
7304         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."),
7305         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."),
7306         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."),
7307         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."),
7308         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."),
7309         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."),
7310         _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."),
7311         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."),
7312         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."),
7313         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}\"]'?"),
7314         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."),
7315         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."),
7316         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."),
7317         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}'."),
7318         Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
7319         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."),
7320         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?"),
7321         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'."),
7322         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'."),
7323         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'."),
7324         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}'?"),
7325         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}."),
7326         Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
7327         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}'?"),
7328         _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
7329         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."),
7330         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."),
7331         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(...)'."),
7332         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"),
7333         Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
7334         Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
7335         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}'?"),
7336         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}'."),
7337         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."),
7338         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."),
7339         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}"),
7340         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."),
7341         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}'."),
7342         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."),
7343         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."),
7344         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."),
7345         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."),
7346         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."),
7347         _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}'."),
7348         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."),
7349         _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}'?"),
7350         The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
7351         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."),
7352         The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
7353         Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
7354         super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
7355         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."),
7356         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."),
7357         Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
7358         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."),
7359         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."),
7360         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."),
7361         Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
7362         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."),
7363         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}'."),
7364         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}'."),
7365         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}'."),
7366         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}'."),
7367         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."),
7368         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."),
7369         No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
7370         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."),
7371         The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
7372         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."),
7373         Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
7374         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?"),
7375         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."),
7376         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."),
7377         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."),
7378         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."),
7379         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."),
7380         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."),
7381         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."),
7382         _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
7383         _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."),
7384         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."),
7385         This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
7386         _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."),
7387         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."),
7388         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."),
7389         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."),
7390         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}'."),
7391         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}'."),
7392         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}'."),
7393         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}'."),
7394         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}'."),
7395         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}'."),
7396         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}'."),
7397         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}'."),
7398         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}'."),
7399         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}'."),
7400         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}'."),
7401         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}'."),
7402         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."),
7403         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}'."),
7404         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}'."),
7405         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."),
7406         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}'."),
7407         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}'."),
7408         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."),
7409         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}'."),
7410         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}'."),
7411         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}'."),
7412         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}'."),
7413         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}'."),
7414         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}'."),
7415         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}'."),
7416         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}'."),
7417         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."),
7418         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}'."),
7419         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}'."),
7420         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."),
7421         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}'."),
7422         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}'."),
7423         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}'."),
7424         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}'."),
7425         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}'."),
7426         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}'."),
7427         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}'."),
7428         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}'."),
7429         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."),
7430         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}'."),
7431         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}'."),
7432         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."),
7433         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}'."),
7434         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}'."),
7435         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}'."),
7436         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}'."),
7437         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."),
7438         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}'."),
7439         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}'."),
7440         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."),
7441         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}'."),
7442         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}'."),
7443         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}'."),
7444         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}'."),
7445         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}'."),
7446         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}'."),
7447         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."),
7448         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}'."),
7449         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}'."),
7450         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."),
7451         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}'."),
7452         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}'."),
7453         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}'."),
7454         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}'."),
7455         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."),
7456         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}'."),
7457         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}'."),
7458         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}'."),
7459         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}'."),
7460         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}'."),
7461         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."),
7462         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}'."),
7463         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}'."),
7464         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."),
7465         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."),
7466         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}'."),
7467         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}'."),
7468         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."),
7469         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}'."),
7470         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}'."),
7471         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}'."),
7472         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}'."),
7473         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}'."),
7474         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}'."),
7475         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."),
7476         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}'."),
7477         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}'."),
7478         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."),
7479         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."),
7480         Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
7481         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."),
7482         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."),
7483         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}'."),
7484         Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
7485         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}."),
7486         Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
7487         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}."),
7488         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}'?"),
7489         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}."),
7490         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."),
7491         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."),
7492         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'."),
7493         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."),
7494         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}'."),
7495         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}'."),
7496         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}'."),
7497         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."),
7498         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."),
7499         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}'."),
7500         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}'."),
7501         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."),
7502         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."),
7503         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."),
7504         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."),
7505         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."),
7506         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}'."),
7507         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}'."),
7508         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."),
7509         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."),
7510         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."),
7511         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}'."),
7512         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."),
7513         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'."),
7514         Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
7515         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}."),
7516         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."),
7517         _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}'."),
7518         _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."),
7519         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}'?"),
7520         Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
7521         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}'?"),
7522         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}."),
7523         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}."),
7524         _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}'."),
7525         Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
7526         The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."),
7527         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."),
7528         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."),
7529         Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
7530         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."),
7531         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."),
7532         Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
7533         Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
7534         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."),
7535         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."),
7536         Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
7537         Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
7538         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."),
7539         Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
7540         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."),
7541         Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
7542         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'."),
7543         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'."),
7544         Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
7545         Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
7546         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'."),
7547         Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
7548         options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
7549         file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
7550         Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
7551         Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
7552         Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
7553         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."),
7554         Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
7555         File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
7556         KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
7557         FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
7558         VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
7559         LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
7560         DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
7561         STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
7562         FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
7563         Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
7564         Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
7565         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}'."),
7566         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}."),
7567         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}'."),
7568         Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
7569         Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
7570         Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
7571         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."),
7572         File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
7573         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}."),
7574         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."),
7575         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."),
7576         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."),
7577         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."),
7578         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)."),
7579         NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
7580         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."),
7581         Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
7582         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."),
7583         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."),
7584         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)."),
7585         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."),
7586         Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
7587         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."),
7588         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)."),
7589         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."),
7590         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."),
7591         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."),
7592         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."),
7593         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."),
7594         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."),
7595         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'."),
7596         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."),
7597         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}."),
7598         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."),
7599         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"),
7600         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."),
7601         Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
7602         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}'."),
7603         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}'."),
7604         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}'. ========"),
7605         Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
7606         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}'."),
7607         Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
7608         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}'."),
7609         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}'."),
7610         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}'."),
7611         File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
7612         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."),
7613         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}'."),
7614         Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
7615         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."),
7616         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}'."),
7617         Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
7618         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."),
7619         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}'."),
7620         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}'."),
7621         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}'."),
7622         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}'."),
7623         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}'."),
7624         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}'."),
7625         Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
7626         Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
7627         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."),
7628         Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
7629         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'?"),
7630         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."),
7631         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}'. ========"),
7632         Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
7633         Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
7634         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}. ========"),
7635         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. ========"),
7636         Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
7637         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."),
7638         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. ========"),
7639         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."),
7640         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}'."),
7641         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."),
7642         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}'. ========"),
7643         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. ========"),
7644         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}'."),
7645         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'."),
7646         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."),
7647         _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),
7648         Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
7649         Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
7650         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."),
7651         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}'."),
7652         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),
7653         Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
7654         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}'."),
7655         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."),
7656         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."),
7657         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}'."),
7658         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."),
7659         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'."),
7660         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}'."),
7661         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."),
7662         Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
7663         Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
7664         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."),
7665         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."),
7666         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')."),
7667         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."),
7668         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."),
7669         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')"),
7670         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."),
7671         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)."),
7672         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."),
7673         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."),
7674         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."),
7675         Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
7676         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."),
7677         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."),
7678         Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
7679         Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
7680         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'."),
7681         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."),
7682         Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
7683         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"),
7684         Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
7685         Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
7686         Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
7687         Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
7688         Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
7689         Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
7690         Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
7691         Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
7692         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'."),
7693         Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
7694         List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
7695         Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
7696         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."),
7697         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."),
7698         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."),
7699         Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
7700         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."),
7701         Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
7702         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."),
7703         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."),
7704         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),
7705         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."),
7706         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."),
7707         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)."),
7708         _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),
7709         Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
7710         All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
7711         All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
7712         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}"),
7713         Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
7714         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}"),
7715         _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
7716         and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
7717         All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
7718         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."),
7719         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}'."),
7720         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}'."),
7721         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."),
7722         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."),
7723         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."),
7724         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?"),
7725         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?"),
7726         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."),
7727         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}'."),
7728         Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
7729         Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
7730         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}'. ========"),
7731         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}. ========"),
7732         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."),
7733         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."),
7734         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."),
7735         Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
7736         Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
7737         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'."),
7738         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'."),
7739         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'."),
7740         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."),
7741         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}'."),
7742         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."),
7743         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}."),
7744         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."),
7745         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."),
7746         Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
7747         Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
7748         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."),
7749         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}'."),
7750         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."),
7751         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."),
7752         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"),
7753         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"),
7754         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}'"),
7755         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}'"),
7756         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"),
7757         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"),
7758         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"),
7759         Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
7760         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}"),
7761         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}'"),
7762         Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
7763         Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
7764         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"),
7765         Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
7766         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"),
7767         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"),
7768         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"),
7769         Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
7770         Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
7771         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')"),
7772         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"),
7773         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."),
7774         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."),
7775         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}'..."),
7776         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"),
7777         Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
7778         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}'"),
7779         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}'"),
7780         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}'"),
7781         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}'"),
7782         Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
7783         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."),
7784         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"),
7785         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}'"),
7786         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"),
7787         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"),
7788         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."),
7789         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}'"),
7790         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."),
7791         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."),
7792         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."),
7793         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?"),
7794         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."),
7795         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."),
7796         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."),
7797         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."),
7798         _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."),
7799         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."),
7800         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."),
7801         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."),
7802         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'."),
7803         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."),
7804         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."),
7805         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."),
7806         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."),
7807         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."),
7808         _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."),
7809         _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."),
7810         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."),
7811         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."),
7812         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."),
7813         Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
7814         Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
7815         Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
7816         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."),
7817         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."),
7818         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."),
7819         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."),
7820         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."),
7821         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}';`"),
7822         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}'."),
7823         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'."),
7824         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."),
7825         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."),
7826         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}`"),
7827         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'."),
7828         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."),
7829         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."),
7830         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."),
7831         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."),
7832         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."),
7833         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."),
7834         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."),
7835         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."),
7836         _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."),
7837         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}'?"),
7838         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}'?"),
7839         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}'."),
7840         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}'."),
7841         _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."),
7842         You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
7843         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."),
7844         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."),
7845         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."),
7846         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."),
7847         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."),
7848         _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."),
7849         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."),
7850         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."),
7851         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."),
7852         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."),
7853         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."),
7854         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."),
7855         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."),
7856         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}'."),
7857         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}'."),
7858         Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
7859         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."),
7860         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."),
7861         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."),
7862         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."),
7863         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."),
7864         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."),
7865         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."),
7866         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."),
7867         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."),
7868         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."),
7869         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."),
7870         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."),
7871         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}'."),
7872         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."),
7873         class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
7874         Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
7875         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."),
7876         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."),
7877         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'."),
7878         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."),
7879         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}'."),
7880         JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
7881         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."),
7882         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'."),
7883         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."),
7884         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."),
7885         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."),
7886         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."),
7887         Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
7888         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."),
7889         _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}'?"),
7890         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."),
7891         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."),
7892         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."),
7893         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"),
7894         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"),
7895         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}'?"),
7896         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}"),
7897         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."),
7898         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."),
7899         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}'."),
7900         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."),
7901         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."),
7902         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."),
7903         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."),
7904         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."),
7905         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."),
7906         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."),
7907         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."),
7908         Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
7909         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"),
7910         Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
7911         Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
7912         Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
7913         Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
7914         Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
7915         Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
7916         Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
7917         Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
7918         Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
7919         Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
7920         Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
7921         Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
7922         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}\""),
7923         Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
7924         Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
7925         Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
7926         Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
7927         Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
7928         Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
7929         Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
7930         Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
7931         Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
7932         Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
7933         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}'"),
7934         Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
7935         Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
7936         Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
7937         Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
7938         Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
7939         Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
7940         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}\""),
7941         Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
7942         Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
7943         Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
7944         Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
7945         Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
7946         Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
7947         Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
7948         Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
7949         Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
7950         Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
7951         Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
7952         Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
7953         Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
7954         Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
7955         Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
7956         Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
7957         Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
7958         Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
7959         Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
7960         Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
7961         Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
7962         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}'"),
7963         Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
7964         Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
7965         Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
7966         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"),
7967         Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
7968         Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
7969         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"),
7970         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"),
7971         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"),
7972         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)"),
7973         Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
7974         Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
7975         Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
7976         Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
7977         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"),
7978         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"),
7979         Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
7980         Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
7981         Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
7982         Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
7983         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"),
7984         Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
7985         Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
7986         Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
7987         Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
7988         Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
7989         Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
7990         Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
7991         Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
7992         Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
7993         Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
7994         Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
7995         Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
7996         Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
7997         Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
7998         Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
7999         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"),
8000         Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
8001         Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
8002         Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
8003         Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
8004         Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
8005         Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
8006         Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
8007         Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
8008         Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
8009         Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
8010         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"),
8011         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"),
8012         Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
8013         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"),
8014         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"),
8015         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"),
8016         Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
8017         Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
8018         Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
8019         Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
8020         Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
8021         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"),
8022         Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
8023         Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
8024         Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
8025         Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
8026         Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
8027         Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
8028         Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
8029         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"),
8030         Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
8031         Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
8032         Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
8033         Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
8034         Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
8035         Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
8036         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'"),
8037         Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
8038         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"),
8039         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}'"),
8040         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}'"),
8041         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"),
8042         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"),
8043         Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"),
8044         Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"),
8045         Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."),
8046         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"),
8047         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"),
8048         Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
8049         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"),
8050         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"),
8051         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"),
8052         Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
8053         Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"),
8054         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"),
8055         Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
8056         Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"),
8057         Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
8058         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."),
8059         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'."),
8060         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?"),
8061         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"),
8062         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."),
8063         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."),
8064         constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
8065         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."),
8066         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."),
8067         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}'."),
8068         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."),
8069         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"),
8070         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"),
8071         _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"),
8072         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."),
8073         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."),
8074         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."),
8075         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."),
8076         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."),
8077         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."),
8078         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."),
8079         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."),
8080         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."),
8081         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."),
8082         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."),
8083     };
8084 })(ts || (ts = {}));
8085 var ts;
8086 (function (ts) {
8087     var _a;
8088     /* @internal */
8089     function tokenIsIdentifierOrKeyword(token) {
8090         return token >= 75 /* Identifier */;
8091     }
8092     ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
8093     /* @internal */
8094     function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
8095         return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
8096     }
8097     ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
8098     var textToKeywordObj = (_a = {
8099             abstract: 122 /* AbstractKeyword */,
8100             any: 125 /* AnyKeyword */,
8101             as: 123 /* AsKeyword */,
8102             asserts: 124 /* AssertsKeyword */,
8103             bigint: 151 /* BigIntKeyword */,
8104             boolean: 128 /* BooleanKeyword */,
8105             break: 77 /* BreakKeyword */,
8106             case: 78 /* CaseKeyword */,
8107             catch: 79 /* CatchKeyword */,
8108             class: 80 /* ClassKeyword */,
8109             continue: 82 /* ContinueKeyword */,
8110             const: 81 /* ConstKeyword */
8111         },
8112         _a["" + "constructor"] = 129 /* ConstructorKeyword */,
8113         _a.debugger = 83 /* DebuggerKeyword */,
8114         _a.declare = 130 /* DeclareKeyword */,
8115         _a.default = 84 /* DefaultKeyword */,
8116         _a.delete = 85 /* DeleteKeyword */,
8117         _a.do = 86 /* DoKeyword */,
8118         _a.else = 87 /* ElseKeyword */,
8119         _a.enum = 88 /* EnumKeyword */,
8120         _a.export = 89 /* ExportKeyword */,
8121         _a.extends = 90 /* ExtendsKeyword */,
8122         _a.false = 91 /* FalseKeyword */,
8123         _a.finally = 92 /* FinallyKeyword */,
8124         _a.for = 93 /* ForKeyword */,
8125         _a.from = 149 /* FromKeyword */,
8126         _a.function = 94 /* FunctionKeyword */,
8127         _a.get = 131 /* GetKeyword */,
8128         _a.if = 95 /* IfKeyword */,
8129         _a.implements = 113 /* ImplementsKeyword */,
8130         _a.import = 96 /* ImportKeyword */,
8131         _a.in = 97 /* InKeyword */,
8132         _a.infer = 132 /* InferKeyword */,
8133         _a.instanceof = 98 /* InstanceOfKeyword */,
8134         _a.interface = 114 /* InterfaceKeyword */,
8135         _a.is = 133 /* IsKeyword */,
8136         _a.keyof = 134 /* KeyOfKeyword */,
8137         _a.let = 115 /* LetKeyword */,
8138         _a.module = 135 /* ModuleKeyword */,
8139         _a.namespace = 136 /* NamespaceKeyword */,
8140         _a.never = 137 /* NeverKeyword */,
8141         _a.new = 99 /* NewKeyword */,
8142         _a.null = 100 /* NullKeyword */,
8143         _a.number = 140 /* NumberKeyword */,
8144         _a.object = 141 /* ObjectKeyword */,
8145         _a.package = 116 /* PackageKeyword */,
8146         _a.private = 117 /* PrivateKeyword */,
8147         _a.protected = 118 /* ProtectedKeyword */,
8148         _a.public = 119 /* PublicKeyword */,
8149         _a.readonly = 138 /* ReadonlyKeyword */,
8150         _a.require = 139 /* RequireKeyword */,
8151         _a.global = 150 /* GlobalKeyword */,
8152         _a.return = 101 /* ReturnKeyword */,
8153         _a.set = 142 /* SetKeyword */,
8154         _a.static = 120 /* StaticKeyword */,
8155         _a.string = 143 /* StringKeyword */,
8156         _a.super = 102 /* SuperKeyword */,
8157         _a.switch = 103 /* SwitchKeyword */,
8158         _a.symbol = 144 /* SymbolKeyword */,
8159         _a.this = 104 /* ThisKeyword */,
8160         _a.throw = 105 /* ThrowKeyword */,
8161         _a.true = 106 /* TrueKeyword */,
8162         _a.try = 107 /* TryKeyword */,
8163         _a.type = 145 /* TypeKeyword */,
8164         _a.typeof = 108 /* TypeOfKeyword */,
8165         _a.undefined = 146 /* UndefinedKeyword */,
8166         _a.unique = 147 /* UniqueKeyword */,
8167         _a.unknown = 148 /* UnknownKeyword */,
8168         _a.var = 109 /* VarKeyword */,
8169         _a.void = 110 /* VoidKeyword */,
8170         _a.while = 111 /* WhileKeyword */,
8171         _a.with = 112 /* WithKeyword */,
8172         _a.yield = 121 /* YieldKeyword */,
8173         _a.async = 126 /* AsyncKeyword */,
8174         _a.await = 127 /* AwaitKeyword */,
8175         _a.of = 152 /* OfKeyword */,
8176         _a);
8177     var textToKeyword = ts.createMapFromTemplate(textToKeywordObj);
8178     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 */ }));
8179     /*
8180         As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
8181         IdentifierStart ::
8182             Can contain Unicode 3.0.0 categories:
8183             Uppercase letter (Lu),
8184             Lowercase letter (Ll),
8185             Titlecase letter (Lt),
8186             Modifier letter (Lm),
8187             Other letter (Lo), or
8188             Letter number (Nl).
8189         IdentifierPart :: =
8190             Can contain IdentifierStart + Unicode 3.0.0 categories:
8191             Non-spacing mark (Mn),
8192             Combining spacing mark (Mc),
8193             Decimal number (Nd), or
8194             Connector punctuation (Pc).
8195
8196         Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
8197         http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
8198     */
8199     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,];
8200     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,];
8201     /*
8202         As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
8203         IdentifierStart ::
8204             Can contain Unicode 6.2 categories:
8205             Uppercase letter (Lu),
8206             Lowercase letter (Ll),
8207             Titlecase letter (Lt),
8208             Modifier letter (Lm),
8209             Other letter (Lo), or
8210             Letter number (Nl).
8211         IdentifierPart ::
8212             Can contain IdentifierStart + Unicode 6.2 categories:
8213             Non-spacing mark (Mn),
8214             Combining spacing mark (Mc),
8215             Decimal number (Nd),
8216             Connector punctuation (Pc),
8217             <ZWNJ>, or
8218             <ZWJ>.
8219
8220         Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
8221         http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
8222     */
8223     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,];
8224     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,];
8225     /**
8226      * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
8227      * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
8228      * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
8229      * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
8230      */
8231     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];
8232     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];
8233     /**
8234      * Test for whether a single line comment's text contains a directive.
8235      */
8236     var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
8237     /**
8238      * Test for whether a multi-line comment's last line contains a directive.
8239      */
8240     var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
8241     function lookupInUnicodeMap(code, map) {
8242         // Bail out quickly if it couldn't possibly be in the map.
8243         if (code < map[0]) {
8244             return false;
8245         }
8246         // Perform binary search in one of the Unicode range maps
8247         var lo = 0;
8248         var hi = map.length;
8249         var mid;
8250         while (lo + 1 < hi) {
8251             mid = lo + (hi - lo) / 2;
8252             // mid has to be even to catch a range's beginning
8253             mid -= mid % 2;
8254             if (map[mid] <= code && code <= map[mid + 1]) {
8255                 return true;
8256             }
8257             if (code < map[mid]) {
8258                 hi = mid;
8259             }
8260             else {
8261                 lo = mid + 2;
8262             }
8263         }
8264         return false;
8265     }
8266     /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
8267         return languageVersion >= 2 /* ES2015 */ ?
8268             lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
8269             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
8270                 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
8271     }
8272     ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
8273     function isUnicodeIdentifierPart(code, languageVersion) {
8274         return languageVersion >= 2 /* ES2015 */ ?
8275             lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
8276             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
8277                 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
8278     }
8279     function makeReverseMap(source) {
8280         var result = [];
8281         source.forEach(function (value, name) {
8282             result[value] = name;
8283         });
8284         return result;
8285     }
8286     var tokenStrings = makeReverseMap(textToToken);
8287     function tokenToString(t) {
8288         return tokenStrings[t];
8289     }
8290     ts.tokenToString = tokenToString;
8291     /* @internal */
8292     function stringToToken(s) {
8293         return textToToken.get(s);
8294     }
8295     ts.stringToToken = stringToToken;
8296     /* @internal */
8297     function computeLineStarts(text) {
8298         var result = new Array();
8299         var pos = 0;
8300         var lineStart = 0;
8301         while (pos < text.length) {
8302             var ch = text.charCodeAt(pos);
8303             pos++;
8304             switch (ch) {
8305                 case 13 /* carriageReturn */:
8306                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
8307                         pos++;
8308                     }
8309                 // falls through
8310                 case 10 /* lineFeed */:
8311                     result.push(lineStart);
8312                     lineStart = pos;
8313                     break;
8314                 default:
8315                     if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
8316                         result.push(lineStart);
8317                         lineStart = pos;
8318                     }
8319                     break;
8320             }
8321         }
8322         result.push(lineStart);
8323         return result;
8324     }
8325     ts.computeLineStarts = computeLineStarts;
8326     function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
8327         return sourceFile.getPositionOfLineAndCharacter ?
8328             sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
8329             computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
8330     }
8331     ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
8332     /* @internal */
8333     function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
8334         if (line < 0 || line >= lineStarts.length) {
8335             if (allowEdits) {
8336                 // Clamp line to nearest allowable value
8337                 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
8338             }
8339             else {
8340                 ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
8341             }
8342         }
8343         var res = lineStarts[line] + character;
8344         if (allowEdits) {
8345             // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
8346             // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
8347             // apply them to the computed position to improve accuracy
8348             return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
8349         }
8350         if (line < lineStarts.length - 1) {
8351             ts.Debug.assert(res < lineStarts[line + 1]);
8352         }
8353         else if (debugText !== undefined) {
8354             ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
8355         }
8356         return res;
8357     }
8358     ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
8359     /* @internal */
8360     function getLineStarts(sourceFile) {
8361         return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
8362     }
8363     ts.getLineStarts = getLineStarts;
8364     /* @internal */
8365     function computeLineAndCharacterOfPosition(lineStarts, position) {
8366         var lineNumber = computeLineOfPosition(lineStarts, position);
8367         return {
8368             line: lineNumber,
8369             character: position - lineStarts[lineNumber]
8370         };
8371     }
8372     ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
8373     /**
8374      * @internal
8375      * We assume the first line starts at position 0 and 'position' is non-negative.
8376      */
8377     function computeLineOfPosition(lineStarts, position, lowerBound) {
8378         var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
8379         if (lineNumber < 0) {
8380             // If the actual position was not found,
8381             // the binary search returns the 2's-complement of the next line start
8382             // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
8383             // then the search will return -2.
8384             //
8385             // We want the index of the previous line start, so we subtract 1.
8386             // Review 2's-complement if this is confusing.
8387             lineNumber = ~lineNumber - 1;
8388             ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
8389         }
8390         return lineNumber;
8391     }
8392     ts.computeLineOfPosition = computeLineOfPosition;
8393     /** @internal */
8394     function getLinesBetweenPositions(sourceFile, pos1, pos2) {
8395         if (pos1 === pos2)
8396             return 0;
8397         var lineStarts = getLineStarts(sourceFile);
8398         var lower = Math.min(pos1, pos2);
8399         var isNegative = lower === pos2;
8400         var upper = isNegative ? pos1 : pos2;
8401         var lowerLine = computeLineOfPosition(lineStarts, lower);
8402         var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
8403         return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
8404     }
8405     ts.getLinesBetweenPositions = getLinesBetweenPositions;
8406     function getLineAndCharacterOfPosition(sourceFile, position) {
8407         return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
8408     }
8409     ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
8410     function isWhiteSpaceLike(ch) {
8411         return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
8412     }
8413     ts.isWhiteSpaceLike = isWhiteSpaceLike;
8414     /** Does not include line breaks. For that, see isWhiteSpaceLike. */
8415     function isWhiteSpaceSingleLine(ch) {
8416         // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
8417         // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
8418         return ch === 32 /* space */ ||
8419             ch === 9 /* tab */ ||
8420             ch === 11 /* verticalTab */ ||
8421             ch === 12 /* formFeed */ ||
8422             ch === 160 /* nonBreakingSpace */ ||
8423             ch === 133 /* nextLine */ ||
8424             ch === 5760 /* ogham */ ||
8425             ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
8426             ch === 8239 /* narrowNoBreakSpace */ ||
8427             ch === 8287 /* mathematicalSpace */ ||
8428             ch === 12288 /* ideographicSpace */ ||
8429             ch === 65279 /* byteOrderMark */;
8430     }
8431     ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
8432     function isLineBreak(ch) {
8433         // ES5 7.3:
8434         // The ECMAScript line terminator characters are listed in Table 3.
8435         //     Table 3: Line Terminator Characters
8436         //     Code Unit Value     Name                    Formal Name
8437         //     \u000A              Line Feed               <LF>
8438         //     \u000D              Carriage Return         <CR>
8439         //     \u2028              Line separator          <LS>
8440         //     \u2029              Paragraph separator     <PS>
8441         // Only the characters in Table 3 are treated as line terminators. Other new line or line
8442         // breaking characters are treated as white space but not as line terminators.
8443         return ch === 10 /* lineFeed */ ||
8444             ch === 13 /* carriageReturn */ ||
8445             ch === 8232 /* lineSeparator */ ||
8446             ch === 8233 /* paragraphSeparator */;
8447     }
8448     ts.isLineBreak = isLineBreak;
8449     function isDigit(ch) {
8450         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
8451     }
8452     function isHexDigit(ch) {
8453         return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
8454     }
8455     function isCodePoint(code) {
8456         return code <= 0x10FFFF;
8457     }
8458     /* @internal */
8459     function isOctalDigit(ch) {
8460         return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
8461     }
8462     ts.isOctalDigit = isOctalDigit;
8463     function couldStartTrivia(text, pos) {
8464         // Keep in sync with skipTrivia
8465         var ch = text.charCodeAt(pos);
8466         switch (ch) {
8467             case 13 /* carriageReturn */:
8468             case 10 /* lineFeed */:
8469             case 9 /* tab */:
8470             case 11 /* verticalTab */:
8471             case 12 /* formFeed */:
8472             case 32 /* space */:
8473             case 47 /* slash */:
8474             // starts of normal trivia
8475             // falls through
8476             case 60 /* lessThan */:
8477             case 124 /* bar */:
8478             case 61 /* equals */:
8479             case 62 /* greaterThan */:
8480                 // Starts of conflict marker trivia
8481                 return true;
8482             case 35 /* hash */:
8483                 // Only if its the beginning can we have #! trivia
8484                 return pos === 0;
8485             default:
8486                 return ch > 127 /* maxAsciiCharacter */;
8487         }
8488     }
8489     ts.couldStartTrivia = couldStartTrivia;
8490     /* @internal */
8491     function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
8492         if (stopAtComments === void 0) { stopAtComments = false; }
8493         if (ts.positionIsSynthesized(pos)) {
8494             return pos;
8495         }
8496         // Keep in sync with couldStartTrivia
8497         while (true) {
8498             var ch = text.charCodeAt(pos);
8499             switch (ch) {
8500                 case 13 /* carriageReturn */:
8501                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8502                         pos++;
8503                     }
8504                 // falls through
8505                 case 10 /* lineFeed */:
8506                     pos++;
8507                     if (stopAfterLineBreak) {
8508                         return pos;
8509                     }
8510                     continue;
8511                 case 9 /* tab */:
8512                 case 11 /* verticalTab */:
8513                 case 12 /* formFeed */:
8514                 case 32 /* space */:
8515                     pos++;
8516                     continue;
8517                 case 47 /* slash */:
8518                     if (stopAtComments) {
8519                         break;
8520                     }
8521                     if (text.charCodeAt(pos + 1) === 47 /* slash */) {
8522                         pos += 2;
8523                         while (pos < text.length) {
8524                             if (isLineBreak(text.charCodeAt(pos))) {
8525                                 break;
8526                             }
8527                             pos++;
8528                         }
8529                         continue;
8530                     }
8531                     if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
8532                         pos += 2;
8533                         while (pos < text.length) {
8534                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8535                                 pos += 2;
8536                                 break;
8537                             }
8538                             pos++;
8539                         }
8540                         continue;
8541                     }
8542                     break;
8543                 case 60 /* lessThan */:
8544                 case 124 /* bar */:
8545                 case 61 /* equals */:
8546                 case 62 /* greaterThan */:
8547                     if (isConflictMarkerTrivia(text, pos)) {
8548                         pos = scanConflictMarkerTrivia(text, pos);
8549                         continue;
8550                     }
8551                     break;
8552                 case 35 /* hash */:
8553                     if (pos === 0 && isShebangTrivia(text, pos)) {
8554                         pos = scanShebangTrivia(text, pos);
8555                         continue;
8556                     }
8557                     break;
8558                 default:
8559                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8560                         pos++;
8561                         continue;
8562                     }
8563                     break;
8564             }
8565             return pos;
8566         }
8567     }
8568     ts.skipTrivia = skipTrivia;
8569     // All conflict markers consist of the same character repeated seven times.  If it is
8570     // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
8571     var mergeConflictMarkerLength = "<<<<<<<".length;
8572     function isConflictMarkerTrivia(text, pos) {
8573         ts.Debug.assert(pos >= 0);
8574         // Conflict markers must be at the start of a line.
8575         if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
8576             var ch = text.charCodeAt(pos);
8577             if ((pos + mergeConflictMarkerLength) < text.length) {
8578                 for (var i = 0; i < mergeConflictMarkerLength; i++) {
8579                     if (text.charCodeAt(pos + i) !== ch) {
8580                         return false;
8581                     }
8582                 }
8583                 return ch === 61 /* equals */ ||
8584                     text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
8585             }
8586         }
8587         return false;
8588     }
8589     function scanConflictMarkerTrivia(text, pos, error) {
8590         if (error) {
8591             error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
8592         }
8593         var ch = text.charCodeAt(pos);
8594         var len = text.length;
8595         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
8596             while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
8597                 pos++;
8598             }
8599         }
8600         else {
8601             ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
8602             // Consume everything from the start of a ||||||| or ======= marker to the start
8603             // of the next ======= or >>>>>>> marker.
8604             while (pos < len) {
8605                 var currentChar = text.charCodeAt(pos);
8606                 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
8607                     break;
8608                 }
8609                 pos++;
8610             }
8611         }
8612         return pos;
8613     }
8614     var shebangTriviaRegex = /^#!.*/;
8615     /*@internal*/
8616     function isShebangTrivia(text, pos) {
8617         // Shebangs check must only be done at the start of the file
8618         ts.Debug.assert(pos === 0);
8619         return shebangTriviaRegex.test(text);
8620     }
8621     ts.isShebangTrivia = isShebangTrivia;
8622     /*@internal*/
8623     function scanShebangTrivia(text, pos) {
8624         var shebang = shebangTriviaRegex.exec(text)[0];
8625         pos = pos + shebang.length;
8626         return pos;
8627     }
8628     ts.scanShebangTrivia = scanShebangTrivia;
8629     /**
8630      * Invokes a callback for each comment range following the provided position.
8631      *
8632      * Single-line comment ranges include the leading double-slash characters but not the ending
8633      * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
8634      * asterisk-slash characters.
8635      *
8636      * @param reduce If true, accumulates the result of calling the callback in a fashion similar
8637      *      to reduceLeft. If false, iteration stops when the callback returns a truthy value.
8638      * @param text The source text to scan.
8639      * @param pos The position at which to start scanning.
8640      * @param trailing If false, whitespace is skipped until the first line break and comments
8641      *      between that location and the next token are returned. If true, comments occurring
8642      *      between the given position and the next line break are returned.
8643      * @param cb The callback to execute as each comment range is encountered.
8644      * @param state A state value to pass to each iteration of the callback.
8645      * @param initial An initial value to pass when accumulating results (when "reduce" is true).
8646      * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
8647      *      return value of the callback.
8648      */
8649     function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
8650         var pendingPos;
8651         var pendingEnd;
8652         var pendingKind;
8653         var pendingHasTrailingNewLine;
8654         var hasPendingCommentRange = false;
8655         var collecting = trailing;
8656         var accumulator = initial;
8657         if (pos === 0) {
8658             collecting = true;
8659             var shebang = getShebang(text);
8660             if (shebang) {
8661                 pos = shebang.length;
8662             }
8663         }
8664         scan: while (pos >= 0 && pos < text.length) {
8665             var ch = text.charCodeAt(pos);
8666             switch (ch) {
8667                 case 13 /* carriageReturn */:
8668                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8669                         pos++;
8670                     }
8671                 // falls through
8672                 case 10 /* lineFeed */:
8673                     pos++;
8674                     if (trailing) {
8675                         break scan;
8676                     }
8677                     collecting = true;
8678                     if (hasPendingCommentRange) {
8679                         pendingHasTrailingNewLine = true;
8680                     }
8681                     continue;
8682                 case 9 /* tab */:
8683                 case 11 /* verticalTab */:
8684                 case 12 /* formFeed */:
8685                 case 32 /* space */:
8686                     pos++;
8687                     continue;
8688                 case 47 /* slash */:
8689                     var nextChar = text.charCodeAt(pos + 1);
8690                     var hasTrailingNewLine = false;
8691                     if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
8692                         var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
8693                         var startPos = pos;
8694                         pos += 2;
8695                         if (nextChar === 47 /* slash */) {
8696                             while (pos < text.length) {
8697                                 if (isLineBreak(text.charCodeAt(pos))) {
8698                                     hasTrailingNewLine = true;
8699                                     break;
8700                                 }
8701                                 pos++;
8702                             }
8703                         }
8704                         else {
8705                             while (pos < text.length) {
8706                                 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8707                                     pos += 2;
8708                                     break;
8709                                 }
8710                                 pos++;
8711                             }
8712                         }
8713                         if (collecting) {
8714                             if (hasPendingCommentRange) {
8715                                 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8716                                 if (!reduce && accumulator) {
8717                                     // If we are not reducing and we have a truthy result, return it.
8718                                     return accumulator;
8719                                 }
8720                             }
8721                             pendingPos = startPos;
8722                             pendingEnd = pos;
8723                             pendingKind = kind;
8724                             pendingHasTrailingNewLine = hasTrailingNewLine;
8725                             hasPendingCommentRange = true;
8726                         }
8727                         continue;
8728                     }
8729                     break scan;
8730                 default:
8731                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8732                         if (hasPendingCommentRange && isLineBreak(ch)) {
8733                             pendingHasTrailingNewLine = true;
8734                         }
8735                         pos++;
8736                         continue;
8737                     }
8738                     break scan;
8739             }
8740         }
8741         if (hasPendingCommentRange) {
8742             accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8743         }
8744         return accumulator;
8745     }
8746     function forEachLeadingCommentRange(text, pos, cb, state) {
8747         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
8748     }
8749     ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
8750     function forEachTrailingCommentRange(text, pos, cb, state) {
8751         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
8752     }
8753     ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
8754     function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
8755         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
8756     }
8757     ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
8758     function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
8759         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
8760     }
8761     ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
8762     function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
8763         if (!comments) {
8764             comments = [];
8765         }
8766         comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
8767         return comments;
8768     }
8769     function getLeadingCommentRanges(text, pos) {
8770         return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8771     }
8772     ts.getLeadingCommentRanges = getLeadingCommentRanges;
8773     function getTrailingCommentRanges(text, pos) {
8774         return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8775     }
8776     ts.getTrailingCommentRanges = getTrailingCommentRanges;
8777     /** Optionally, get the shebang */
8778     function getShebang(text) {
8779         var match = shebangTriviaRegex.exec(text);
8780         if (match) {
8781             return match[0];
8782         }
8783     }
8784     ts.getShebang = getShebang;
8785     function isIdentifierStart(ch, languageVersion) {
8786         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8787             ch === 36 /* $ */ || ch === 95 /* _ */ ||
8788             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
8789     }
8790     ts.isIdentifierStart = isIdentifierStart;
8791     function isIdentifierPart(ch, languageVersion, identifierVariant) {
8792         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8793             ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
8794             // "-" and ":" are valid in JSX Identifiers
8795             (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
8796             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
8797     }
8798     ts.isIdentifierPart = isIdentifierPart;
8799     /* @internal */
8800     function isIdentifierText(name, languageVersion, identifierVariant) {
8801         var ch = codePointAt(name, 0);
8802         if (!isIdentifierStart(ch, languageVersion)) {
8803             return false;
8804         }
8805         for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
8806             if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
8807                 return false;
8808             }
8809         }
8810         return true;
8811     }
8812     ts.isIdentifierText = isIdentifierText;
8813     // Creates a scanner over a (possibly unspecified) range of a piece of text.
8814     function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
8815         if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
8816         var text = textInitial;
8817         // Current position (end position of text of current token)
8818         var pos;
8819         // end of text
8820         var end;
8821         // Start position of whitespace before current token
8822         var startPos;
8823         // Start position of text of current token
8824         var tokenPos;
8825         var token;
8826         var tokenValue;
8827         var tokenFlags;
8828         var commentDirectives;
8829         var inJSDocType = 0;
8830         setText(text, start, length);
8831         var scanner = {
8832             getStartPos: function () { return startPos; },
8833             getTextPos: function () { return pos; },
8834             getToken: function () { return token; },
8835             getTokenPos: function () { return tokenPos; },
8836             getTokenText: function () { return text.substring(tokenPos, pos); },
8837             getTokenValue: function () { return tokenValue; },
8838             hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
8839             hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
8840             hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
8841             isIdentifier: function () { return token === 75 /* Identifier */ || token > 112 /* LastReservedWord */; },
8842             isReservedWord: function () { return token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */; },
8843             isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
8844             getCommentDirectives: function () { return commentDirectives; },
8845             getTokenFlags: function () { return tokenFlags; },
8846             reScanGreaterToken: reScanGreaterToken,
8847             reScanSlashToken: reScanSlashToken,
8848             reScanTemplateToken: reScanTemplateToken,
8849             reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
8850             scanJsxIdentifier: scanJsxIdentifier,
8851             scanJsxAttributeValue: scanJsxAttributeValue,
8852             reScanJsxAttributeValue: reScanJsxAttributeValue,
8853             reScanJsxToken: reScanJsxToken,
8854             reScanLessThanToken: reScanLessThanToken,
8855             reScanQuestionToken: reScanQuestionToken,
8856             scanJsxToken: scanJsxToken,
8857             scanJsDocToken: scanJsDocToken,
8858             scan: scan,
8859             getText: getText,
8860             clearCommentDirectives: clearCommentDirectives,
8861             setText: setText,
8862             setScriptTarget: setScriptTarget,
8863             setLanguageVariant: setLanguageVariant,
8864             setOnError: setOnError,
8865             setTextPos: setTextPos,
8866             setInJSDocType: setInJSDocType,
8867             tryScan: tryScan,
8868             lookAhead: lookAhead,
8869             scanRange: scanRange,
8870         };
8871         if (ts.Debug.isDebugging) {
8872             Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
8873                 get: function () {
8874                     var text = scanner.getText();
8875                     return text.slice(0, scanner.getStartPos()) + "â•‘" + text.slice(scanner.getStartPos());
8876                 },
8877             });
8878         }
8879         return scanner;
8880         function error(message, errPos, length) {
8881             if (errPos === void 0) { errPos = pos; }
8882             if (onError) {
8883                 var oldPos = pos;
8884                 pos = errPos;
8885                 onError(message, length || 0);
8886                 pos = oldPos;
8887             }
8888         }
8889         function scanNumberFragment() {
8890             var start = pos;
8891             var allowSeparator = false;
8892             var isPreviousTokenSeparator = false;
8893             var result = "";
8894             while (true) {
8895                 var ch = text.charCodeAt(pos);
8896                 if (ch === 95 /* _ */) {
8897                     tokenFlags |= 512 /* ContainsSeparator */;
8898                     if (allowSeparator) {
8899                         allowSeparator = false;
8900                         isPreviousTokenSeparator = true;
8901                         result += text.substring(start, pos);
8902                     }
8903                     else if (isPreviousTokenSeparator) {
8904                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
8905                     }
8906                     else {
8907                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
8908                     }
8909                     pos++;
8910                     start = pos;
8911                     continue;
8912                 }
8913                 if (isDigit(ch)) {
8914                     allowSeparator = true;
8915                     isPreviousTokenSeparator = false;
8916                     pos++;
8917                     continue;
8918                 }
8919                 break;
8920             }
8921             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
8922                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
8923             }
8924             return result + text.substring(start, pos);
8925         }
8926         function scanNumber() {
8927             var start = pos;
8928             var mainFragment = scanNumberFragment();
8929             var decimalFragment;
8930             var scientificFragment;
8931             if (text.charCodeAt(pos) === 46 /* dot */) {
8932                 pos++;
8933                 decimalFragment = scanNumberFragment();
8934             }
8935             var end = pos;
8936             if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
8937                 pos++;
8938                 tokenFlags |= 16 /* Scientific */;
8939                 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
8940                     pos++;
8941                 var preNumericPart = pos;
8942                 var finalFragment = scanNumberFragment();
8943                 if (!finalFragment) {
8944                     error(ts.Diagnostics.Digit_expected);
8945                 }
8946                 else {
8947                     scientificFragment = text.substring(end, preNumericPart) + finalFragment;
8948                     end = pos;
8949                 }
8950             }
8951             var result;
8952             if (tokenFlags & 512 /* ContainsSeparator */) {
8953                 result = mainFragment;
8954                 if (decimalFragment) {
8955                     result += "." + decimalFragment;
8956                 }
8957                 if (scientificFragment) {
8958                     result += scientificFragment;
8959                 }
8960             }
8961             else {
8962                 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
8963             }
8964             if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
8965                 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
8966                 return {
8967                     type: 8 /* NumericLiteral */,
8968                     value: "" + +result // if value is not an integer, it can be safely coerced to a number
8969                 };
8970             }
8971             else {
8972                 tokenValue = result;
8973                 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
8974                 checkForIdentifierStartAfterNumericLiteral(start);
8975                 return { type: type, value: tokenValue };
8976             }
8977         }
8978         function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
8979             if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
8980                 return;
8981             }
8982             var identifierStart = pos;
8983             var length = scanIdentifierParts().length;
8984             if (length === 1 && text[identifierStart] === "n") {
8985                 if (isScientific) {
8986                     error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
8987                 }
8988                 else {
8989                     error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
8990                 }
8991             }
8992             else {
8993                 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
8994                 pos = identifierStart;
8995             }
8996         }
8997         function scanOctalDigits() {
8998             var start = pos;
8999             while (isOctalDigit(text.charCodeAt(pos))) {
9000                 pos++;
9001             }
9002             return +(text.substring(start, pos));
9003         }
9004         /**
9005          * Scans the given number of hexadecimal digits in the text,
9006          * returning -1 if the given number is unavailable.
9007          */
9008         function scanExactNumberOfHexDigits(count, canHaveSeparators) {
9009             var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
9010             return valueString ? parseInt(valueString, 16) : -1;
9011         }
9012         /**
9013          * Scans as many hexadecimal digits as are available in the text,
9014          * returning "" if the given number of digits was unavailable.
9015          */
9016         function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
9017             return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
9018         }
9019         function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
9020             var valueChars = [];
9021             var allowSeparator = false;
9022             var isPreviousTokenSeparator = false;
9023             while (valueChars.length < minCount || scanAsManyAsPossible) {
9024                 var ch = text.charCodeAt(pos);
9025                 if (canHaveSeparators && ch === 95 /* _ */) {
9026                     tokenFlags |= 512 /* ContainsSeparator */;
9027                     if (allowSeparator) {
9028                         allowSeparator = false;
9029                         isPreviousTokenSeparator = true;
9030                     }
9031                     else if (isPreviousTokenSeparator) {
9032                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9033                     }
9034                     else {
9035                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9036                     }
9037                     pos++;
9038                     continue;
9039                 }
9040                 allowSeparator = canHaveSeparators;
9041                 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
9042                     ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
9043                 }
9044                 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
9045                     (ch >= 97 /* a */ && ch <= 102 /* f */))) {
9046                     break;
9047                 }
9048                 valueChars.push(ch);
9049                 pos++;
9050                 isPreviousTokenSeparator = false;
9051             }
9052             if (valueChars.length < minCount) {
9053                 valueChars = [];
9054             }
9055             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9056                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9057             }
9058             return String.fromCharCode.apply(String, valueChars);
9059         }
9060         function scanString(jsxAttributeString) {
9061             if (jsxAttributeString === void 0) { jsxAttributeString = false; }
9062             var quote = text.charCodeAt(pos);
9063             pos++;
9064             var result = "";
9065             var start = pos;
9066             while (true) {
9067                 if (pos >= end) {
9068                     result += text.substring(start, pos);
9069                     tokenFlags |= 4 /* Unterminated */;
9070                     error(ts.Diagnostics.Unterminated_string_literal);
9071                     break;
9072                 }
9073                 var ch = text.charCodeAt(pos);
9074                 if (ch === quote) {
9075                     result += text.substring(start, pos);
9076                     pos++;
9077                     break;
9078                 }
9079                 if (ch === 92 /* backslash */ && !jsxAttributeString) {
9080                     result += text.substring(start, pos);
9081                     result += scanEscapeSequence();
9082                     start = pos;
9083                     continue;
9084                 }
9085                 if (isLineBreak(ch) && !jsxAttributeString) {
9086                     result += text.substring(start, pos);
9087                     tokenFlags |= 4 /* Unterminated */;
9088                     error(ts.Diagnostics.Unterminated_string_literal);
9089                     break;
9090                 }
9091                 pos++;
9092             }
9093             return result;
9094         }
9095         /**
9096          * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
9097          * a literal component of a TemplateExpression.
9098          */
9099         function scanTemplateAndSetTokenValue(isTaggedTemplate) {
9100             var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
9101             pos++;
9102             var start = pos;
9103             var contents = "";
9104             var resultingToken;
9105             while (true) {
9106                 if (pos >= end) {
9107                     contents += text.substring(start, pos);
9108                     tokenFlags |= 4 /* Unterminated */;
9109                     error(ts.Diagnostics.Unterminated_template_literal);
9110                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9111                     break;
9112                 }
9113                 var currChar = text.charCodeAt(pos);
9114                 // '`'
9115                 if (currChar === 96 /* backtick */) {
9116                     contents += text.substring(start, pos);
9117                     pos++;
9118                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9119                     break;
9120                 }
9121                 // '${'
9122                 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
9123                     contents += text.substring(start, pos);
9124                     pos += 2;
9125                     resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
9126                     break;
9127                 }
9128                 // Escape character
9129                 if (currChar === 92 /* backslash */) {
9130                     contents += text.substring(start, pos);
9131                     contents += scanEscapeSequence(isTaggedTemplate);
9132                     start = pos;
9133                     continue;
9134                 }
9135                 // Speculated ECMAScript 6 Spec 11.8.6.1:
9136                 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
9137                 if (currChar === 13 /* carriageReturn */) {
9138                     contents += text.substring(start, pos);
9139                     pos++;
9140                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9141                         pos++;
9142                     }
9143                     contents += "\n";
9144                     start = pos;
9145                     continue;
9146                 }
9147                 pos++;
9148             }
9149             ts.Debug.assert(resultingToken !== undefined);
9150             tokenValue = contents;
9151             return resultingToken;
9152         }
9153         function scanEscapeSequence(isTaggedTemplate) {
9154             var start = pos;
9155             pos++;
9156             if (pos >= end) {
9157                 error(ts.Diagnostics.Unexpected_end_of_text);
9158                 return "";
9159             }
9160             var ch = text.charCodeAt(pos);
9161             pos++;
9162             switch (ch) {
9163                 case 48 /* _0 */:
9164                     // '\01'
9165                     if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
9166                         pos++;
9167                         tokenFlags |= 2048 /* ContainsInvalidEscape */;
9168                         return text.substring(start, pos);
9169                     }
9170                     return "\0";
9171                 case 98 /* b */:
9172                     return "\b";
9173                 case 116 /* t */:
9174                     return "\t";
9175                 case 110 /* n */:
9176                     return "\n";
9177                 case 118 /* v */:
9178                     return "\v";
9179                 case 102 /* f */:
9180                     return "\f";
9181                 case 114 /* r */:
9182                     return "\r";
9183                 case 39 /* singleQuote */:
9184                     return "\'";
9185                 case 34 /* doubleQuote */:
9186                     return "\"";
9187                 case 117 /* u */:
9188                     if (isTaggedTemplate) {
9189                         // '\u' or '\u0' or '\u00' or '\u000'
9190                         for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
9191                             if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
9192                                 pos = escapePos;
9193                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9194                                 return text.substring(start, pos);
9195                             }
9196                         }
9197                     }
9198                     // '\u{DDDDDDDD}'
9199                     if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
9200                         pos++;
9201                         // '\u{'
9202                         if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
9203                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9204                             return text.substring(start, pos);
9205                         }
9206                         if (isTaggedTemplate) {
9207                             var savePos = pos;
9208                             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9209                             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9210                             // '\u{Not Code Point' or '\u{CodePoint'
9211                             if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
9212                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9213                                 return text.substring(start, pos);
9214                             }
9215                             else {
9216                                 pos = savePos;
9217                             }
9218                         }
9219                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9220                         return scanExtendedUnicodeEscape();
9221                     }
9222                     tokenFlags |= 1024 /* UnicodeEscape */;
9223                     // '\uDDDD'
9224                     return scanHexadecimalEscape(/*numDigits*/ 4);
9225                 case 120 /* x */:
9226                     if (isTaggedTemplate) {
9227                         if (!isHexDigit(text.charCodeAt(pos))) {
9228                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9229                             return text.substring(start, pos);
9230                         }
9231                         else if (!isHexDigit(text.charCodeAt(pos + 1))) {
9232                             pos++;
9233                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9234                             return text.substring(start, pos);
9235                         }
9236                     }
9237                     // '\xDD'
9238                     return scanHexadecimalEscape(/*numDigits*/ 2);
9239                 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
9240                 // the line terminator is interpreted to be "the empty code unit sequence".
9241                 case 13 /* carriageReturn */:
9242                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9243                         pos++;
9244                     }
9245                 // falls through
9246                 case 10 /* lineFeed */:
9247                 case 8232 /* lineSeparator */:
9248                 case 8233 /* paragraphSeparator */:
9249                     return "";
9250                 default:
9251                     return String.fromCharCode(ch);
9252             }
9253         }
9254         function scanHexadecimalEscape(numDigits) {
9255             var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
9256             if (escapedValue >= 0) {
9257                 return String.fromCharCode(escapedValue);
9258             }
9259             else {
9260                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9261                 return "";
9262             }
9263         }
9264         function scanExtendedUnicodeEscape() {
9265             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9266             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9267             var isInvalidExtendedEscape = false;
9268             // Validate the value of the digit
9269             if (escapedValue < 0) {
9270                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9271                 isInvalidExtendedEscape = true;
9272             }
9273             else if (escapedValue > 0x10FFFF) {
9274                 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
9275                 isInvalidExtendedEscape = true;
9276             }
9277             if (pos >= end) {
9278                 error(ts.Diagnostics.Unexpected_end_of_text);
9279                 isInvalidExtendedEscape = true;
9280             }
9281             else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
9282                 // Only swallow the following character up if it's a '}'.
9283                 pos++;
9284             }
9285             else {
9286                 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
9287                 isInvalidExtendedEscape = true;
9288             }
9289             if (isInvalidExtendedEscape) {
9290                 return "";
9291             }
9292             return utf16EncodeAsString(escapedValue);
9293         }
9294         // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
9295         // and return code point value if valid Unicode escape is found. Otherwise return -1.
9296         function peekUnicodeEscape() {
9297             if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
9298                 var start_1 = pos;
9299                 pos += 2;
9300                 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
9301                 pos = start_1;
9302                 return value;
9303             }
9304             return -1;
9305         }
9306         function peekExtendedUnicodeEscape() {
9307             if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
9308                 var start_2 = pos;
9309                 pos += 3;
9310                 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9311                 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9312                 pos = start_2;
9313                 return escapedValue;
9314             }
9315             return -1;
9316         }
9317         function scanIdentifierParts() {
9318             var result = "";
9319             var start = pos;
9320             while (pos < end) {
9321                 var ch = codePointAt(text, pos);
9322                 if (isIdentifierPart(ch, languageVersion)) {
9323                     pos += charSize(ch);
9324                 }
9325                 else if (ch === 92 /* backslash */) {
9326                     ch = peekExtendedUnicodeEscape();
9327                     if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
9328                         pos += 3;
9329                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9330                         result += scanExtendedUnicodeEscape();
9331                         start = pos;
9332                         continue;
9333                     }
9334                     ch = peekUnicodeEscape();
9335                     if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
9336                         break;
9337                     }
9338                     tokenFlags |= 1024 /* UnicodeEscape */;
9339                     result += text.substring(start, pos);
9340                     result += utf16EncodeAsString(ch);
9341                     // Valid Unicode escape is always six characters
9342                     pos += 6;
9343                     start = pos;
9344                 }
9345                 else {
9346                     break;
9347                 }
9348             }
9349             result += text.substring(start, pos);
9350             return result;
9351         }
9352         function getIdentifierToken() {
9353             // Reserved words are between 2 and 11 characters long and start with a lowercase letter
9354             var len = tokenValue.length;
9355             if (len >= 2 && len <= 11) {
9356                 var ch = tokenValue.charCodeAt(0);
9357                 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
9358                     var keyword = textToKeyword.get(tokenValue);
9359                     if (keyword !== undefined) {
9360                         return token = keyword;
9361                     }
9362                 }
9363             }
9364             return token = 75 /* Identifier */;
9365         }
9366         function scanBinaryOrOctalDigits(base) {
9367             var value = "";
9368             // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
9369             // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
9370             var separatorAllowed = false;
9371             var isPreviousTokenSeparator = false;
9372             while (true) {
9373                 var ch = text.charCodeAt(pos);
9374                 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
9375                 if (ch === 95 /* _ */) {
9376                     tokenFlags |= 512 /* ContainsSeparator */;
9377                     if (separatorAllowed) {
9378                         separatorAllowed = false;
9379                         isPreviousTokenSeparator = true;
9380                     }
9381                     else if (isPreviousTokenSeparator) {
9382                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9383                     }
9384                     else {
9385                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9386                     }
9387                     pos++;
9388                     continue;
9389                 }
9390                 separatorAllowed = true;
9391                 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
9392                     break;
9393                 }
9394                 value += text[pos];
9395                 pos++;
9396                 isPreviousTokenSeparator = false;
9397             }
9398             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9399                 // Literal ends with underscore - not allowed
9400                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9401             }
9402             return value;
9403         }
9404         function checkBigIntSuffix() {
9405             if (text.charCodeAt(pos) === 110 /* n */) {
9406                 tokenValue += "n";
9407                 // Use base 10 instead of base 2 or base 8 for shorter literals
9408                 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
9409                     tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
9410                 }
9411                 pos++;
9412                 return 9 /* BigIntLiteral */;
9413             }
9414             else { // not a bigint, so can convert to number in simplified form
9415                 // Number() may not support 0b or 0o, so use parseInt() instead
9416                 var numericValue = tokenFlags & 128 /* BinarySpecifier */
9417                     ? parseInt(tokenValue.slice(2), 2) // skip "0b"
9418                     : tokenFlags & 256 /* OctalSpecifier */
9419                         ? parseInt(tokenValue.slice(2), 8) // skip "0o"
9420                         : +tokenValue;
9421                 tokenValue = "" + numericValue;
9422                 return 8 /* NumericLiteral */;
9423             }
9424         }
9425         function scan() {
9426             var _a;
9427             startPos = pos;
9428             tokenFlags = 0 /* None */;
9429             var asteriskSeen = false;
9430             while (true) {
9431                 tokenPos = pos;
9432                 if (pos >= end) {
9433                     return token = 1 /* EndOfFileToken */;
9434                 }
9435                 var ch = codePointAt(text, pos);
9436                 // Special handling for shebang
9437                 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
9438                     pos = scanShebangTrivia(text, pos);
9439                     if (skipTrivia) {
9440                         continue;
9441                     }
9442                     else {
9443                         return token = 6 /* ShebangTrivia */;
9444                     }
9445                 }
9446                 switch (ch) {
9447                     case 10 /* lineFeed */:
9448                     case 13 /* carriageReturn */:
9449                         tokenFlags |= 1 /* PrecedingLineBreak */;
9450                         if (skipTrivia) {
9451                             pos++;
9452                             continue;
9453                         }
9454                         else {
9455                             if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9456                                 // consume both CR and LF
9457                                 pos += 2;
9458                             }
9459                             else {
9460                                 pos++;
9461                             }
9462                             return token = 4 /* NewLineTrivia */;
9463                         }
9464                     case 9 /* tab */:
9465                     case 11 /* verticalTab */:
9466                     case 12 /* formFeed */:
9467                     case 32 /* space */:
9468                     case 160 /* nonBreakingSpace */:
9469                     case 5760 /* ogham */:
9470                     case 8192 /* enQuad */:
9471                     case 8193 /* emQuad */:
9472                     case 8194 /* enSpace */:
9473                     case 8195 /* emSpace */:
9474                     case 8196 /* threePerEmSpace */:
9475                     case 8197 /* fourPerEmSpace */:
9476                     case 8198 /* sixPerEmSpace */:
9477                     case 8199 /* figureSpace */:
9478                     case 8200 /* punctuationSpace */:
9479                     case 8201 /* thinSpace */:
9480                     case 8202 /* hairSpace */:
9481                     case 8203 /* zeroWidthSpace */:
9482                     case 8239 /* narrowNoBreakSpace */:
9483                     case 8287 /* mathematicalSpace */:
9484                     case 12288 /* ideographicSpace */:
9485                     case 65279 /* byteOrderMark */:
9486                         if (skipTrivia) {
9487                             pos++;
9488                             continue;
9489                         }
9490                         else {
9491                             while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
9492                                 pos++;
9493                             }
9494                             return token = 5 /* WhitespaceTrivia */;
9495                         }
9496                     case 33 /* exclamation */:
9497                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9498                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9499                                 return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
9500                             }
9501                             return pos += 2, token = 35 /* ExclamationEqualsToken */;
9502                         }
9503                         pos++;
9504                         return token = 53 /* ExclamationToken */;
9505                     case 34 /* doubleQuote */:
9506                     case 39 /* singleQuote */:
9507                         tokenValue = scanString();
9508                         return token = 10 /* StringLiteral */;
9509                     case 96 /* backtick */:
9510                         return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
9511                     case 37 /* percent */:
9512                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9513                             return pos += 2, token = 68 /* PercentEqualsToken */;
9514                         }
9515                         pos++;
9516                         return token = 44 /* PercentToken */;
9517                     case 38 /* ampersand */:
9518                         if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
9519                             return pos += 2, token = 55 /* AmpersandAmpersandToken */;
9520                         }
9521                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9522                             return pos += 2, token = 72 /* AmpersandEqualsToken */;
9523                         }
9524                         pos++;
9525                         return token = 50 /* AmpersandToken */;
9526                     case 40 /* openParen */:
9527                         pos++;
9528                         return token = 20 /* OpenParenToken */;
9529                     case 41 /* closeParen */:
9530                         pos++;
9531                         return token = 21 /* CloseParenToken */;
9532                     case 42 /* asterisk */:
9533                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9534                             return pos += 2, token = 65 /* AsteriskEqualsToken */;
9535                         }
9536                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9537                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9538                                 return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
9539                             }
9540                             return pos += 2, token = 42 /* AsteriskAsteriskToken */;
9541                         }
9542                         pos++;
9543                         if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
9544                             // decoration at the start of a JSDoc comment line
9545                             asteriskSeen = true;
9546                             continue;
9547                         }
9548                         return token = 41 /* AsteriskToken */;
9549                     case 43 /* plus */:
9550                         if (text.charCodeAt(pos + 1) === 43 /* plus */) {
9551                             return pos += 2, token = 45 /* PlusPlusToken */;
9552                         }
9553                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9554                             return pos += 2, token = 63 /* PlusEqualsToken */;
9555                         }
9556                         pos++;
9557                         return token = 39 /* PlusToken */;
9558                     case 44 /* comma */:
9559                         pos++;
9560                         return token = 27 /* CommaToken */;
9561                     case 45 /* minus */:
9562                         if (text.charCodeAt(pos + 1) === 45 /* minus */) {
9563                             return pos += 2, token = 46 /* MinusMinusToken */;
9564                         }
9565                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9566                             return pos += 2, token = 64 /* MinusEqualsToken */;
9567                         }
9568                         pos++;
9569                         return token = 40 /* MinusToken */;
9570                     case 46 /* dot */:
9571                         if (isDigit(text.charCodeAt(pos + 1))) {
9572                             tokenValue = scanNumber().value;
9573                             return token = 8 /* NumericLiteral */;
9574                         }
9575                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
9576                             return pos += 3, token = 25 /* DotDotDotToken */;
9577                         }
9578                         pos++;
9579                         return token = 24 /* DotToken */;
9580                     case 47 /* slash */:
9581                         // Single-line comment
9582                         if (text.charCodeAt(pos + 1) === 47 /* slash */) {
9583                             pos += 2;
9584                             while (pos < end) {
9585                                 if (isLineBreak(text.charCodeAt(pos))) {
9586                                     break;
9587                                 }
9588                                 pos++;
9589                             }
9590                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
9591                             if (skipTrivia) {
9592                                 continue;
9593                             }
9594                             else {
9595                                 return token = 2 /* SingleLineCommentTrivia */;
9596                             }
9597                         }
9598                         // Multi-line comment
9599                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9600                             pos += 2;
9601                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
9602                                 tokenFlags |= 2 /* PrecedingJSDocComment */;
9603                             }
9604                             var commentClosed = false;
9605                             var lastLineStart = tokenPos;
9606                             while (pos < end) {
9607                                 var ch_1 = text.charCodeAt(pos);
9608                                 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9609                                     pos += 2;
9610                                     commentClosed = true;
9611                                     break;
9612                                 }
9613                                 pos++;
9614                                 if (isLineBreak(ch_1)) {
9615                                     lastLineStart = pos;
9616                                     tokenFlags |= 1 /* PrecedingLineBreak */;
9617                                 }
9618                             }
9619                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
9620                             if (!commentClosed) {
9621                                 error(ts.Diagnostics.Asterisk_Slash_expected);
9622                             }
9623                             if (skipTrivia) {
9624                                 continue;
9625                             }
9626                             else {
9627                                 if (!commentClosed) {
9628                                     tokenFlags |= 4 /* Unterminated */;
9629                                 }
9630                                 return token = 3 /* MultiLineCommentTrivia */;
9631                             }
9632                         }
9633                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9634                             return pos += 2, token = 67 /* SlashEqualsToken */;
9635                         }
9636                         pos++;
9637                         return token = 43 /* SlashToken */;
9638                     case 48 /* _0 */:
9639                         if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
9640                             pos += 2;
9641                             tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
9642                             if (!tokenValue) {
9643                                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9644                                 tokenValue = "0";
9645                             }
9646                             tokenValue = "0x" + tokenValue;
9647                             tokenFlags |= 64 /* HexSpecifier */;
9648                             return token = checkBigIntSuffix();
9649                         }
9650                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
9651                             pos += 2;
9652                             tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
9653                             if (!tokenValue) {
9654                                 error(ts.Diagnostics.Binary_digit_expected);
9655                                 tokenValue = "0";
9656                             }
9657                             tokenValue = "0b" + tokenValue;
9658                             tokenFlags |= 128 /* BinarySpecifier */;
9659                             return token = checkBigIntSuffix();
9660                         }
9661                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
9662                             pos += 2;
9663                             tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
9664                             if (!tokenValue) {
9665                                 error(ts.Diagnostics.Octal_digit_expected);
9666                                 tokenValue = "0";
9667                             }
9668                             tokenValue = "0o" + tokenValue;
9669                             tokenFlags |= 256 /* OctalSpecifier */;
9670                             return token = checkBigIntSuffix();
9671                         }
9672                         // Try to parse as an octal
9673                         if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
9674                             tokenValue = "" + scanOctalDigits();
9675                             tokenFlags |= 32 /* Octal */;
9676                             return token = 8 /* NumericLiteral */;
9677                         }
9678                     // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
9679                     // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
9680                     // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
9681                     // falls through
9682                     case 49 /* _1 */:
9683                     case 50 /* _2 */:
9684                     case 51 /* _3 */:
9685                     case 52 /* _4 */:
9686                     case 53 /* _5 */:
9687                     case 54 /* _6 */:
9688                     case 55 /* _7 */:
9689                     case 56 /* _8 */:
9690                     case 57 /* _9 */:
9691                         (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
9692                         return token;
9693                     case 58 /* colon */:
9694                         pos++;
9695                         return token = 58 /* ColonToken */;
9696                     case 59 /* semicolon */:
9697                         pos++;
9698                         return token = 26 /* SemicolonToken */;
9699                     case 60 /* lessThan */:
9700                         if (isConflictMarkerTrivia(text, pos)) {
9701                             pos = scanConflictMarkerTrivia(text, pos, error);
9702                             if (skipTrivia) {
9703                                 continue;
9704                             }
9705                             else {
9706                                 return token = 7 /* ConflictMarkerTrivia */;
9707                             }
9708                         }
9709                         if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
9710                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9711                                 return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
9712                             }
9713                             return pos += 2, token = 47 /* LessThanLessThanToken */;
9714                         }
9715                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9716                             return pos += 2, token = 32 /* LessThanEqualsToken */;
9717                         }
9718                         if (languageVariant === 1 /* JSX */ &&
9719                             text.charCodeAt(pos + 1) === 47 /* slash */ &&
9720                             text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
9721                             return pos += 2, token = 30 /* LessThanSlashToken */;
9722                         }
9723                         pos++;
9724                         return token = 29 /* LessThanToken */;
9725                     case 61 /* equals */:
9726                         if (isConflictMarkerTrivia(text, pos)) {
9727                             pos = scanConflictMarkerTrivia(text, pos, error);
9728                             if (skipTrivia) {
9729                                 continue;
9730                             }
9731                             else {
9732                                 return token = 7 /* ConflictMarkerTrivia */;
9733                             }
9734                         }
9735                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9736                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9737                                 return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
9738                             }
9739                             return pos += 2, token = 34 /* EqualsEqualsToken */;
9740                         }
9741                         if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
9742                             return pos += 2, token = 38 /* EqualsGreaterThanToken */;
9743                         }
9744                         pos++;
9745                         return token = 62 /* EqualsToken */;
9746                     case 62 /* greaterThan */:
9747                         if (isConflictMarkerTrivia(text, pos)) {
9748                             pos = scanConflictMarkerTrivia(text, pos, error);
9749                             if (skipTrivia) {
9750                                 continue;
9751                             }
9752                             else {
9753                                 return token = 7 /* ConflictMarkerTrivia */;
9754                             }
9755                         }
9756                         pos++;
9757                         return token = 31 /* GreaterThanToken */;
9758                     case 63 /* question */:
9759                         pos++;
9760                         if (text.charCodeAt(pos) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 1))) {
9761                             pos++;
9762                             return token = 28 /* QuestionDotToken */;
9763                         }
9764                         if (text.charCodeAt(pos) === 63 /* question */) {
9765                             pos++;
9766                             return token = 60 /* QuestionQuestionToken */;
9767                         }
9768                         return token = 57 /* QuestionToken */;
9769                     case 91 /* openBracket */:
9770                         pos++;
9771                         return token = 22 /* OpenBracketToken */;
9772                     case 93 /* closeBracket */:
9773                         pos++;
9774                         return token = 23 /* CloseBracketToken */;
9775                     case 94 /* caret */:
9776                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9777                             return pos += 2, token = 74 /* CaretEqualsToken */;
9778                         }
9779                         pos++;
9780                         return token = 52 /* CaretToken */;
9781                     case 123 /* openBrace */:
9782                         pos++;
9783                         return token = 18 /* OpenBraceToken */;
9784                     case 124 /* bar */:
9785                         if (isConflictMarkerTrivia(text, pos)) {
9786                             pos = scanConflictMarkerTrivia(text, pos, error);
9787                             if (skipTrivia) {
9788                                 continue;
9789                             }
9790                             else {
9791                                 return token = 7 /* ConflictMarkerTrivia */;
9792                             }
9793                         }
9794                         if (text.charCodeAt(pos + 1) === 124 /* bar */) {
9795                             return pos += 2, token = 56 /* BarBarToken */;
9796                         }
9797                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9798                             return pos += 2, token = 73 /* BarEqualsToken */;
9799                         }
9800                         pos++;
9801                         return token = 51 /* BarToken */;
9802                     case 125 /* closeBrace */:
9803                         pos++;
9804                         return token = 19 /* CloseBraceToken */;
9805                     case 126 /* tilde */:
9806                         pos++;
9807                         return token = 54 /* TildeToken */;
9808                     case 64 /* at */:
9809                         pos++;
9810                         return token = 59 /* AtToken */;
9811                     case 92 /* backslash */:
9812                         var extendedCookedChar = peekExtendedUnicodeEscape();
9813                         if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
9814                             pos += 3;
9815                             tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9816                             tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
9817                             return token = getIdentifierToken();
9818                         }
9819                         var cookedChar = peekUnicodeEscape();
9820                         if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
9821                             pos += 6;
9822                             tokenFlags |= 1024 /* UnicodeEscape */;
9823                             tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
9824                             return token = getIdentifierToken();
9825                         }
9826                         error(ts.Diagnostics.Invalid_character);
9827                         pos++;
9828                         return token = 0 /* Unknown */;
9829                     case 35 /* hash */:
9830                         if (pos !== 0 && text[pos + 1] === "!") {
9831                             error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
9832                             pos++;
9833                             return token = 0 /* Unknown */;
9834                         }
9835                         pos++;
9836                         if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
9837                             pos++;
9838                             while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
9839                                 pos++;
9840                             tokenValue = text.substring(tokenPos, pos);
9841                             if (ch === 92 /* backslash */) {
9842                                 tokenValue += scanIdentifierParts();
9843                             }
9844                         }
9845                         else {
9846                             tokenValue = "#";
9847                             error(ts.Diagnostics.Invalid_character);
9848                         }
9849                         return token = 76 /* PrivateIdentifier */;
9850                     default:
9851                         if (isIdentifierStart(ch, languageVersion)) {
9852                             pos += charSize(ch);
9853                             while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
9854                                 pos += charSize(ch);
9855                             tokenValue = text.substring(tokenPos, pos);
9856                             if (ch === 92 /* backslash */) {
9857                                 tokenValue += scanIdentifierParts();
9858                             }
9859                             return token = getIdentifierToken();
9860                         }
9861                         else if (isWhiteSpaceSingleLine(ch)) {
9862                             pos += charSize(ch);
9863                             continue;
9864                         }
9865                         else if (isLineBreak(ch)) {
9866                             tokenFlags |= 1 /* PrecedingLineBreak */;
9867                             pos += charSize(ch);
9868                             continue;
9869                         }
9870                         error(ts.Diagnostics.Invalid_character);
9871                         pos += charSize(ch);
9872                         return token = 0 /* Unknown */;
9873                 }
9874             }
9875         }
9876         function reScanGreaterToken() {
9877             if (token === 31 /* GreaterThanToken */) {
9878                 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
9879                     if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
9880                         if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9881                             return pos += 3, token = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
9882                         }
9883                         return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
9884                     }
9885                     if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9886                         return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
9887                     }
9888                     pos++;
9889                     return token = 48 /* GreaterThanGreaterThanToken */;
9890                 }
9891                 if (text.charCodeAt(pos) === 61 /* equals */) {
9892                     pos++;
9893                     return token = 33 /* GreaterThanEqualsToken */;
9894                 }
9895             }
9896             return token;
9897         }
9898         function reScanSlashToken() {
9899             if (token === 43 /* SlashToken */ || token === 67 /* SlashEqualsToken */) {
9900                 var p = tokenPos + 1;
9901                 var inEscape = false;
9902                 var inCharacterClass = false;
9903                 while (true) {
9904                     // If we reach the end of a file, or hit a newline, then this is an unterminated
9905                     // regex.  Report error and return what we have so far.
9906                     if (p >= end) {
9907                         tokenFlags |= 4 /* Unterminated */;
9908                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
9909                         break;
9910                     }
9911                     var ch = text.charCodeAt(p);
9912                     if (isLineBreak(ch)) {
9913                         tokenFlags |= 4 /* Unterminated */;
9914                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
9915                         break;
9916                     }
9917                     if (inEscape) {
9918                         // Parsing an escape character;
9919                         // reset the flag and just advance to the next char.
9920                         inEscape = false;
9921                     }
9922                     else if (ch === 47 /* slash */ && !inCharacterClass) {
9923                         // A slash within a character class is permissible,
9924                         // but in general it signals the end of the regexp literal.
9925                         p++;
9926                         break;
9927                     }
9928                     else if (ch === 91 /* openBracket */) {
9929                         inCharacterClass = true;
9930                     }
9931                     else if (ch === 92 /* backslash */) {
9932                         inEscape = true;
9933                     }
9934                     else if (ch === 93 /* closeBracket */) {
9935                         inCharacterClass = false;
9936                     }
9937                     p++;
9938                 }
9939                 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
9940                     p++;
9941                 }
9942                 pos = p;
9943                 tokenValue = text.substring(tokenPos, pos);
9944                 token = 13 /* RegularExpressionLiteral */;
9945             }
9946             return token;
9947         }
9948         function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
9949             var type = getDirectiveFromComment(text, commentDirectiveRegEx);
9950             if (type === undefined) {
9951                 return commentDirectives;
9952             }
9953             return ts.append(commentDirectives, {
9954                 range: { pos: lineStart, end: pos },
9955                 type: type,
9956             });
9957         }
9958         function getDirectiveFromComment(text, commentDirectiveRegEx) {
9959             var match = commentDirectiveRegEx.exec(text);
9960             if (!match) {
9961                 return undefined;
9962             }
9963             switch (match[1]) {
9964                 case "ts-expect-error":
9965                     return 0 /* ExpectError */;
9966                 case "ts-ignore":
9967                     return 1 /* Ignore */;
9968             }
9969             return undefined;
9970         }
9971         /**
9972          * Unconditionally back up and scan a template expression portion.
9973          */
9974         function reScanTemplateToken(isTaggedTemplate) {
9975             ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
9976             pos = tokenPos;
9977             return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
9978         }
9979         function reScanTemplateHeadOrNoSubstitutionTemplate() {
9980             pos = tokenPos;
9981             return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
9982         }
9983         function reScanJsxToken() {
9984             pos = tokenPos = startPos;
9985             return token = scanJsxToken();
9986         }
9987         function reScanLessThanToken() {
9988             if (token === 47 /* LessThanLessThanToken */) {
9989                 pos = tokenPos + 1;
9990                 return token = 29 /* LessThanToken */;
9991             }
9992             return token;
9993         }
9994         function reScanQuestionToken() {
9995             ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
9996             pos = tokenPos + 1;
9997             return token = 57 /* QuestionToken */;
9998         }
9999         function scanJsxToken() {
10000             startPos = tokenPos = pos;
10001             if (pos >= end) {
10002                 return token = 1 /* EndOfFileToken */;
10003             }
10004             var char = text.charCodeAt(pos);
10005             if (char === 60 /* lessThan */) {
10006                 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10007                     pos += 2;
10008                     return token = 30 /* LessThanSlashToken */;
10009                 }
10010                 pos++;
10011                 return token = 29 /* LessThanToken */;
10012             }
10013             if (char === 123 /* openBrace */) {
10014                 pos++;
10015                 return token = 18 /* OpenBraceToken */;
10016             }
10017             // First non-whitespace character on this line.
10018             var firstNonWhitespace = 0;
10019             var lastNonWhitespace = -1;
10020             // These initial values are special because the first line is:
10021             // firstNonWhitespace = 0 to indicate that we want leading whitespace,
10022             while (pos < end) {
10023                 // We want to keep track of the last non-whitespace (but including
10024                 // newlines character for hitting the end of the JSX Text region)
10025                 if (!isWhiteSpaceSingleLine(char)) {
10026                     lastNonWhitespace = pos;
10027                 }
10028                 char = text.charCodeAt(pos);
10029                 if (char === 123 /* openBrace */) {
10030                     break;
10031                 }
10032                 if (char === 60 /* lessThan */) {
10033                     if (isConflictMarkerTrivia(text, pos)) {
10034                         pos = scanConflictMarkerTrivia(text, pos, error);
10035                         return token = 7 /* ConflictMarkerTrivia */;
10036                     }
10037                     break;
10038                 }
10039                 if (char === 62 /* greaterThan */) {
10040                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
10041                 }
10042                 if (char === 125 /* closeBrace */) {
10043                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
10044                 }
10045                 if (lastNonWhitespace > 0)
10046                     lastNonWhitespace++;
10047                 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
10048                 // i.e (- : whitespace)
10049                 //      <div>----
10050                 //      </div> becomes <div></div>
10051                 //
10052                 //      <div>----</div> becomes <div>----</div>
10053                 if (isLineBreak(char) && firstNonWhitespace === 0) {
10054                     firstNonWhitespace = -1;
10055                 }
10056                 else if (!isWhiteSpaceLike(char)) {
10057                     firstNonWhitespace = pos;
10058                 }
10059                 pos++;
10060             }
10061             var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
10062             tokenValue = text.substring(startPos, endPosition);
10063             return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
10064         }
10065         // Scans a JSX identifier; these differ from normal identifiers in that
10066         // they allow dashes
10067         function scanJsxIdentifier() {
10068             if (tokenIsIdentifierOrKeyword(token)) {
10069                 // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
10070                 // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
10071                 // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
10072                 while (pos < end) {
10073                     var ch = text.charCodeAt(pos);
10074                     if (ch === 45 /* minus */) {
10075                         tokenValue += "-";
10076                         pos++;
10077                         continue;
10078                     }
10079                     var oldPos = pos;
10080                     tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
10081                     if (pos === oldPos) {
10082                         break;
10083                     }
10084                 }
10085             }
10086             return token;
10087         }
10088         function scanJsxAttributeValue() {
10089             startPos = pos;
10090             switch (text.charCodeAt(pos)) {
10091                 case 34 /* doubleQuote */:
10092                 case 39 /* singleQuote */:
10093                     tokenValue = scanString(/*jsxAttributeString*/ true);
10094                     return token = 10 /* StringLiteral */;
10095                 default:
10096                     // If this scans anything other than `{`, it's a parse error.
10097                     return scan();
10098             }
10099         }
10100         function reScanJsxAttributeValue() {
10101             pos = tokenPos = startPos;
10102             return scanJsxAttributeValue();
10103         }
10104         function scanJsDocToken() {
10105             startPos = tokenPos = pos;
10106             tokenFlags = 0 /* None */;
10107             if (pos >= end) {
10108                 return token = 1 /* EndOfFileToken */;
10109             }
10110             var ch = codePointAt(text, pos);
10111             pos += charSize(ch);
10112             switch (ch) {
10113                 case 9 /* tab */:
10114                 case 11 /* verticalTab */:
10115                 case 12 /* formFeed */:
10116                 case 32 /* space */:
10117                     while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
10118                         pos++;
10119                     }
10120                     return token = 5 /* WhitespaceTrivia */;
10121                 case 64 /* at */:
10122                     return token = 59 /* AtToken */;
10123                 case 10 /* lineFeed */:
10124                 case 13 /* carriageReturn */:
10125                     tokenFlags |= 1 /* PrecedingLineBreak */;
10126                     return token = 4 /* NewLineTrivia */;
10127                 case 42 /* asterisk */:
10128                     return token = 41 /* AsteriskToken */;
10129                 case 123 /* openBrace */:
10130                     return token = 18 /* OpenBraceToken */;
10131                 case 125 /* closeBrace */:
10132                     return token = 19 /* CloseBraceToken */;
10133                 case 91 /* openBracket */:
10134                     return token = 22 /* OpenBracketToken */;
10135                 case 93 /* closeBracket */:
10136                     return token = 23 /* CloseBracketToken */;
10137                 case 60 /* lessThan */:
10138                     return token = 29 /* LessThanToken */;
10139                 case 62 /* greaterThan */:
10140                     return token = 31 /* GreaterThanToken */;
10141                 case 61 /* equals */:
10142                     return token = 62 /* EqualsToken */;
10143                 case 44 /* comma */:
10144                     return token = 27 /* CommaToken */;
10145                 case 46 /* dot */:
10146                     return token = 24 /* DotToken */;
10147                 case 96 /* backtick */:
10148                     return token = 61 /* BacktickToken */;
10149                 case 92 /* backslash */:
10150                     pos--;
10151                     var extendedCookedChar = peekExtendedUnicodeEscape();
10152                     if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
10153                         pos += 3;
10154                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10155                         tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
10156                         return token = getIdentifierToken();
10157                     }
10158                     var cookedChar = peekUnicodeEscape();
10159                     if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
10160                         pos += 6;
10161                         tokenFlags |= 1024 /* UnicodeEscape */;
10162                         tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
10163                         return token = getIdentifierToken();
10164                     }
10165                     pos++;
10166                     return token = 0 /* Unknown */;
10167             }
10168             if (isIdentifierStart(ch, languageVersion)) {
10169                 var char = ch;
10170                 while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
10171                     pos += charSize(char);
10172                 tokenValue = text.substring(tokenPos, pos);
10173                 if (char === 92 /* backslash */) {
10174                     tokenValue += scanIdentifierParts();
10175                 }
10176                 return token = getIdentifierToken();
10177             }
10178             else {
10179                 return token = 0 /* Unknown */;
10180             }
10181         }
10182         function speculationHelper(callback, isLookahead) {
10183             var savePos = pos;
10184             var saveStartPos = startPos;
10185             var saveTokenPos = tokenPos;
10186             var saveToken = token;
10187             var saveTokenValue = tokenValue;
10188             var saveTokenFlags = tokenFlags;
10189             var result = callback();
10190             // If our callback returned something 'falsy' or we're just looking ahead,
10191             // then unconditionally restore us to where we were.
10192             if (!result || isLookahead) {
10193                 pos = savePos;
10194                 startPos = saveStartPos;
10195                 tokenPos = saveTokenPos;
10196                 token = saveToken;
10197                 tokenValue = saveTokenValue;
10198                 tokenFlags = saveTokenFlags;
10199             }
10200             return result;
10201         }
10202         function scanRange(start, length, callback) {
10203             var saveEnd = end;
10204             var savePos = pos;
10205             var saveStartPos = startPos;
10206             var saveTokenPos = tokenPos;
10207             var saveToken = token;
10208             var saveTokenValue = tokenValue;
10209             var saveTokenFlags = tokenFlags;
10210             var saveErrorExpectations = commentDirectives;
10211             setText(text, start, length);
10212             var result = callback();
10213             end = saveEnd;
10214             pos = savePos;
10215             startPos = saveStartPos;
10216             tokenPos = saveTokenPos;
10217             token = saveToken;
10218             tokenValue = saveTokenValue;
10219             tokenFlags = saveTokenFlags;
10220             commentDirectives = saveErrorExpectations;
10221             return result;
10222         }
10223         function lookAhead(callback) {
10224             return speculationHelper(callback, /*isLookahead*/ true);
10225         }
10226         function tryScan(callback) {
10227             return speculationHelper(callback, /*isLookahead*/ false);
10228         }
10229         function getText() {
10230             return text;
10231         }
10232         function clearCommentDirectives() {
10233             commentDirectives = undefined;
10234         }
10235         function setText(newText, start, length) {
10236             text = newText || "";
10237             end = length === undefined ? text.length : start + length;
10238             setTextPos(start || 0);
10239         }
10240         function setOnError(errorCallback) {
10241             onError = errorCallback;
10242         }
10243         function setScriptTarget(scriptTarget) {
10244             languageVersion = scriptTarget;
10245         }
10246         function setLanguageVariant(variant) {
10247             languageVariant = variant;
10248         }
10249         function setTextPos(textPos) {
10250             ts.Debug.assert(textPos >= 0);
10251             pos = textPos;
10252             startPos = textPos;
10253             tokenPos = textPos;
10254             token = 0 /* Unknown */;
10255             tokenValue = undefined;
10256             tokenFlags = 0 /* None */;
10257         }
10258         function setInJSDocType(inType) {
10259             inJSDocType += inType ? 1 : -1;
10260         }
10261     }
10262     ts.createScanner = createScanner;
10263     /* @internal */
10264     var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
10265         // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
10266         var size = str.length;
10267         // Account for out-of-bounds indices:
10268         if (i < 0 || i >= size) {
10269             return undefined; // String.codePointAt returns `undefined` for OOB indexes
10270         }
10271         // Get the first code unit
10272         var first = str.charCodeAt(i);
10273         // check if it’s the start of a surrogate pair
10274         if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
10275             var second = str.charCodeAt(i + 1);
10276             if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
10277                 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
10278                 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
10279             }
10280         }
10281         return first;
10282     };
10283     /* @internal */
10284     function charSize(ch) {
10285         if (ch >= 0x10000) {
10286             return 2;
10287         }
10288         return 1;
10289     }
10290     // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
10291     function utf16EncodeAsStringFallback(codePoint) {
10292         ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
10293         if (codePoint <= 65535) {
10294             return String.fromCharCode(codePoint);
10295         }
10296         var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
10297         var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
10298         return String.fromCharCode(codeUnit1, codeUnit2);
10299     }
10300     var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
10301     /* @internal */
10302     function utf16EncodeAsString(codePoint) {
10303         return utf16EncodeAsStringWorker(codePoint);
10304     }
10305     ts.utf16EncodeAsString = utf16EncodeAsString;
10306 })(ts || (ts = {}));
10307 var ts;
10308 (function (ts) {
10309     function isExternalModuleNameRelative(moduleName) {
10310         // TypeScript 1.0 spec (April 2014): 11.2.1
10311         // An external module name is "relative" if the first term is "." or "..".
10312         // 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.
10313         return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
10314     }
10315     ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
10316     function sortAndDeduplicateDiagnostics(diagnostics) {
10317         return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
10318     }
10319     ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
10320     function getDefaultLibFileName(options) {
10321         switch (options.target) {
10322             case 99 /* ESNext */:
10323                 return "lib.esnext.full.d.ts";
10324             case 7 /* ES2020 */:
10325                 return "lib.es2020.full.d.ts";
10326             case 6 /* ES2019 */:
10327                 return "lib.es2019.full.d.ts";
10328             case 5 /* ES2018 */:
10329                 return "lib.es2018.full.d.ts";
10330             case 4 /* ES2017 */:
10331                 return "lib.es2017.full.d.ts";
10332             case 3 /* ES2016 */:
10333                 return "lib.es2016.full.d.ts";
10334             case 2 /* ES2015 */:
10335                 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
10336             default:
10337                 return "lib.d.ts";
10338         }
10339     }
10340     ts.getDefaultLibFileName = getDefaultLibFileName;
10341     function textSpanEnd(span) {
10342         return span.start + span.length;
10343     }
10344     ts.textSpanEnd = textSpanEnd;
10345     function textSpanIsEmpty(span) {
10346         return span.length === 0;
10347     }
10348     ts.textSpanIsEmpty = textSpanIsEmpty;
10349     function textSpanContainsPosition(span, position) {
10350         return position >= span.start && position < textSpanEnd(span);
10351     }
10352     ts.textSpanContainsPosition = textSpanContainsPosition;
10353     /* @internal */
10354     function textRangeContainsPositionInclusive(span, position) {
10355         return position >= span.pos && position <= span.end;
10356     }
10357     ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
10358     // Returns true if 'span' contains 'other'.
10359     function textSpanContainsTextSpan(span, other) {
10360         return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
10361     }
10362     ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
10363     function textSpanOverlapsWith(span, other) {
10364         return textSpanOverlap(span, other) !== undefined;
10365     }
10366     ts.textSpanOverlapsWith = textSpanOverlapsWith;
10367     function textSpanOverlap(span1, span2) {
10368         var overlap = textSpanIntersection(span1, span2);
10369         return overlap && overlap.length === 0 ? undefined : overlap;
10370     }
10371     ts.textSpanOverlap = textSpanOverlap;
10372     function textSpanIntersectsWithTextSpan(span, other) {
10373         return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
10374     }
10375     ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
10376     function textSpanIntersectsWith(span, start, length) {
10377         return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
10378     }
10379     ts.textSpanIntersectsWith = textSpanIntersectsWith;
10380     function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
10381         var end1 = start1 + length1;
10382         var end2 = start2 + length2;
10383         return start2 <= end1 && end2 >= start1;
10384     }
10385     ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
10386     function textSpanIntersectsWithPosition(span, position) {
10387         return position <= textSpanEnd(span) && position >= span.start;
10388     }
10389     ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
10390     function textSpanIntersection(span1, span2) {
10391         var start = Math.max(span1.start, span2.start);
10392         var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
10393         return start <= end ? createTextSpanFromBounds(start, end) : undefined;
10394     }
10395     ts.textSpanIntersection = textSpanIntersection;
10396     function createTextSpan(start, length) {
10397         if (start < 0) {
10398             throw new Error("start < 0");
10399         }
10400         if (length < 0) {
10401             throw new Error("length < 0");
10402         }
10403         return { start: start, length: length };
10404     }
10405     ts.createTextSpan = createTextSpan;
10406     function createTextSpanFromBounds(start, end) {
10407         return createTextSpan(start, end - start);
10408     }
10409     ts.createTextSpanFromBounds = createTextSpanFromBounds;
10410     function textChangeRangeNewSpan(range) {
10411         return createTextSpan(range.span.start, range.newLength);
10412     }
10413     ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
10414     function textChangeRangeIsUnchanged(range) {
10415         return textSpanIsEmpty(range.span) && range.newLength === 0;
10416     }
10417     ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
10418     function createTextChangeRange(span, newLength) {
10419         if (newLength < 0) {
10420             throw new Error("newLength < 0");
10421         }
10422         return { span: span, newLength: newLength };
10423     }
10424     ts.createTextChangeRange = createTextChangeRange;
10425     ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
10426     /**
10427      * Called to merge all the changes that occurred across several versions of a script snapshot
10428      * into a single change.  i.e. if a user keeps making successive edits to a script we will
10429      * have a text change from V1 to V2, V2 to V3, ..., Vn.
10430      *
10431      * This function will then merge those changes into a single change range valid between V1 and
10432      * Vn.
10433      */
10434     function collapseTextChangeRangesAcrossMultipleVersions(changes) {
10435         if (changes.length === 0) {
10436             return ts.unchangedTextChangeRange;
10437         }
10438         if (changes.length === 1) {
10439             return changes[0];
10440         }
10441         // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
10442         // as it makes things much easier to reason about.
10443         var change0 = changes[0];
10444         var oldStartN = change0.span.start;
10445         var oldEndN = textSpanEnd(change0.span);
10446         var newEndN = oldStartN + change0.newLength;
10447         for (var i = 1; i < changes.length; i++) {
10448             var nextChange = changes[i];
10449             // Consider the following case:
10450             // i.e. two edits.  The first represents the text change range { { 10, 50 }, 30 }.  i.e. The span starting
10451             // at 10, with length 50 is reduced to length 30.  The second represents the text change range { { 30, 30 }, 40 }.
10452             // i.e. the span starting at 30 with length 30 is increased to length 40.
10453             //
10454             //      0         10        20        30        40        50        60        70        80        90        100
10455             //      -------------------------------------------------------------------------------------------------------
10456             //                |                                                 /
10457             //                |                                            /----
10458             //  T1            |                                       /----
10459             //                |                                  /----
10460             //                |                             /----
10461             //      -------------------------------------------------------------------------------------------------------
10462             //                                     |                            \
10463             //                                     |                               \
10464             //   T2                                |                                 \
10465             //                                     |                                   \
10466             //                                     |                                      \
10467             //      -------------------------------------------------------------------------------------------------------
10468             //
10469             // Merging these turns out to not be too difficult.  First, determining the new start of the change is trivial
10470             // it's just the min of the old and new starts.  i.e.:
10471             //
10472             //      0         10        20        30        40        50        60        70        80        90        100
10473             //      ------------------------------------------------------------*------------------------------------------
10474             //                |                                                 /
10475             //                |                                            /----
10476             //  T1            |                                       /----
10477             //                |                                  /----
10478             //                |                             /----
10479             //      ----------------------------------------$-------------------$------------------------------------------
10480             //                .                    |                            \
10481             //                .                    |                               \
10482             //   T2           .                    |                                 \
10483             //                .                    |                                   \
10484             //                .                    |                                      \
10485             //      ----------------------------------------------------------------------*--------------------------------
10486             //
10487             // (Note the dots represent the newly inferred start.
10488             // Determining the new and old end is also pretty simple.  Basically it boils down to paying attention to the
10489             // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
10490             // which if the two $'s precedes the other, and we move that one forward until they line up.  in this case that
10491             // means:
10492             //
10493             //      0         10        20        30        40        50        60        70        80        90        100
10494             //      --------------------------------------------------------------------------------*----------------------
10495             //                |                                                                     /
10496             //                |                                                                /----
10497             //  T1            |                                                           /----
10498             //                |                                                      /----
10499             //                |                                                 /----
10500             //      ------------------------------------------------------------$------------------------------------------
10501             //                .                    |                            \
10502             //                .                    |                               \
10503             //   T2           .                    |                                 \
10504             //                .                    |                                   \
10505             //                .                    |                                      \
10506             //      ----------------------------------------------------------------------*--------------------------------
10507             //
10508             // In other words (in this case), we're recognizing that the second edit happened after where the first edit
10509             // ended with a delta of 20 characters (60 - 40).  Thus, if we go back in time to where the first edit started
10510             // that's the same as if we started at char 80 instead of 60.
10511             //
10512             // As it so happens, the same logic applies if the second edit precedes the first edit.  In that case rather
10513             // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
10514             // first.
10515             //
10516             // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
10517             // semantics: { { start: 10, length: 70 }, newLength: 60 }
10518             //
10519             // The math then works out as follows.
10520             // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
10521             // final result like so:
10522             //
10523             // {
10524             //      oldStart3: Min(oldStart1, oldStart2),
10525             //      oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
10526             //      newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
10527             // }
10528             var oldStart1 = oldStartN;
10529             var oldEnd1 = oldEndN;
10530             var newEnd1 = newEndN;
10531             var oldStart2 = nextChange.span.start;
10532             var oldEnd2 = textSpanEnd(nextChange.span);
10533             var newEnd2 = oldStart2 + nextChange.newLength;
10534             oldStartN = Math.min(oldStart1, oldStart2);
10535             oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
10536             newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
10537         }
10538         return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
10539     }
10540     ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
10541     function getTypeParameterOwner(d) {
10542         if (d && d.kind === 155 /* TypeParameter */) {
10543             for (var current = d; current; current = current.parent) {
10544                 if (isFunctionLike(current) || isClassLike(current) || current.kind === 246 /* InterfaceDeclaration */) {
10545                     return current;
10546                 }
10547             }
10548         }
10549     }
10550     ts.getTypeParameterOwner = getTypeParameterOwner;
10551     function isParameterPropertyDeclaration(node, parent) {
10552         return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 162 /* Constructor */;
10553     }
10554     ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
10555     function isEmptyBindingPattern(node) {
10556         if (isBindingPattern(node)) {
10557             return ts.every(node.elements, isEmptyBindingElement);
10558         }
10559         return false;
10560     }
10561     ts.isEmptyBindingPattern = isEmptyBindingPattern;
10562     function isEmptyBindingElement(node) {
10563         if (isOmittedExpression(node)) {
10564             return true;
10565         }
10566         return isEmptyBindingPattern(node.name);
10567     }
10568     ts.isEmptyBindingElement = isEmptyBindingElement;
10569     function walkUpBindingElementsAndPatterns(binding) {
10570         var node = binding.parent;
10571         while (isBindingElement(node.parent)) {
10572             node = node.parent.parent;
10573         }
10574         return node.parent;
10575     }
10576     ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
10577     function getCombinedFlags(node, getFlags) {
10578         if (isBindingElement(node)) {
10579             node = walkUpBindingElementsAndPatterns(node);
10580         }
10581         var flags = getFlags(node);
10582         if (node.kind === 242 /* VariableDeclaration */) {
10583             node = node.parent;
10584         }
10585         if (node && node.kind === 243 /* VariableDeclarationList */) {
10586             flags |= getFlags(node);
10587             node = node.parent;
10588         }
10589         if (node && node.kind === 225 /* VariableStatement */) {
10590             flags |= getFlags(node);
10591         }
10592         return flags;
10593     }
10594     function getCombinedModifierFlags(node) {
10595         return getCombinedFlags(node, ts.getModifierFlags);
10596     }
10597     ts.getCombinedModifierFlags = getCombinedModifierFlags;
10598     // Returns the node flags for this node and all relevant parent nodes.  This is done so that
10599     // nodes like variable declarations and binding elements can returned a view of their flags
10600     // that includes the modifiers from their container.  i.e. flags like export/declare aren't
10601     // stored on the variable declaration directly, but on the containing variable statement
10602     // (if it has one).  Similarly, flags for let/const are store on the variable declaration
10603     // list.  By calling this function, all those flags are combined so that the client can treat
10604     // the node as if it actually had those flags.
10605     function getCombinedNodeFlags(node) {
10606         return getCombinedFlags(node, function (n) { return n.flags; });
10607     }
10608     ts.getCombinedNodeFlags = getCombinedNodeFlags;
10609     /**
10610      * Checks to see if the locale is in the appropriate format,
10611      * and if it is, attempts to set the appropriate language.
10612      */
10613     function validateLocaleAndSetLanguage(locale, sys, errors) {
10614         var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
10615         if (!matchResult) {
10616             if (errors) {
10617                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
10618             }
10619             return;
10620         }
10621         var language = matchResult[1];
10622         var territory = matchResult[3];
10623         // First try the entire locale, then fall back to just language if that's all we have.
10624         // Either ways do not fail, and fallback to the English diagnostic strings.
10625         if (!trySetLanguageAndTerritory(language, territory, errors)) {
10626             trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
10627         }
10628         // Set the UI locale for string collation
10629         ts.setUILocale(locale);
10630         function trySetLanguageAndTerritory(language, territory, errors) {
10631             var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
10632             var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
10633             var filePath = ts.combinePaths(containingDirectoryPath, language);
10634             if (territory) {
10635                 filePath = filePath + "-" + territory;
10636             }
10637             filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
10638             if (!sys.fileExists(filePath)) {
10639                 return false;
10640             }
10641             // TODO: Add codePage support for readFile?
10642             var fileContents = "";
10643             try {
10644                 fileContents = sys.readFile(filePath);
10645             }
10646             catch (e) {
10647                 if (errors) {
10648                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
10649                 }
10650                 return false;
10651             }
10652             try {
10653                 // this is a global mutation (or live binding update)!
10654                 ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
10655             }
10656             catch (_a) {
10657                 if (errors) {
10658                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
10659                 }
10660                 return false;
10661             }
10662             return true;
10663         }
10664     }
10665     ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
10666     function getOriginalNode(node, nodeTest) {
10667         if (node) {
10668             while (node.original !== undefined) {
10669                 node = node.original;
10670             }
10671         }
10672         return !nodeTest || nodeTest(node) ? node : undefined;
10673     }
10674     ts.getOriginalNode = getOriginalNode;
10675     /**
10676      * Gets a value indicating whether a node originated in the parse tree.
10677      *
10678      * @param node The node to test.
10679      */
10680     function isParseTreeNode(node) {
10681         return (node.flags & 8 /* Synthesized */) === 0;
10682     }
10683     ts.isParseTreeNode = isParseTreeNode;
10684     function getParseTreeNode(node, nodeTest) {
10685         if (node === undefined || isParseTreeNode(node)) {
10686             return node;
10687         }
10688         node = getOriginalNode(node);
10689         if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
10690             return node;
10691         }
10692         return undefined;
10693     }
10694     ts.getParseTreeNode = getParseTreeNode;
10695     /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
10696     function escapeLeadingUnderscores(identifier) {
10697         return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
10698     }
10699     ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
10700     /**
10701      * Remove extra underscore from escaped identifier text content.
10702      *
10703      * @param identifier The escaped identifier text.
10704      * @returns The unescaped identifier text.
10705      */
10706     function unescapeLeadingUnderscores(identifier) {
10707         var id = identifier;
10708         return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
10709     }
10710     ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
10711     function idText(identifierOrPrivateName) {
10712         return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
10713     }
10714     ts.idText = idText;
10715     function symbolName(symbol) {
10716         if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
10717             return idText(symbol.valueDeclaration.name);
10718         }
10719         return unescapeLeadingUnderscores(symbol.escapedName);
10720     }
10721     ts.symbolName = symbolName;
10722     /**
10723      * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
10724      * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
10725      * will be merged with)
10726      */
10727     function nameForNamelessJSDocTypedef(declaration) {
10728         var hostNode = declaration.parent.parent;
10729         if (!hostNode) {
10730             return undefined;
10731         }
10732         // Covers classes, functions - any named declaration host node
10733         if (isDeclaration(hostNode)) {
10734             return getDeclarationIdentifier(hostNode);
10735         }
10736         // Covers remaining cases (returning undefined if none match).
10737         switch (hostNode.kind) {
10738             case 225 /* VariableStatement */:
10739                 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
10740                     return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
10741                 }
10742                 break;
10743             case 226 /* ExpressionStatement */:
10744                 var expr = hostNode.expression;
10745                 if (expr.kind === 209 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
10746                     expr = expr.left;
10747                 }
10748                 switch (expr.kind) {
10749                     case 194 /* PropertyAccessExpression */:
10750                         return expr.name;
10751                     case 195 /* ElementAccessExpression */:
10752                         var arg = expr.argumentExpression;
10753                         if (isIdentifier(arg)) {
10754                             return arg;
10755                         }
10756                 }
10757                 break;
10758             case 200 /* ParenthesizedExpression */: {
10759                 return getDeclarationIdentifier(hostNode.expression);
10760             }
10761             case 238 /* LabeledStatement */: {
10762                 if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
10763                     return getDeclarationIdentifier(hostNode.statement);
10764                 }
10765                 break;
10766             }
10767         }
10768     }
10769     function getDeclarationIdentifier(node) {
10770         var name = getNameOfDeclaration(node);
10771         return name && isIdentifier(name) ? name : undefined;
10772     }
10773     /** @internal */
10774     function nodeHasName(statement, name) {
10775         if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
10776             return true;
10777         }
10778         if (isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
10779             return true;
10780         }
10781         return false;
10782     }
10783     ts.nodeHasName = nodeHasName;
10784     function getNameOfJSDocTypedef(declaration) {
10785         return declaration.name || nameForNamelessJSDocTypedef(declaration);
10786     }
10787     ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
10788     /** @internal */
10789     function isNamedDeclaration(node) {
10790         return !!node.name; // A 'name' property should always be a DeclarationName.
10791     }
10792     ts.isNamedDeclaration = isNamedDeclaration;
10793     /** @internal */
10794     function getNonAssignedNameOfDeclaration(declaration) {
10795         switch (declaration.kind) {
10796             case 75 /* Identifier */:
10797                 return declaration;
10798             case 323 /* JSDocPropertyTag */:
10799             case 317 /* JSDocParameterTag */: {
10800                 var name = declaration.name;
10801                 if (name.kind === 153 /* QualifiedName */) {
10802                     return name.right;
10803                 }
10804                 break;
10805             }
10806             case 196 /* CallExpression */:
10807             case 209 /* BinaryExpression */: {
10808                 var expr_1 = declaration;
10809                 switch (ts.getAssignmentDeclarationKind(expr_1)) {
10810                     case 1 /* ExportsProperty */:
10811                     case 4 /* ThisProperty */:
10812                     case 5 /* Property */:
10813                     case 3 /* PrototypeProperty */:
10814                         return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
10815                     case 7 /* ObjectDefinePropertyValue */:
10816                     case 8 /* ObjectDefinePropertyExports */:
10817                     case 9 /* ObjectDefinePrototypeProperty */:
10818                         return expr_1.arguments[1];
10819                     default:
10820                         return undefined;
10821                 }
10822             }
10823             case 322 /* JSDocTypedefTag */:
10824                 return getNameOfJSDocTypedef(declaration);
10825             case 316 /* JSDocEnumTag */:
10826                 return nameForNamelessJSDocTypedef(declaration);
10827             case 259 /* ExportAssignment */: {
10828                 var expression = declaration.expression;
10829                 return isIdentifier(expression) ? expression : undefined;
10830             }
10831             case 195 /* ElementAccessExpression */:
10832                 var expr = declaration;
10833                 if (ts.isBindableStaticElementAccessExpression(expr)) {
10834                     return expr.argumentExpression;
10835                 }
10836         }
10837         return declaration.name;
10838     }
10839     ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
10840     function getNameOfDeclaration(declaration) {
10841         if (declaration === undefined)
10842             return undefined;
10843         return getNonAssignedNameOfDeclaration(declaration) ||
10844             (isFunctionExpression(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
10845     }
10846     ts.getNameOfDeclaration = getNameOfDeclaration;
10847     function getAssignedName(node) {
10848         if (!node.parent) {
10849             return undefined;
10850         }
10851         else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) {
10852             return node.parent.name;
10853         }
10854         else if (isBinaryExpression(node.parent) && node === node.parent.right) {
10855             if (isIdentifier(node.parent.left)) {
10856                 return node.parent.left;
10857             }
10858             else if (ts.isAccessExpression(node.parent.left)) {
10859                 return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
10860             }
10861         }
10862         else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) {
10863             return node.parent.name;
10864         }
10865     }
10866     /**
10867      * Gets the JSDoc parameter tags for the node if present.
10868      *
10869      * @remarks Returns any JSDoc param tag whose name matches the provided
10870      * parameter, whether a param tag on a containing function
10871      * expression, or a param tag on a variable declaration whose
10872      * initializer is the containing function. The tags closest to the
10873      * node are returned first, so in the previous example, the param
10874      * tag on the containing function expression would be first.
10875      *
10876      * For binding patterns, parameter tags are matched by position.
10877      */
10878     function getJSDocParameterTags(param) {
10879         if (param.name) {
10880             if (isIdentifier(param.name)) {
10881                 var name_1 = param.name.escapedText;
10882                 return getJSDocTags(param.parent).filter(function (tag) { return isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name_1; });
10883             }
10884             else {
10885                 var i = param.parent.parameters.indexOf(param);
10886                 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
10887                 var paramTags = getJSDocTags(param.parent).filter(isJSDocParameterTag);
10888                 if (i < paramTags.length) {
10889                     return [paramTags[i]];
10890                 }
10891             }
10892         }
10893         // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
10894         return ts.emptyArray;
10895     }
10896     ts.getJSDocParameterTags = getJSDocParameterTags;
10897     /**
10898      * Gets the JSDoc type parameter tags for the node if present.
10899      *
10900      * @remarks Returns any JSDoc template tag whose names match the provided
10901      * parameter, whether a template tag on a containing function
10902      * expression, or a template tag on a variable declaration whose
10903      * initializer is the containing function. The tags closest to the
10904      * node are returned first, so in the previous example, the template
10905      * tag on the containing function expression would be first.
10906      */
10907     function getJSDocTypeParameterTags(param) {
10908         var name = param.name.escapedText;
10909         return getJSDocTags(param.parent).filter(function (tag) {
10910             return isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
10911         });
10912     }
10913     ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
10914     /**
10915      * Return true if the node has JSDoc parameter tags.
10916      *
10917      * @remarks Includes parameter tags that are not directly on the node,
10918      * for example on a variable declaration whose initializer is a function expression.
10919      */
10920     function hasJSDocParameterTags(node) {
10921         return !!getFirstJSDocTag(node, isJSDocParameterTag);
10922     }
10923     ts.hasJSDocParameterTags = hasJSDocParameterTags;
10924     /** Gets the JSDoc augments tag for the node if present */
10925     function getJSDocAugmentsTag(node) {
10926         return getFirstJSDocTag(node, isJSDocAugmentsTag);
10927     }
10928     ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
10929     /** Gets the JSDoc implements tags for the node if present */
10930     function getJSDocImplementsTags(node) {
10931         return getAllJSDocTags(node, isJSDocImplementsTag);
10932     }
10933     ts.getJSDocImplementsTags = getJSDocImplementsTags;
10934     /** Gets the JSDoc class tag for the node if present */
10935     function getJSDocClassTag(node) {
10936         return getFirstJSDocTag(node, isJSDocClassTag);
10937     }
10938     ts.getJSDocClassTag = getJSDocClassTag;
10939     /** Gets the JSDoc public tag for the node if present */
10940     function getJSDocPublicTag(node) {
10941         return getFirstJSDocTag(node, isJSDocPublicTag);
10942     }
10943     ts.getJSDocPublicTag = getJSDocPublicTag;
10944     /** Gets the JSDoc private tag for the node if present */
10945     function getJSDocPrivateTag(node) {
10946         return getFirstJSDocTag(node, isJSDocPrivateTag);
10947     }
10948     ts.getJSDocPrivateTag = getJSDocPrivateTag;
10949     /** Gets the JSDoc protected tag for the node if present */
10950     function getJSDocProtectedTag(node) {
10951         return getFirstJSDocTag(node, isJSDocProtectedTag);
10952     }
10953     ts.getJSDocProtectedTag = getJSDocProtectedTag;
10954     /** Gets the JSDoc protected tag for the node if present */
10955     function getJSDocReadonlyTag(node) {
10956         return getFirstJSDocTag(node, isJSDocReadonlyTag);
10957     }
10958     ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
10959     /** Gets the JSDoc enum tag for the node if present */
10960     function getJSDocEnumTag(node) {
10961         return getFirstJSDocTag(node, isJSDocEnumTag);
10962     }
10963     ts.getJSDocEnumTag = getJSDocEnumTag;
10964     /** Gets the JSDoc this tag for the node if present */
10965     function getJSDocThisTag(node) {
10966         return getFirstJSDocTag(node, isJSDocThisTag);
10967     }
10968     ts.getJSDocThisTag = getJSDocThisTag;
10969     /** Gets the JSDoc return tag for the node if present */
10970     function getJSDocReturnTag(node) {
10971         return getFirstJSDocTag(node, isJSDocReturnTag);
10972     }
10973     ts.getJSDocReturnTag = getJSDocReturnTag;
10974     /** Gets the JSDoc template tag for the node if present */
10975     function getJSDocTemplateTag(node) {
10976         return getFirstJSDocTag(node, isJSDocTemplateTag);
10977     }
10978     ts.getJSDocTemplateTag = getJSDocTemplateTag;
10979     /** Gets the JSDoc type tag for the node if present and valid */
10980     function getJSDocTypeTag(node) {
10981         // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
10982         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
10983         if (tag && tag.typeExpression && tag.typeExpression.type) {
10984             return tag;
10985         }
10986         return undefined;
10987     }
10988     ts.getJSDocTypeTag = getJSDocTypeTag;
10989     /**
10990      * Gets the type node for the node if provided via JSDoc.
10991      *
10992      * @remarks The search includes any JSDoc param tag that relates
10993      * to the provided parameter, for example a type tag on the
10994      * parameter itself, or a param tag on a containing function
10995      * expression, or a param tag on a variable declaration whose
10996      * initializer is the containing function. The tags closest to the
10997      * node are examined first, so in the previous example, the type
10998      * tag directly on the node would be returned.
10999      */
11000     function getJSDocType(node) {
11001         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
11002         if (!tag && isParameter(node)) {
11003             tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
11004         }
11005         return tag && tag.typeExpression && tag.typeExpression.type;
11006     }
11007     ts.getJSDocType = getJSDocType;
11008     /**
11009      * Gets the return type node for the node if provided via JSDoc return tag or type tag.
11010      *
11011      * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
11012      * gets the type from inside the braces, after the fat arrow, etc.
11013      */
11014     function getJSDocReturnType(node) {
11015         var returnTag = getJSDocReturnTag(node);
11016         if (returnTag && returnTag.typeExpression) {
11017             return returnTag.typeExpression.type;
11018         }
11019         var typeTag = getJSDocTypeTag(node);
11020         if (typeTag && typeTag.typeExpression) {
11021             var type = typeTag.typeExpression.type;
11022             if (isTypeLiteralNode(type)) {
11023                 var sig = ts.find(type.members, isCallSignatureDeclaration);
11024                 return sig && sig.type;
11025             }
11026             if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) {
11027                 return type.type;
11028             }
11029         }
11030     }
11031     ts.getJSDocReturnType = getJSDocReturnType;
11032     /** Get all JSDoc tags related to a node, including those on parent nodes. */
11033     function getJSDocTags(node) {
11034         var tags = node.jsDocCache;
11035         // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
11036         if (tags === undefined) {
11037             var comments = ts.getJSDocCommentsAndTags(node);
11038             ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
11039             node.jsDocCache = tags = ts.flatMap(comments, function (j) { return isJSDoc(j) ? j.tags : j; });
11040         }
11041         return tags;
11042     }
11043     ts.getJSDocTags = getJSDocTags;
11044     /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
11045     function getFirstJSDocTag(node, predicate) {
11046         return ts.find(getJSDocTags(node), predicate);
11047     }
11048     /** Gets all JSDoc tags that match a specified predicate */
11049     function getAllJSDocTags(node, predicate) {
11050         return getJSDocTags(node).filter(predicate);
11051     }
11052     ts.getAllJSDocTags = getAllJSDocTags;
11053     /** Gets all JSDoc tags of a specified kind */
11054     function getAllJSDocTagsOfKind(node, kind) {
11055         return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
11056     }
11057     ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
11058     /**
11059      * Gets the effective type parameters. If the node was parsed in a
11060      * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
11061      */
11062     function getEffectiveTypeParameterDeclarations(node) {
11063         if (isJSDocSignature(node)) {
11064             return ts.emptyArray;
11065         }
11066         if (ts.isJSDocTypeAlias(node)) {
11067             ts.Debug.assert(node.parent.kind === 303 /* JSDocComment */);
11068             return ts.flatMap(node.parent.tags, function (tag) { return isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
11069         }
11070         if (node.typeParameters) {
11071             return node.typeParameters;
11072         }
11073         if (ts.isInJSFile(node)) {
11074             var decls = ts.getJSDocTypeParameterDeclarations(node);
11075             if (decls.length) {
11076                 return decls;
11077             }
11078             var typeTag = getJSDocType(node);
11079             if (typeTag && isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
11080                 return typeTag.typeParameters;
11081             }
11082         }
11083         return ts.emptyArray;
11084     }
11085     ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
11086     function getEffectiveConstraintOfTypeParameter(node) {
11087         return node.constraint ? node.constraint :
11088             isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
11089                 undefined;
11090     }
11091     ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
11092     // #region
11093     // Simple node tests of the form `node.kind === SyntaxKind.Foo`.
11094     // Literals
11095     function isNumericLiteral(node) {
11096         return node.kind === 8 /* NumericLiteral */;
11097     }
11098     ts.isNumericLiteral = isNumericLiteral;
11099     function isBigIntLiteral(node) {
11100         return node.kind === 9 /* BigIntLiteral */;
11101     }
11102     ts.isBigIntLiteral = isBigIntLiteral;
11103     function isStringLiteral(node) {
11104         return node.kind === 10 /* StringLiteral */;
11105     }
11106     ts.isStringLiteral = isStringLiteral;
11107     function isJsxText(node) {
11108         return node.kind === 11 /* JsxText */;
11109     }
11110     ts.isJsxText = isJsxText;
11111     function isRegularExpressionLiteral(node) {
11112         return node.kind === 13 /* RegularExpressionLiteral */;
11113     }
11114     ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
11115     function isNoSubstitutionTemplateLiteral(node) {
11116         return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
11117     }
11118     ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
11119     // Pseudo-literals
11120     function isTemplateHead(node) {
11121         return node.kind === 15 /* TemplateHead */;
11122     }
11123     ts.isTemplateHead = isTemplateHead;
11124     function isTemplateMiddle(node) {
11125         return node.kind === 16 /* TemplateMiddle */;
11126     }
11127     ts.isTemplateMiddle = isTemplateMiddle;
11128     function isTemplateTail(node) {
11129         return node.kind === 17 /* TemplateTail */;
11130     }
11131     ts.isTemplateTail = isTemplateTail;
11132     function isIdentifier(node) {
11133         return node.kind === 75 /* Identifier */;
11134     }
11135     ts.isIdentifier = isIdentifier;
11136     // Names
11137     function isQualifiedName(node) {
11138         return node.kind === 153 /* QualifiedName */;
11139     }
11140     ts.isQualifiedName = isQualifiedName;
11141     function isComputedPropertyName(node) {
11142         return node.kind === 154 /* ComputedPropertyName */;
11143     }
11144     ts.isComputedPropertyName = isComputedPropertyName;
11145     function isPrivateIdentifier(node) {
11146         return node.kind === 76 /* PrivateIdentifier */;
11147     }
11148     ts.isPrivateIdentifier = isPrivateIdentifier;
11149     function isIdentifierOrPrivateIdentifier(node) {
11150         return node.kind === 75 /* Identifier */ || node.kind === 76 /* PrivateIdentifier */;
11151     }
11152     ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
11153     // Signature elements
11154     function isTypeParameterDeclaration(node) {
11155         return node.kind === 155 /* TypeParameter */;
11156     }
11157     ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
11158     function isParameter(node) {
11159         return node.kind === 156 /* Parameter */;
11160     }
11161     ts.isParameter = isParameter;
11162     function isDecorator(node) {
11163         return node.kind === 157 /* Decorator */;
11164     }
11165     ts.isDecorator = isDecorator;
11166     // TypeMember
11167     function isPropertySignature(node) {
11168         return node.kind === 158 /* PropertySignature */;
11169     }
11170     ts.isPropertySignature = isPropertySignature;
11171     function isPropertyDeclaration(node) {
11172         return node.kind === 159 /* PropertyDeclaration */;
11173     }
11174     ts.isPropertyDeclaration = isPropertyDeclaration;
11175     function isMethodSignature(node) {
11176         return node.kind === 160 /* MethodSignature */;
11177     }
11178     ts.isMethodSignature = isMethodSignature;
11179     function isMethodDeclaration(node) {
11180         return node.kind === 161 /* MethodDeclaration */;
11181     }
11182     ts.isMethodDeclaration = isMethodDeclaration;
11183     function isConstructorDeclaration(node) {
11184         return node.kind === 162 /* Constructor */;
11185     }
11186     ts.isConstructorDeclaration = isConstructorDeclaration;
11187     function isGetAccessorDeclaration(node) {
11188         return node.kind === 163 /* GetAccessor */;
11189     }
11190     ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
11191     function isSetAccessorDeclaration(node) {
11192         return node.kind === 164 /* SetAccessor */;
11193     }
11194     ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
11195     function isCallSignatureDeclaration(node) {
11196         return node.kind === 165 /* CallSignature */;
11197     }
11198     ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
11199     function isConstructSignatureDeclaration(node) {
11200         return node.kind === 166 /* ConstructSignature */;
11201     }
11202     ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
11203     function isIndexSignatureDeclaration(node) {
11204         return node.kind === 167 /* IndexSignature */;
11205     }
11206     ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
11207     /* @internal */
11208     function isGetOrSetAccessorDeclaration(node) {
11209         return node.kind === 164 /* SetAccessor */ || node.kind === 163 /* GetAccessor */;
11210     }
11211     ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
11212     // Type
11213     function isTypePredicateNode(node) {
11214         return node.kind === 168 /* TypePredicate */;
11215     }
11216     ts.isTypePredicateNode = isTypePredicateNode;
11217     function isTypeReferenceNode(node) {
11218         return node.kind === 169 /* TypeReference */;
11219     }
11220     ts.isTypeReferenceNode = isTypeReferenceNode;
11221     function isFunctionTypeNode(node) {
11222         return node.kind === 170 /* FunctionType */;
11223     }
11224     ts.isFunctionTypeNode = isFunctionTypeNode;
11225     function isConstructorTypeNode(node) {
11226         return node.kind === 171 /* ConstructorType */;
11227     }
11228     ts.isConstructorTypeNode = isConstructorTypeNode;
11229     function isTypeQueryNode(node) {
11230         return node.kind === 172 /* TypeQuery */;
11231     }
11232     ts.isTypeQueryNode = isTypeQueryNode;
11233     function isTypeLiteralNode(node) {
11234         return node.kind === 173 /* TypeLiteral */;
11235     }
11236     ts.isTypeLiteralNode = isTypeLiteralNode;
11237     function isArrayTypeNode(node) {
11238         return node.kind === 174 /* ArrayType */;
11239     }
11240     ts.isArrayTypeNode = isArrayTypeNode;
11241     function isTupleTypeNode(node) {
11242         return node.kind === 175 /* TupleType */;
11243     }
11244     ts.isTupleTypeNode = isTupleTypeNode;
11245     function isUnionTypeNode(node) {
11246         return node.kind === 178 /* UnionType */;
11247     }
11248     ts.isUnionTypeNode = isUnionTypeNode;
11249     function isIntersectionTypeNode(node) {
11250         return node.kind === 179 /* IntersectionType */;
11251     }
11252     ts.isIntersectionTypeNode = isIntersectionTypeNode;
11253     function isConditionalTypeNode(node) {
11254         return node.kind === 180 /* ConditionalType */;
11255     }
11256     ts.isConditionalTypeNode = isConditionalTypeNode;
11257     function isInferTypeNode(node) {
11258         return node.kind === 181 /* InferType */;
11259     }
11260     ts.isInferTypeNode = isInferTypeNode;
11261     function isParenthesizedTypeNode(node) {
11262         return node.kind === 182 /* ParenthesizedType */;
11263     }
11264     ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
11265     function isThisTypeNode(node) {
11266         return node.kind === 183 /* ThisType */;
11267     }
11268     ts.isThisTypeNode = isThisTypeNode;
11269     function isTypeOperatorNode(node) {
11270         return node.kind === 184 /* TypeOperator */;
11271     }
11272     ts.isTypeOperatorNode = isTypeOperatorNode;
11273     function isIndexedAccessTypeNode(node) {
11274         return node.kind === 185 /* IndexedAccessType */;
11275     }
11276     ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
11277     function isMappedTypeNode(node) {
11278         return node.kind === 186 /* MappedType */;
11279     }
11280     ts.isMappedTypeNode = isMappedTypeNode;
11281     function isLiteralTypeNode(node) {
11282         return node.kind === 187 /* LiteralType */;
11283     }
11284     ts.isLiteralTypeNode = isLiteralTypeNode;
11285     function isImportTypeNode(node) {
11286         return node.kind === 188 /* ImportType */;
11287     }
11288     ts.isImportTypeNode = isImportTypeNode;
11289     // Binding patterns
11290     function isObjectBindingPattern(node) {
11291         return node.kind === 189 /* ObjectBindingPattern */;
11292     }
11293     ts.isObjectBindingPattern = isObjectBindingPattern;
11294     function isArrayBindingPattern(node) {
11295         return node.kind === 190 /* ArrayBindingPattern */;
11296     }
11297     ts.isArrayBindingPattern = isArrayBindingPattern;
11298     function isBindingElement(node) {
11299         return node.kind === 191 /* BindingElement */;
11300     }
11301     ts.isBindingElement = isBindingElement;
11302     // Expression
11303     function isArrayLiteralExpression(node) {
11304         return node.kind === 192 /* ArrayLiteralExpression */;
11305     }
11306     ts.isArrayLiteralExpression = isArrayLiteralExpression;
11307     function isObjectLiteralExpression(node) {
11308         return node.kind === 193 /* ObjectLiteralExpression */;
11309     }
11310     ts.isObjectLiteralExpression = isObjectLiteralExpression;
11311     function isPropertyAccessExpression(node) {
11312         return node.kind === 194 /* PropertyAccessExpression */;
11313     }
11314     ts.isPropertyAccessExpression = isPropertyAccessExpression;
11315     function isPropertyAccessChain(node) {
11316         return isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11317     }
11318     ts.isPropertyAccessChain = isPropertyAccessChain;
11319     function isElementAccessExpression(node) {
11320         return node.kind === 195 /* ElementAccessExpression */;
11321     }
11322     ts.isElementAccessExpression = isElementAccessExpression;
11323     function isElementAccessChain(node) {
11324         return isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11325     }
11326     ts.isElementAccessChain = isElementAccessChain;
11327     function isCallExpression(node) {
11328         return node.kind === 196 /* CallExpression */;
11329     }
11330     ts.isCallExpression = isCallExpression;
11331     function isCallChain(node) {
11332         return isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11333     }
11334     ts.isCallChain = isCallChain;
11335     function isOptionalChain(node) {
11336         var kind = node.kind;
11337         return !!(node.flags & 32 /* OptionalChain */) &&
11338             (kind === 194 /* PropertyAccessExpression */
11339                 || kind === 195 /* ElementAccessExpression */
11340                 || kind === 196 /* CallExpression */
11341                 || kind === 218 /* NonNullExpression */);
11342     }
11343     ts.isOptionalChain = isOptionalChain;
11344     /* @internal */
11345     function isOptionalChainRoot(node) {
11346         return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken;
11347     }
11348     ts.isOptionalChainRoot = isOptionalChainRoot;
11349     /**
11350      * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
11351      */
11352     /* @internal */
11353     function isExpressionOfOptionalChainRoot(node) {
11354         return isOptionalChainRoot(node.parent) && node.parent.expression === node;
11355     }
11356     ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
11357     /**
11358      * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
11359      *
11360      * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
11361      * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
11362      * 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)
11363      * 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
11364      *   the end of the chain starting at `c?.`)
11365      * 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
11366      *   the end of the chain starting at `a?.`)
11367      */
11368     /* @internal */
11369     function isOutermostOptionalChain(node) {
11370         return !isOptionalChain(node.parent) // cases 1, 2, and 3
11371             || isOptionalChainRoot(node.parent) // case 4
11372             || node !== node.parent.expression; // case 5
11373     }
11374     ts.isOutermostOptionalChain = isOutermostOptionalChain;
11375     function isNullishCoalesce(node) {
11376         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
11377     }
11378     ts.isNullishCoalesce = isNullishCoalesce;
11379     function isNewExpression(node) {
11380         return node.kind === 197 /* NewExpression */;
11381     }
11382     ts.isNewExpression = isNewExpression;
11383     function isTaggedTemplateExpression(node) {
11384         return node.kind === 198 /* TaggedTemplateExpression */;
11385     }
11386     ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
11387     function isTypeAssertion(node) {
11388         return node.kind === 199 /* TypeAssertionExpression */;
11389     }
11390     ts.isTypeAssertion = isTypeAssertion;
11391     function isConstTypeReference(node) {
11392         return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
11393             node.typeName.escapedText === "const" && !node.typeArguments;
11394     }
11395     ts.isConstTypeReference = isConstTypeReference;
11396     function isParenthesizedExpression(node) {
11397         return node.kind === 200 /* ParenthesizedExpression */;
11398     }
11399     ts.isParenthesizedExpression = isParenthesizedExpression;
11400     function skipPartiallyEmittedExpressions(node) {
11401         return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
11402     }
11403     ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
11404     function isFunctionExpression(node) {
11405         return node.kind === 201 /* FunctionExpression */;
11406     }
11407     ts.isFunctionExpression = isFunctionExpression;
11408     function isArrowFunction(node) {
11409         return node.kind === 202 /* ArrowFunction */;
11410     }
11411     ts.isArrowFunction = isArrowFunction;
11412     function isDeleteExpression(node) {
11413         return node.kind === 203 /* DeleteExpression */;
11414     }
11415     ts.isDeleteExpression = isDeleteExpression;
11416     function isTypeOfExpression(node) {
11417         return node.kind === 204 /* TypeOfExpression */;
11418     }
11419     ts.isTypeOfExpression = isTypeOfExpression;
11420     function isVoidExpression(node) {
11421         return node.kind === 205 /* VoidExpression */;
11422     }
11423     ts.isVoidExpression = isVoidExpression;
11424     function isAwaitExpression(node) {
11425         return node.kind === 206 /* AwaitExpression */;
11426     }
11427     ts.isAwaitExpression = isAwaitExpression;
11428     function isPrefixUnaryExpression(node) {
11429         return node.kind === 207 /* PrefixUnaryExpression */;
11430     }
11431     ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
11432     function isPostfixUnaryExpression(node) {
11433         return node.kind === 208 /* PostfixUnaryExpression */;
11434     }
11435     ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
11436     function isBinaryExpression(node) {
11437         return node.kind === 209 /* BinaryExpression */;
11438     }
11439     ts.isBinaryExpression = isBinaryExpression;
11440     function isConditionalExpression(node) {
11441         return node.kind === 210 /* ConditionalExpression */;
11442     }
11443     ts.isConditionalExpression = isConditionalExpression;
11444     function isTemplateExpression(node) {
11445         return node.kind === 211 /* TemplateExpression */;
11446     }
11447     ts.isTemplateExpression = isTemplateExpression;
11448     function isYieldExpression(node) {
11449         return node.kind === 212 /* YieldExpression */;
11450     }
11451     ts.isYieldExpression = isYieldExpression;
11452     function isSpreadElement(node) {
11453         return node.kind === 213 /* SpreadElement */;
11454     }
11455     ts.isSpreadElement = isSpreadElement;
11456     function isClassExpression(node) {
11457         return node.kind === 214 /* ClassExpression */;
11458     }
11459     ts.isClassExpression = isClassExpression;
11460     function isOmittedExpression(node) {
11461         return node.kind === 215 /* OmittedExpression */;
11462     }
11463     ts.isOmittedExpression = isOmittedExpression;
11464     function isExpressionWithTypeArguments(node) {
11465         return node.kind === 216 /* ExpressionWithTypeArguments */;
11466     }
11467     ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
11468     function isAsExpression(node) {
11469         return node.kind === 217 /* AsExpression */;
11470     }
11471     ts.isAsExpression = isAsExpression;
11472     function isNonNullExpression(node) {
11473         return node.kind === 218 /* NonNullExpression */;
11474     }
11475     ts.isNonNullExpression = isNonNullExpression;
11476     function isNonNullChain(node) {
11477         return isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11478     }
11479     ts.isNonNullChain = isNonNullChain;
11480     function isMetaProperty(node) {
11481         return node.kind === 219 /* MetaProperty */;
11482     }
11483     ts.isMetaProperty = isMetaProperty;
11484     // Misc
11485     function isTemplateSpan(node) {
11486         return node.kind === 221 /* TemplateSpan */;
11487     }
11488     ts.isTemplateSpan = isTemplateSpan;
11489     function isSemicolonClassElement(node) {
11490         return node.kind === 222 /* SemicolonClassElement */;
11491     }
11492     ts.isSemicolonClassElement = isSemicolonClassElement;
11493     // Block
11494     function isBlock(node) {
11495         return node.kind === 223 /* Block */;
11496     }
11497     ts.isBlock = isBlock;
11498     function isVariableStatement(node) {
11499         return node.kind === 225 /* VariableStatement */;
11500     }
11501     ts.isVariableStatement = isVariableStatement;
11502     function isEmptyStatement(node) {
11503         return node.kind === 224 /* EmptyStatement */;
11504     }
11505     ts.isEmptyStatement = isEmptyStatement;
11506     function isExpressionStatement(node) {
11507         return node.kind === 226 /* ExpressionStatement */;
11508     }
11509     ts.isExpressionStatement = isExpressionStatement;
11510     function isIfStatement(node) {
11511         return node.kind === 227 /* IfStatement */;
11512     }
11513     ts.isIfStatement = isIfStatement;
11514     function isDoStatement(node) {
11515         return node.kind === 228 /* DoStatement */;
11516     }
11517     ts.isDoStatement = isDoStatement;
11518     function isWhileStatement(node) {
11519         return node.kind === 229 /* WhileStatement */;
11520     }
11521     ts.isWhileStatement = isWhileStatement;
11522     function isForStatement(node) {
11523         return node.kind === 230 /* ForStatement */;
11524     }
11525     ts.isForStatement = isForStatement;
11526     function isForInStatement(node) {
11527         return node.kind === 231 /* ForInStatement */;
11528     }
11529     ts.isForInStatement = isForInStatement;
11530     function isForOfStatement(node) {
11531         return node.kind === 232 /* ForOfStatement */;
11532     }
11533     ts.isForOfStatement = isForOfStatement;
11534     function isContinueStatement(node) {
11535         return node.kind === 233 /* ContinueStatement */;
11536     }
11537     ts.isContinueStatement = isContinueStatement;
11538     function isBreakStatement(node) {
11539         return node.kind === 234 /* BreakStatement */;
11540     }
11541     ts.isBreakStatement = isBreakStatement;
11542     function isBreakOrContinueStatement(node) {
11543         return node.kind === 234 /* BreakStatement */ || node.kind === 233 /* ContinueStatement */;
11544     }
11545     ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
11546     function isReturnStatement(node) {
11547         return node.kind === 235 /* ReturnStatement */;
11548     }
11549     ts.isReturnStatement = isReturnStatement;
11550     function isWithStatement(node) {
11551         return node.kind === 236 /* WithStatement */;
11552     }
11553     ts.isWithStatement = isWithStatement;
11554     function isSwitchStatement(node) {
11555         return node.kind === 237 /* SwitchStatement */;
11556     }
11557     ts.isSwitchStatement = isSwitchStatement;
11558     function isLabeledStatement(node) {
11559         return node.kind === 238 /* LabeledStatement */;
11560     }
11561     ts.isLabeledStatement = isLabeledStatement;
11562     function isThrowStatement(node) {
11563         return node.kind === 239 /* ThrowStatement */;
11564     }
11565     ts.isThrowStatement = isThrowStatement;
11566     function isTryStatement(node) {
11567         return node.kind === 240 /* TryStatement */;
11568     }
11569     ts.isTryStatement = isTryStatement;
11570     function isDebuggerStatement(node) {
11571         return node.kind === 241 /* DebuggerStatement */;
11572     }
11573     ts.isDebuggerStatement = isDebuggerStatement;
11574     function isVariableDeclaration(node) {
11575         return node.kind === 242 /* VariableDeclaration */;
11576     }
11577     ts.isVariableDeclaration = isVariableDeclaration;
11578     function isVariableDeclarationList(node) {
11579         return node.kind === 243 /* VariableDeclarationList */;
11580     }
11581     ts.isVariableDeclarationList = isVariableDeclarationList;
11582     function isFunctionDeclaration(node) {
11583         return node.kind === 244 /* FunctionDeclaration */;
11584     }
11585     ts.isFunctionDeclaration = isFunctionDeclaration;
11586     function isClassDeclaration(node) {
11587         return node.kind === 245 /* ClassDeclaration */;
11588     }
11589     ts.isClassDeclaration = isClassDeclaration;
11590     function isInterfaceDeclaration(node) {
11591         return node.kind === 246 /* InterfaceDeclaration */;
11592     }
11593     ts.isInterfaceDeclaration = isInterfaceDeclaration;
11594     function isTypeAliasDeclaration(node) {
11595         return node.kind === 247 /* TypeAliasDeclaration */;
11596     }
11597     ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
11598     function isEnumDeclaration(node) {
11599         return node.kind === 248 /* EnumDeclaration */;
11600     }
11601     ts.isEnumDeclaration = isEnumDeclaration;
11602     function isModuleDeclaration(node) {
11603         return node.kind === 249 /* ModuleDeclaration */;
11604     }
11605     ts.isModuleDeclaration = isModuleDeclaration;
11606     function isModuleBlock(node) {
11607         return node.kind === 250 /* ModuleBlock */;
11608     }
11609     ts.isModuleBlock = isModuleBlock;
11610     function isCaseBlock(node) {
11611         return node.kind === 251 /* CaseBlock */;
11612     }
11613     ts.isCaseBlock = isCaseBlock;
11614     function isNamespaceExportDeclaration(node) {
11615         return node.kind === 252 /* NamespaceExportDeclaration */;
11616     }
11617     ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
11618     function isImportEqualsDeclaration(node) {
11619         return node.kind === 253 /* ImportEqualsDeclaration */;
11620     }
11621     ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
11622     function isImportDeclaration(node) {
11623         return node.kind === 254 /* ImportDeclaration */;
11624     }
11625     ts.isImportDeclaration = isImportDeclaration;
11626     function isImportClause(node) {
11627         return node.kind === 255 /* ImportClause */;
11628     }
11629     ts.isImportClause = isImportClause;
11630     function isNamespaceImport(node) {
11631         return node.kind === 256 /* NamespaceImport */;
11632     }
11633     ts.isNamespaceImport = isNamespaceImport;
11634     function isNamespaceExport(node) {
11635         return node.kind === 262 /* NamespaceExport */;
11636     }
11637     ts.isNamespaceExport = isNamespaceExport;
11638     function isNamedExportBindings(node) {
11639         return node.kind === 262 /* NamespaceExport */ || node.kind === 261 /* NamedExports */;
11640     }
11641     ts.isNamedExportBindings = isNamedExportBindings;
11642     function isNamedImports(node) {
11643         return node.kind === 257 /* NamedImports */;
11644     }
11645     ts.isNamedImports = isNamedImports;
11646     function isImportSpecifier(node) {
11647         return node.kind === 258 /* ImportSpecifier */;
11648     }
11649     ts.isImportSpecifier = isImportSpecifier;
11650     function isExportAssignment(node) {
11651         return node.kind === 259 /* ExportAssignment */;
11652     }
11653     ts.isExportAssignment = isExportAssignment;
11654     function isExportDeclaration(node) {
11655         return node.kind === 260 /* ExportDeclaration */;
11656     }
11657     ts.isExportDeclaration = isExportDeclaration;
11658     function isNamedExports(node) {
11659         return node.kind === 261 /* NamedExports */;
11660     }
11661     ts.isNamedExports = isNamedExports;
11662     function isExportSpecifier(node) {
11663         return node.kind === 263 /* ExportSpecifier */;
11664     }
11665     ts.isExportSpecifier = isExportSpecifier;
11666     function isMissingDeclaration(node) {
11667         return node.kind === 264 /* MissingDeclaration */;
11668     }
11669     ts.isMissingDeclaration = isMissingDeclaration;
11670     // Module References
11671     function isExternalModuleReference(node) {
11672         return node.kind === 265 /* ExternalModuleReference */;
11673     }
11674     ts.isExternalModuleReference = isExternalModuleReference;
11675     // JSX
11676     function isJsxElement(node) {
11677         return node.kind === 266 /* JsxElement */;
11678     }
11679     ts.isJsxElement = isJsxElement;
11680     function isJsxSelfClosingElement(node) {
11681         return node.kind === 267 /* JsxSelfClosingElement */;
11682     }
11683     ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
11684     function isJsxOpeningElement(node) {
11685         return node.kind === 268 /* JsxOpeningElement */;
11686     }
11687     ts.isJsxOpeningElement = isJsxOpeningElement;
11688     function isJsxClosingElement(node) {
11689         return node.kind === 269 /* JsxClosingElement */;
11690     }
11691     ts.isJsxClosingElement = isJsxClosingElement;
11692     function isJsxFragment(node) {
11693         return node.kind === 270 /* JsxFragment */;
11694     }
11695     ts.isJsxFragment = isJsxFragment;
11696     function isJsxOpeningFragment(node) {
11697         return node.kind === 271 /* JsxOpeningFragment */;
11698     }
11699     ts.isJsxOpeningFragment = isJsxOpeningFragment;
11700     function isJsxClosingFragment(node) {
11701         return node.kind === 272 /* JsxClosingFragment */;
11702     }
11703     ts.isJsxClosingFragment = isJsxClosingFragment;
11704     function isJsxAttribute(node) {
11705         return node.kind === 273 /* JsxAttribute */;
11706     }
11707     ts.isJsxAttribute = isJsxAttribute;
11708     function isJsxAttributes(node) {
11709         return node.kind === 274 /* JsxAttributes */;
11710     }
11711     ts.isJsxAttributes = isJsxAttributes;
11712     function isJsxSpreadAttribute(node) {
11713         return node.kind === 275 /* JsxSpreadAttribute */;
11714     }
11715     ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
11716     function isJsxExpression(node) {
11717         return node.kind === 276 /* JsxExpression */;
11718     }
11719     ts.isJsxExpression = isJsxExpression;
11720     // Clauses
11721     function isCaseClause(node) {
11722         return node.kind === 277 /* CaseClause */;
11723     }
11724     ts.isCaseClause = isCaseClause;
11725     function isDefaultClause(node) {
11726         return node.kind === 278 /* DefaultClause */;
11727     }
11728     ts.isDefaultClause = isDefaultClause;
11729     function isHeritageClause(node) {
11730         return node.kind === 279 /* HeritageClause */;
11731     }
11732     ts.isHeritageClause = isHeritageClause;
11733     function isCatchClause(node) {
11734         return node.kind === 280 /* CatchClause */;
11735     }
11736     ts.isCatchClause = isCatchClause;
11737     // Property assignments
11738     function isPropertyAssignment(node) {
11739         return node.kind === 281 /* PropertyAssignment */;
11740     }
11741     ts.isPropertyAssignment = isPropertyAssignment;
11742     function isShorthandPropertyAssignment(node) {
11743         return node.kind === 282 /* ShorthandPropertyAssignment */;
11744     }
11745     ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
11746     function isSpreadAssignment(node) {
11747         return node.kind === 283 /* SpreadAssignment */;
11748     }
11749     ts.isSpreadAssignment = isSpreadAssignment;
11750     // Enum
11751     function isEnumMember(node) {
11752         return node.kind === 284 /* EnumMember */;
11753     }
11754     ts.isEnumMember = isEnumMember;
11755     // Top-level nodes
11756     function isSourceFile(node) {
11757         return node.kind === 290 /* SourceFile */;
11758     }
11759     ts.isSourceFile = isSourceFile;
11760     function isBundle(node) {
11761         return node.kind === 291 /* Bundle */;
11762     }
11763     ts.isBundle = isBundle;
11764     function isUnparsedSource(node) {
11765         return node.kind === 292 /* UnparsedSource */;
11766     }
11767     ts.isUnparsedSource = isUnparsedSource;
11768     function isUnparsedPrepend(node) {
11769         return node.kind === 286 /* UnparsedPrepend */;
11770     }
11771     ts.isUnparsedPrepend = isUnparsedPrepend;
11772     function isUnparsedTextLike(node) {
11773         switch (node.kind) {
11774             case 287 /* UnparsedText */:
11775             case 288 /* UnparsedInternalText */:
11776                 return true;
11777             default:
11778                 return false;
11779         }
11780     }
11781     ts.isUnparsedTextLike = isUnparsedTextLike;
11782     function isUnparsedNode(node) {
11783         return isUnparsedTextLike(node) ||
11784             node.kind === 285 /* UnparsedPrologue */ ||
11785             node.kind === 289 /* UnparsedSyntheticReference */;
11786     }
11787     ts.isUnparsedNode = isUnparsedNode;
11788     // JSDoc
11789     function isJSDocTypeExpression(node) {
11790         return node.kind === 294 /* JSDocTypeExpression */;
11791     }
11792     ts.isJSDocTypeExpression = isJSDocTypeExpression;
11793     function isJSDocAllType(node) {
11794         return node.kind === 295 /* JSDocAllType */;
11795     }
11796     ts.isJSDocAllType = isJSDocAllType;
11797     function isJSDocUnknownType(node) {
11798         return node.kind === 296 /* JSDocUnknownType */;
11799     }
11800     ts.isJSDocUnknownType = isJSDocUnknownType;
11801     function isJSDocNullableType(node) {
11802         return node.kind === 297 /* JSDocNullableType */;
11803     }
11804     ts.isJSDocNullableType = isJSDocNullableType;
11805     function isJSDocNonNullableType(node) {
11806         return node.kind === 298 /* JSDocNonNullableType */;
11807     }
11808     ts.isJSDocNonNullableType = isJSDocNonNullableType;
11809     function isJSDocOptionalType(node) {
11810         return node.kind === 299 /* JSDocOptionalType */;
11811     }
11812     ts.isJSDocOptionalType = isJSDocOptionalType;
11813     function isJSDocFunctionType(node) {
11814         return node.kind === 300 /* JSDocFunctionType */;
11815     }
11816     ts.isJSDocFunctionType = isJSDocFunctionType;
11817     function isJSDocVariadicType(node) {
11818         return node.kind === 301 /* JSDocVariadicType */;
11819     }
11820     ts.isJSDocVariadicType = isJSDocVariadicType;
11821     function isJSDoc(node) {
11822         return node.kind === 303 /* JSDocComment */;
11823     }
11824     ts.isJSDoc = isJSDoc;
11825     function isJSDocAuthorTag(node) {
11826         return node.kind === 309 /* JSDocAuthorTag */;
11827     }
11828     ts.isJSDocAuthorTag = isJSDocAuthorTag;
11829     function isJSDocAugmentsTag(node) {
11830         return node.kind === 307 /* JSDocAugmentsTag */;
11831     }
11832     ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
11833     function isJSDocImplementsTag(node) {
11834         return node.kind === 308 /* JSDocImplementsTag */;
11835     }
11836     ts.isJSDocImplementsTag = isJSDocImplementsTag;
11837     function isJSDocClassTag(node) {
11838         return node.kind === 310 /* JSDocClassTag */;
11839     }
11840     ts.isJSDocClassTag = isJSDocClassTag;
11841     function isJSDocPublicTag(node) {
11842         return node.kind === 311 /* JSDocPublicTag */;
11843     }
11844     ts.isJSDocPublicTag = isJSDocPublicTag;
11845     function isJSDocPrivateTag(node) {
11846         return node.kind === 312 /* JSDocPrivateTag */;
11847     }
11848     ts.isJSDocPrivateTag = isJSDocPrivateTag;
11849     function isJSDocProtectedTag(node) {
11850         return node.kind === 313 /* JSDocProtectedTag */;
11851     }
11852     ts.isJSDocProtectedTag = isJSDocProtectedTag;
11853     function isJSDocReadonlyTag(node) {
11854         return node.kind === 314 /* JSDocReadonlyTag */;
11855     }
11856     ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
11857     function isJSDocEnumTag(node) {
11858         return node.kind === 316 /* JSDocEnumTag */;
11859     }
11860     ts.isJSDocEnumTag = isJSDocEnumTag;
11861     function isJSDocThisTag(node) {
11862         return node.kind === 319 /* JSDocThisTag */;
11863     }
11864     ts.isJSDocThisTag = isJSDocThisTag;
11865     function isJSDocParameterTag(node) {
11866         return node.kind === 317 /* JSDocParameterTag */;
11867     }
11868     ts.isJSDocParameterTag = isJSDocParameterTag;
11869     function isJSDocReturnTag(node) {
11870         return node.kind === 318 /* JSDocReturnTag */;
11871     }
11872     ts.isJSDocReturnTag = isJSDocReturnTag;
11873     function isJSDocTypeTag(node) {
11874         return node.kind === 320 /* JSDocTypeTag */;
11875     }
11876     ts.isJSDocTypeTag = isJSDocTypeTag;
11877     function isJSDocTemplateTag(node) {
11878         return node.kind === 321 /* JSDocTemplateTag */;
11879     }
11880     ts.isJSDocTemplateTag = isJSDocTemplateTag;
11881     function isJSDocTypedefTag(node) {
11882         return node.kind === 322 /* JSDocTypedefTag */;
11883     }
11884     ts.isJSDocTypedefTag = isJSDocTypedefTag;
11885     function isJSDocPropertyTag(node) {
11886         return node.kind === 323 /* JSDocPropertyTag */;
11887     }
11888     ts.isJSDocPropertyTag = isJSDocPropertyTag;
11889     function isJSDocPropertyLikeTag(node) {
11890         return node.kind === 323 /* JSDocPropertyTag */ || node.kind === 317 /* JSDocParameterTag */;
11891     }
11892     ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
11893     function isJSDocTypeLiteral(node) {
11894         return node.kind === 304 /* JSDocTypeLiteral */;
11895     }
11896     ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
11897     function isJSDocCallbackTag(node) {
11898         return node.kind === 315 /* JSDocCallbackTag */;
11899     }
11900     ts.isJSDocCallbackTag = isJSDocCallbackTag;
11901     function isJSDocSignature(node) {
11902         return node.kind === 305 /* JSDocSignature */;
11903     }
11904     ts.isJSDocSignature = isJSDocSignature;
11905     // #endregion
11906     // #region
11907     // Node tests
11908     //
11909     // All node tests in the following list should *not* reference parent pointers so that
11910     // they may be used with transformations.
11911     /* @internal */
11912     function isSyntaxList(n) {
11913         return n.kind === 324 /* SyntaxList */;
11914     }
11915     ts.isSyntaxList = isSyntaxList;
11916     /* @internal */
11917     function isNode(node) {
11918         return isNodeKind(node.kind);
11919     }
11920     ts.isNode = isNode;
11921     /* @internal */
11922     function isNodeKind(kind) {
11923         return kind >= 153 /* FirstNode */;
11924     }
11925     ts.isNodeKind = isNodeKind;
11926     /**
11927      * True if node is of some token syntax kind.
11928      * For example, this is true for an IfKeyword but not for an IfStatement.
11929      * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
11930      */
11931     function isToken(n) {
11932         return n.kind >= 0 /* FirstToken */ && n.kind <= 152 /* LastToken */;
11933     }
11934     ts.isToken = isToken;
11935     // Node Arrays
11936     /* @internal */
11937     function isNodeArray(array) {
11938         return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
11939     }
11940     ts.isNodeArray = isNodeArray;
11941     // Literals
11942     /* @internal */
11943     function isLiteralKind(kind) {
11944         return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
11945     }
11946     ts.isLiteralKind = isLiteralKind;
11947     function isLiteralExpression(node) {
11948         return isLiteralKind(node.kind);
11949     }
11950     ts.isLiteralExpression = isLiteralExpression;
11951     // Pseudo-literals
11952     /* @internal */
11953     function isTemplateLiteralKind(kind) {
11954         return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
11955     }
11956     ts.isTemplateLiteralKind = isTemplateLiteralKind;
11957     function isTemplateLiteralToken(node) {
11958         return isTemplateLiteralKind(node.kind);
11959     }
11960     ts.isTemplateLiteralToken = isTemplateLiteralToken;
11961     function isTemplateMiddleOrTemplateTail(node) {
11962         var kind = node.kind;
11963         return kind === 16 /* TemplateMiddle */
11964             || kind === 17 /* TemplateTail */;
11965     }
11966     ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
11967     function isImportOrExportSpecifier(node) {
11968         return isImportSpecifier(node) || isExportSpecifier(node);
11969     }
11970     ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
11971     function isTypeOnlyImportOrExportDeclaration(node) {
11972         switch (node.kind) {
11973             case 258 /* ImportSpecifier */:
11974             case 263 /* ExportSpecifier */:
11975                 return node.parent.parent.isTypeOnly;
11976             case 256 /* NamespaceImport */:
11977                 return node.parent.isTypeOnly;
11978             case 255 /* ImportClause */:
11979                 return node.isTypeOnly;
11980             default:
11981                 return false;
11982         }
11983     }
11984     ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
11985     function isStringTextContainingNode(node) {
11986         return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
11987     }
11988     ts.isStringTextContainingNode = isStringTextContainingNode;
11989     // Identifiers
11990     /* @internal */
11991     function isGeneratedIdentifier(node) {
11992         return isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
11993     }
11994     ts.isGeneratedIdentifier = isGeneratedIdentifier;
11995     // Private Identifiers
11996     /*@internal*/
11997     function isPrivateIdentifierPropertyDeclaration(node) {
11998         return isPropertyDeclaration(node) && isPrivateIdentifier(node.name);
11999     }
12000     ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
12001     /*@internal*/
12002     function isPrivateIdentifierPropertyAccessExpression(node) {
12003         return isPropertyAccessExpression(node) && isPrivateIdentifier(node.name);
12004     }
12005     ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
12006     // Keywords
12007     /* @internal */
12008     function isModifierKind(token) {
12009         switch (token) {
12010             case 122 /* AbstractKeyword */:
12011             case 126 /* AsyncKeyword */:
12012             case 81 /* ConstKeyword */:
12013             case 130 /* DeclareKeyword */:
12014             case 84 /* DefaultKeyword */:
12015             case 89 /* ExportKeyword */:
12016             case 119 /* PublicKeyword */:
12017             case 117 /* PrivateKeyword */:
12018             case 118 /* ProtectedKeyword */:
12019             case 138 /* ReadonlyKeyword */:
12020             case 120 /* StaticKeyword */:
12021                 return true;
12022         }
12023         return false;
12024     }
12025     ts.isModifierKind = isModifierKind;
12026     /* @internal */
12027     function isParameterPropertyModifier(kind) {
12028         return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
12029     }
12030     ts.isParameterPropertyModifier = isParameterPropertyModifier;
12031     /* @internal */
12032     function isClassMemberModifier(idToken) {
12033         return isParameterPropertyModifier(idToken) || idToken === 120 /* StaticKeyword */;
12034     }
12035     ts.isClassMemberModifier = isClassMemberModifier;
12036     function isModifier(node) {
12037         return isModifierKind(node.kind);
12038     }
12039     ts.isModifier = isModifier;
12040     function isEntityName(node) {
12041         var kind = node.kind;
12042         return kind === 153 /* QualifiedName */
12043             || kind === 75 /* Identifier */;
12044     }
12045     ts.isEntityName = isEntityName;
12046     function isPropertyName(node) {
12047         var kind = node.kind;
12048         return kind === 75 /* Identifier */
12049             || kind === 76 /* PrivateIdentifier */
12050             || kind === 10 /* StringLiteral */
12051             || kind === 8 /* NumericLiteral */
12052             || kind === 154 /* ComputedPropertyName */;
12053     }
12054     ts.isPropertyName = isPropertyName;
12055     function isBindingName(node) {
12056         var kind = node.kind;
12057         return kind === 75 /* Identifier */
12058             || kind === 189 /* ObjectBindingPattern */
12059             || kind === 190 /* ArrayBindingPattern */;
12060     }
12061     ts.isBindingName = isBindingName;
12062     // Functions
12063     function isFunctionLike(node) {
12064         return node && isFunctionLikeKind(node.kind);
12065     }
12066     ts.isFunctionLike = isFunctionLike;
12067     /* @internal */
12068     function isFunctionLikeDeclaration(node) {
12069         return node && isFunctionLikeDeclarationKind(node.kind);
12070     }
12071     ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
12072     function isFunctionLikeDeclarationKind(kind) {
12073         switch (kind) {
12074             case 244 /* FunctionDeclaration */:
12075             case 161 /* MethodDeclaration */:
12076             case 162 /* Constructor */:
12077             case 163 /* GetAccessor */:
12078             case 164 /* SetAccessor */:
12079             case 201 /* FunctionExpression */:
12080             case 202 /* ArrowFunction */:
12081                 return true;
12082             default:
12083                 return false;
12084         }
12085     }
12086     /* @internal */
12087     function isFunctionLikeKind(kind) {
12088         switch (kind) {
12089             case 160 /* MethodSignature */:
12090             case 165 /* CallSignature */:
12091             case 305 /* JSDocSignature */:
12092             case 166 /* ConstructSignature */:
12093             case 167 /* IndexSignature */:
12094             case 170 /* FunctionType */:
12095             case 300 /* JSDocFunctionType */:
12096             case 171 /* ConstructorType */:
12097                 return true;
12098             default:
12099                 return isFunctionLikeDeclarationKind(kind);
12100         }
12101     }
12102     ts.isFunctionLikeKind = isFunctionLikeKind;
12103     /* @internal */
12104     function isFunctionOrModuleBlock(node) {
12105         return isSourceFile(node) || isModuleBlock(node) || isBlock(node) && isFunctionLike(node.parent);
12106     }
12107     ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
12108     // Classes
12109     function isClassElement(node) {
12110         var kind = node.kind;
12111         return kind === 162 /* Constructor */
12112             || kind === 159 /* PropertyDeclaration */
12113             || kind === 161 /* MethodDeclaration */
12114             || kind === 163 /* GetAccessor */
12115             || kind === 164 /* SetAccessor */
12116             || kind === 167 /* IndexSignature */
12117             || kind === 222 /* SemicolonClassElement */;
12118     }
12119     ts.isClassElement = isClassElement;
12120     function isClassLike(node) {
12121         return node && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */);
12122     }
12123     ts.isClassLike = isClassLike;
12124     function isAccessor(node) {
12125         return node && (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */);
12126     }
12127     ts.isAccessor = isAccessor;
12128     /* @internal */
12129     function isMethodOrAccessor(node) {
12130         switch (node.kind) {
12131             case 161 /* MethodDeclaration */:
12132             case 163 /* GetAccessor */:
12133             case 164 /* SetAccessor */:
12134                 return true;
12135             default:
12136                 return false;
12137         }
12138     }
12139     ts.isMethodOrAccessor = isMethodOrAccessor;
12140     // Type members
12141     function isTypeElement(node) {
12142         var kind = node.kind;
12143         return kind === 166 /* ConstructSignature */
12144             || kind === 165 /* CallSignature */
12145             || kind === 158 /* PropertySignature */
12146             || kind === 160 /* MethodSignature */
12147             || kind === 167 /* IndexSignature */;
12148     }
12149     ts.isTypeElement = isTypeElement;
12150     function isClassOrTypeElement(node) {
12151         return isTypeElement(node) || isClassElement(node);
12152     }
12153     ts.isClassOrTypeElement = isClassOrTypeElement;
12154     function isObjectLiteralElementLike(node) {
12155         var kind = node.kind;
12156         return kind === 281 /* PropertyAssignment */
12157             || kind === 282 /* ShorthandPropertyAssignment */
12158             || kind === 283 /* SpreadAssignment */
12159             || kind === 161 /* MethodDeclaration */
12160             || kind === 163 /* GetAccessor */
12161             || kind === 164 /* SetAccessor */;
12162     }
12163     ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
12164     // Type
12165     /**
12166      * Node test that determines whether a node is a valid type node.
12167      * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
12168      * of a TypeNode.
12169      */
12170     function isTypeNode(node) {
12171         return ts.isTypeNodeKind(node.kind);
12172     }
12173     ts.isTypeNode = isTypeNode;
12174     function isFunctionOrConstructorTypeNode(node) {
12175         switch (node.kind) {
12176             case 170 /* FunctionType */:
12177             case 171 /* ConstructorType */:
12178                 return true;
12179         }
12180         return false;
12181     }
12182     ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
12183     // Binding patterns
12184     /* @internal */
12185     function isBindingPattern(node) {
12186         if (node) {
12187             var kind = node.kind;
12188             return kind === 190 /* ArrayBindingPattern */
12189                 || kind === 189 /* ObjectBindingPattern */;
12190         }
12191         return false;
12192     }
12193     ts.isBindingPattern = isBindingPattern;
12194     /* @internal */
12195     function isAssignmentPattern(node) {
12196         var kind = node.kind;
12197         return kind === 192 /* ArrayLiteralExpression */
12198             || kind === 193 /* ObjectLiteralExpression */;
12199     }
12200     ts.isAssignmentPattern = isAssignmentPattern;
12201     /* @internal */
12202     function isArrayBindingElement(node) {
12203         var kind = node.kind;
12204         return kind === 191 /* BindingElement */
12205             || kind === 215 /* OmittedExpression */;
12206     }
12207     ts.isArrayBindingElement = isArrayBindingElement;
12208     /**
12209      * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
12210      */
12211     /* @internal */
12212     function isDeclarationBindingElement(bindingElement) {
12213         switch (bindingElement.kind) {
12214             case 242 /* VariableDeclaration */:
12215             case 156 /* Parameter */:
12216             case 191 /* BindingElement */:
12217                 return true;
12218         }
12219         return false;
12220     }
12221     ts.isDeclarationBindingElement = isDeclarationBindingElement;
12222     /**
12223      * Determines whether a node is a BindingOrAssignmentPattern
12224      */
12225     /* @internal */
12226     function isBindingOrAssignmentPattern(node) {
12227         return isObjectBindingOrAssignmentPattern(node)
12228             || isArrayBindingOrAssignmentPattern(node);
12229     }
12230     ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
12231     /**
12232      * Determines whether a node is an ObjectBindingOrAssignmentPattern
12233      */
12234     /* @internal */
12235     function isObjectBindingOrAssignmentPattern(node) {
12236         switch (node.kind) {
12237             case 189 /* ObjectBindingPattern */:
12238             case 193 /* ObjectLiteralExpression */:
12239                 return true;
12240         }
12241         return false;
12242     }
12243     ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
12244     /**
12245      * Determines whether a node is an ArrayBindingOrAssignmentPattern
12246      */
12247     /* @internal */
12248     function isArrayBindingOrAssignmentPattern(node) {
12249         switch (node.kind) {
12250             case 190 /* ArrayBindingPattern */:
12251             case 192 /* ArrayLiteralExpression */:
12252                 return true;
12253         }
12254         return false;
12255     }
12256     ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
12257     /* @internal */
12258     function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
12259         var kind = node.kind;
12260         return kind === 194 /* PropertyAccessExpression */
12261             || kind === 153 /* QualifiedName */
12262             || kind === 188 /* ImportType */;
12263     }
12264     ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
12265     // Expression
12266     function isPropertyAccessOrQualifiedName(node) {
12267         var kind = node.kind;
12268         return kind === 194 /* PropertyAccessExpression */
12269             || kind === 153 /* QualifiedName */;
12270     }
12271     ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
12272     function isCallLikeExpression(node) {
12273         switch (node.kind) {
12274             case 268 /* JsxOpeningElement */:
12275             case 267 /* JsxSelfClosingElement */:
12276             case 196 /* CallExpression */:
12277             case 197 /* NewExpression */:
12278             case 198 /* TaggedTemplateExpression */:
12279             case 157 /* Decorator */:
12280                 return true;
12281             default:
12282                 return false;
12283         }
12284     }
12285     ts.isCallLikeExpression = isCallLikeExpression;
12286     function isCallOrNewExpression(node) {
12287         return node.kind === 196 /* CallExpression */ || node.kind === 197 /* NewExpression */;
12288     }
12289     ts.isCallOrNewExpression = isCallOrNewExpression;
12290     function isTemplateLiteral(node) {
12291         var kind = node.kind;
12292         return kind === 211 /* TemplateExpression */
12293             || kind === 14 /* NoSubstitutionTemplateLiteral */;
12294     }
12295     ts.isTemplateLiteral = isTemplateLiteral;
12296     /* @internal */
12297     function isLeftHandSideExpression(node) {
12298         return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12299     }
12300     ts.isLeftHandSideExpression = isLeftHandSideExpression;
12301     function isLeftHandSideExpressionKind(kind) {
12302         switch (kind) {
12303             case 194 /* PropertyAccessExpression */:
12304             case 195 /* ElementAccessExpression */:
12305             case 197 /* NewExpression */:
12306             case 196 /* CallExpression */:
12307             case 266 /* JsxElement */:
12308             case 267 /* JsxSelfClosingElement */:
12309             case 270 /* JsxFragment */:
12310             case 198 /* TaggedTemplateExpression */:
12311             case 192 /* ArrayLiteralExpression */:
12312             case 200 /* ParenthesizedExpression */:
12313             case 193 /* ObjectLiteralExpression */:
12314             case 214 /* ClassExpression */:
12315             case 201 /* FunctionExpression */:
12316             case 75 /* Identifier */:
12317             case 13 /* RegularExpressionLiteral */:
12318             case 8 /* NumericLiteral */:
12319             case 9 /* BigIntLiteral */:
12320             case 10 /* StringLiteral */:
12321             case 14 /* NoSubstitutionTemplateLiteral */:
12322             case 211 /* TemplateExpression */:
12323             case 91 /* FalseKeyword */:
12324             case 100 /* NullKeyword */:
12325             case 104 /* ThisKeyword */:
12326             case 106 /* TrueKeyword */:
12327             case 102 /* SuperKeyword */:
12328             case 218 /* NonNullExpression */:
12329             case 219 /* MetaProperty */:
12330             case 96 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
12331                 return true;
12332             default:
12333                 return false;
12334         }
12335     }
12336     /* @internal */
12337     function isUnaryExpression(node) {
12338         return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12339     }
12340     ts.isUnaryExpression = isUnaryExpression;
12341     function isUnaryExpressionKind(kind) {
12342         switch (kind) {
12343             case 207 /* PrefixUnaryExpression */:
12344             case 208 /* PostfixUnaryExpression */:
12345             case 203 /* DeleteExpression */:
12346             case 204 /* TypeOfExpression */:
12347             case 205 /* VoidExpression */:
12348             case 206 /* AwaitExpression */:
12349             case 199 /* TypeAssertionExpression */:
12350                 return true;
12351             default:
12352                 return isLeftHandSideExpressionKind(kind);
12353         }
12354     }
12355     /* @internal */
12356     function isUnaryExpressionWithWrite(expr) {
12357         switch (expr.kind) {
12358             case 208 /* PostfixUnaryExpression */:
12359                 return true;
12360             case 207 /* PrefixUnaryExpression */:
12361                 return expr.operator === 45 /* PlusPlusToken */ ||
12362                     expr.operator === 46 /* MinusMinusToken */;
12363             default:
12364                 return false;
12365         }
12366     }
12367     ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
12368     /* @internal */
12369     /**
12370      * Determines whether a node is an expression based only on its kind.
12371      * Use `isExpressionNode` if not in transforms.
12372      */
12373     function isExpression(node) {
12374         return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12375     }
12376     ts.isExpression = isExpression;
12377     function isExpressionKind(kind) {
12378         switch (kind) {
12379             case 210 /* ConditionalExpression */:
12380             case 212 /* YieldExpression */:
12381             case 202 /* ArrowFunction */:
12382             case 209 /* BinaryExpression */:
12383             case 213 /* SpreadElement */:
12384             case 217 /* AsExpression */:
12385             case 215 /* OmittedExpression */:
12386             case 327 /* CommaListExpression */:
12387             case 326 /* PartiallyEmittedExpression */:
12388                 return true;
12389             default:
12390                 return isUnaryExpressionKind(kind);
12391         }
12392     }
12393     function isAssertionExpression(node) {
12394         var kind = node.kind;
12395         return kind === 199 /* TypeAssertionExpression */
12396             || kind === 217 /* AsExpression */;
12397     }
12398     ts.isAssertionExpression = isAssertionExpression;
12399     /* @internal */
12400     function isPartiallyEmittedExpression(node) {
12401         return node.kind === 326 /* PartiallyEmittedExpression */;
12402     }
12403     ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
12404     /* @internal */
12405     function isNotEmittedStatement(node) {
12406         return node.kind === 325 /* NotEmittedStatement */;
12407     }
12408     ts.isNotEmittedStatement = isNotEmittedStatement;
12409     /* @internal */
12410     function isSyntheticReference(node) {
12411         return node.kind === 330 /* SyntheticReferenceExpression */;
12412     }
12413     ts.isSyntheticReference = isSyntheticReference;
12414     /* @internal */
12415     function isNotEmittedOrPartiallyEmittedNode(node) {
12416         return isNotEmittedStatement(node)
12417             || isPartiallyEmittedExpression(node);
12418     }
12419     ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
12420     function isIterationStatement(node, lookInLabeledStatements) {
12421         switch (node.kind) {
12422             case 230 /* ForStatement */:
12423             case 231 /* ForInStatement */:
12424             case 232 /* ForOfStatement */:
12425             case 228 /* DoStatement */:
12426             case 229 /* WhileStatement */:
12427                 return true;
12428             case 238 /* LabeledStatement */:
12429                 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
12430         }
12431         return false;
12432     }
12433     ts.isIterationStatement = isIterationStatement;
12434     /* @internal */
12435     function isScopeMarker(node) {
12436         return isExportAssignment(node) || isExportDeclaration(node);
12437     }
12438     ts.isScopeMarker = isScopeMarker;
12439     /* @internal */
12440     function hasScopeMarker(statements) {
12441         return ts.some(statements, isScopeMarker);
12442     }
12443     ts.hasScopeMarker = hasScopeMarker;
12444     /* @internal */
12445     function needsScopeMarker(result) {
12446         return !ts.isAnyImportOrReExport(result) && !isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
12447     }
12448     ts.needsScopeMarker = needsScopeMarker;
12449     /* @internal */
12450     function isExternalModuleIndicator(result) {
12451         // Exported top-level member indicates moduleness
12452         return ts.isAnyImportOrReExport(result) || isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
12453     }
12454     ts.isExternalModuleIndicator = isExternalModuleIndicator;
12455     /* @internal */
12456     function isForInOrOfStatement(node) {
12457         return node.kind === 231 /* ForInStatement */ || node.kind === 232 /* ForOfStatement */;
12458     }
12459     ts.isForInOrOfStatement = isForInOrOfStatement;
12460     // Element
12461     /* @internal */
12462     function isConciseBody(node) {
12463         return isBlock(node)
12464             || isExpression(node);
12465     }
12466     ts.isConciseBody = isConciseBody;
12467     /* @internal */
12468     function isFunctionBody(node) {
12469         return isBlock(node);
12470     }
12471     ts.isFunctionBody = isFunctionBody;
12472     /* @internal */
12473     function isForInitializer(node) {
12474         return isVariableDeclarationList(node)
12475             || isExpression(node);
12476     }
12477     ts.isForInitializer = isForInitializer;
12478     /* @internal */
12479     function isModuleBody(node) {
12480         var kind = node.kind;
12481         return kind === 250 /* ModuleBlock */
12482             || kind === 249 /* ModuleDeclaration */
12483             || kind === 75 /* Identifier */;
12484     }
12485     ts.isModuleBody = isModuleBody;
12486     /* @internal */
12487     function isNamespaceBody(node) {
12488         var kind = node.kind;
12489         return kind === 250 /* ModuleBlock */
12490             || kind === 249 /* ModuleDeclaration */;
12491     }
12492     ts.isNamespaceBody = isNamespaceBody;
12493     /* @internal */
12494     function isJSDocNamespaceBody(node) {
12495         var kind = node.kind;
12496         return kind === 75 /* Identifier */
12497             || kind === 249 /* ModuleDeclaration */;
12498     }
12499     ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
12500     /* @internal */
12501     function isNamedImportBindings(node) {
12502         var kind = node.kind;
12503         return kind === 257 /* NamedImports */
12504             || kind === 256 /* NamespaceImport */;
12505     }
12506     ts.isNamedImportBindings = isNamedImportBindings;
12507     /* @internal */
12508     function isModuleOrEnumDeclaration(node) {
12509         return node.kind === 249 /* ModuleDeclaration */ || node.kind === 248 /* EnumDeclaration */;
12510     }
12511     ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
12512     function isDeclarationKind(kind) {
12513         return kind === 202 /* ArrowFunction */
12514             || kind === 191 /* BindingElement */
12515             || kind === 245 /* ClassDeclaration */
12516             || kind === 214 /* ClassExpression */
12517             || kind === 162 /* Constructor */
12518             || kind === 248 /* EnumDeclaration */
12519             || kind === 284 /* EnumMember */
12520             || kind === 263 /* ExportSpecifier */
12521             || kind === 244 /* FunctionDeclaration */
12522             || kind === 201 /* FunctionExpression */
12523             || kind === 163 /* GetAccessor */
12524             || kind === 255 /* ImportClause */
12525             || kind === 253 /* ImportEqualsDeclaration */
12526             || kind === 258 /* ImportSpecifier */
12527             || kind === 246 /* InterfaceDeclaration */
12528             || kind === 273 /* JsxAttribute */
12529             || kind === 161 /* MethodDeclaration */
12530             || kind === 160 /* MethodSignature */
12531             || kind === 249 /* ModuleDeclaration */
12532             || kind === 252 /* NamespaceExportDeclaration */
12533             || kind === 256 /* NamespaceImport */
12534             || kind === 262 /* NamespaceExport */
12535             || kind === 156 /* Parameter */
12536             || kind === 281 /* PropertyAssignment */
12537             || kind === 159 /* PropertyDeclaration */
12538             || kind === 158 /* PropertySignature */
12539             || kind === 164 /* SetAccessor */
12540             || kind === 282 /* ShorthandPropertyAssignment */
12541             || kind === 247 /* TypeAliasDeclaration */
12542             || kind === 155 /* TypeParameter */
12543             || kind === 242 /* VariableDeclaration */
12544             || kind === 322 /* JSDocTypedefTag */
12545             || kind === 315 /* JSDocCallbackTag */
12546             || kind === 323 /* JSDocPropertyTag */;
12547     }
12548     function isDeclarationStatementKind(kind) {
12549         return kind === 244 /* FunctionDeclaration */
12550             || kind === 264 /* MissingDeclaration */
12551             || kind === 245 /* ClassDeclaration */
12552             || kind === 246 /* InterfaceDeclaration */
12553             || kind === 247 /* TypeAliasDeclaration */
12554             || kind === 248 /* EnumDeclaration */
12555             || kind === 249 /* ModuleDeclaration */
12556             || kind === 254 /* ImportDeclaration */
12557             || kind === 253 /* ImportEqualsDeclaration */
12558             || kind === 260 /* ExportDeclaration */
12559             || kind === 259 /* ExportAssignment */
12560             || kind === 252 /* NamespaceExportDeclaration */;
12561     }
12562     function isStatementKindButNotDeclarationKind(kind) {
12563         return kind === 234 /* BreakStatement */
12564             || kind === 233 /* ContinueStatement */
12565             || kind === 241 /* DebuggerStatement */
12566             || kind === 228 /* DoStatement */
12567             || kind === 226 /* ExpressionStatement */
12568             || kind === 224 /* EmptyStatement */
12569             || kind === 231 /* ForInStatement */
12570             || kind === 232 /* ForOfStatement */
12571             || kind === 230 /* ForStatement */
12572             || kind === 227 /* IfStatement */
12573             || kind === 238 /* LabeledStatement */
12574             || kind === 235 /* ReturnStatement */
12575             || kind === 237 /* SwitchStatement */
12576             || kind === 239 /* ThrowStatement */
12577             || kind === 240 /* TryStatement */
12578             || kind === 225 /* VariableStatement */
12579             || kind === 229 /* WhileStatement */
12580             || kind === 236 /* WithStatement */
12581             || kind === 325 /* NotEmittedStatement */
12582             || kind === 329 /* EndOfDeclarationMarker */
12583             || kind === 328 /* MergeDeclarationMarker */;
12584     }
12585     /* @internal */
12586     function isDeclaration(node) {
12587         if (node.kind === 155 /* TypeParameter */) {
12588             return (node.parent && node.parent.kind !== 321 /* JSDocTemplateTag */) || ts.isInJSFile(node);
12589         }
12590         return isDeclarationKind(node.kind);
12591     }
12592     ts.isDeclaration = isDeclaration;
12593     /* @internal */
12594     function isDeclarationStatement(node) {
12595         return isDeclarationStatementKind(node.kind);
12596     }
12597     ts.isDeclarationStatement = isDeclarationStatement;
12598     /**
12599      * Determines whether the node is a statement that is not also a declaration
12600      */
12601     /* @internal */
12602     function isStatementButNotDeclaration(node) {
12603         return isStatementKindButNotDeclarationKind(node.kind);
12604     }
12605     ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
12606     /* @internal */
12607     function isStatement(node) {
12608         var kind = node.kind;
12609         return isStatementKindButNotDeclarationKind(kind)
12610             || isDeclarationStatementKind(kind)
12611             || isBlockStatement(node);
12612     }
12613     ts.isStatement = isStatement;
12614     function isBlockStatement(node) {
12615         if (node.kind !== 223 /* Block */)
12616             return false;
12617         if (node.parent !== undefined) {
12618             if (node.parent.kind === 240 /* TryStatement */ || node.parent.kind === 280 /* CatchClause */) {
12619                 return false;
12620             }
12621         }
12622         return !ts.isFunctionBlock(node);
12623     }
12624     // Module references
12625     /* @internal */
12626     function isModuleReference(node) {
12627         var kind = node.kind;
12628         return kind === 265 /* ExternalModuleReference */
12629             || kind === 153 /* QualifiedName */
12630             || kind === 75 /* Identifier */;
12631     }
12632     ts.isModuleReference = isModuleReference;
12633     // JSX
12634     /* @internal */
12635     function isJsxTagNameExpression(node) {
12636         var kind = node.kind;
12637         return kind === 104 /* ThisKeyword */
12638             || kind === 75 /* Identifier */
12639             || kind === 194 /* PropertyAccessExpression */;
12640     }
12641     ts.isJsxTagNameExpression = isJsxTagNameExpression;
12642     /* @internal */
12643     function isJsxChild(node) {
12644         var kind = node.kind;
12645         return kind === 266 /* JsxElement */
12646             || kind === 276 /* JsxExpression */
12647             || kind === 267 /* JsxSelfClosingElement */
12648             || kind === 11 /* JsxText */
12649             || kind === 270 /* JsxFragment */;
12650     }
12651     ts.isJsxChild = isJsxChild;
12652     /* @internal */
12653     function isJsxAttributeLike(node) {
12654         var kind = node.kind;
12655         return kind === 273 /* JsxAttribute */
12656             || kind === 275 /* JsxSpreadAttribute */;
12657     }
12658     ts.isJsxAttributeLike = isJsxAttributeLike;
12659     /* @internal */
12660     function isStringLiteralOrJsxExpression(node) {
12661         var kind = node.kind;
12662         return kind === 10 /* StringLiteral */
12663             || kind === 276 /* JsxExpression */;
12664     }
12665     ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
12666     function isJsxOpeningLikeElement(node) {
12667         var kind = node.kind;
12668         return kind === 268 /* JsxOpeningElement */
12669             || kind === 267 /* JsxSelfClosingElement */;
12670     }
12671     ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
12672     // Clauses
12673     function isCaseOrDefaultClause(node) {
12674         var kind = node.kind;
12675         return kind === 277 /* CaseClause */
12676             || kind === 278 /* DefaultClause */;
12677     }
12678     ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
12679     // JSDoc
12680     /** True if node is of some JSDoc syntax kind. */
12681     /* @internal */
12682     function isJSDocNode(node) {
12683         return node.kind >= 294 /* FirstJSDocNode */ && node.kind <= 323 /* LastJSDocNode */;
12684     }
12685     ts.isJSDocNode = isJSDocNode;
12686     /** True if node is of a kind that may contain comment text. */
12687     function isJSDocCommentContainingNode(node) {
12688         return node.kind === 303 /* JSDocComment */ || node.kind === 302 /* JSDocNamepathType */ || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node);
12689     }
12690     ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
12691     // TODO: determine what this does before making it public.
12692     /* @internal */
12693     function isJSDocTag(node) {
12694         return node.kind >= 306 /* FirstJSDocTagNode */ && node.kind <= 323 /* LastJSDocTagNode */;
12695     }
12696     ts.isJSDocTag = isJSDocTag;
12697     function isSetAccessor(node) {
12698         return node.kind === 164 /* SetAccessor */;
12699     }
12700     ts.isSetAccessor = isSetAccessor;
12701     function isGetAccessor(node) {
12702         return node.kind === 163 /* GetAccessor */;
12703     }
12704     ts.isGetAccessor = isGetAccessor;
12705     /** True if has jsdoc nodes attached to it. */
12706     /* @internal */
12707     // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
12708     function hasJSDocNodes(node) {
12709         var jsDoc = node.jsDoc;
12710         return !!jsDoc && jsDoc.length > 0;
12711     }
12712     ts.hasJSDocNodes = hasJSDocNodes;
12713     /** True if has type node attached to it. */
12714     /* @internal */
12715     function hasType(node) {
12716         return !!node.type;
12717     }
12718     ts.hasType = hasType;
12719     /** True if has initializer node attached to it. */
12720     /* @internal */
12721     function hasInitializer(node) {
12722         return !!node.initializer;
12723     }
12724     ts.hasInitializer = hasInitializer;
12725     /** True if has initializer node attached to it. */
12726     function hasOnlyExpressionInitializer(node) {
12727         switch (node.kind) {
12728             case 242 /* VariableDeclaration */:
12729             case 156 /* Parameter */:
12730             case 191 /* BindingElement */:
12731             case 158 /* PropertySignature */:
12732             case 159 /* PropertyDeclaration */:
12733             case 281 /* PropertyAssignment */:
12734             case 284 /* EnumMember */:
12735                 return true;
12736             default:
12737                 return false;
12738         }
12739     }
12740     ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
12741     function isObjectLiteralElement(node) {
12742         return node.kind === 273 /* JsxAttribute */ || node.kind === 275 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
12743     }
12744     ts.isObjectLiteralElement = isObjectLiteralElement;
12745     /* @internal */
12746     function isTypeReferenceType(node) {
12747         return node.kind === 169 /* TypeReference */ || node.kind === 216 /* ExpressionWithTypeArguments */;
12748     }
12749     ts.isTypeReferenceType = isTypeReferenceType;
12750     var MAX_SMI_X86 = 1073741823;
12751     /* @internal */
12752     function guessIndentation(lines) {
12753         var indentation = MAX_SMI_X86;
12754         for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
12755             var line = lines_1[_i];
12756             if (!line.length) {
12757                 continue;
12758             }
12759             var i = 0;
12760             for (; i < line.length && i < indentation; i++) {
12761                 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
12762                     break;
12763                 }
12764             }
12765             if (i < indentation) {
12766                 indentation = i;
12767             }
12768             if (indentation === 0) {
12769                 return 0;
12770             }
12771         }
12772         return indentation === MAX_SMI_X86 ? undefined : indentation;
12773     }
12774     ts.guessIndentation = guessIndentation;
12775     function isStringLiteralLike(node) {
12776         return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
12777     }
12778     ts.isStringLiteralLike = isStringLiteralLike;
12779     // #endregion
12780 })(ts || (ts = {}));
12781 /* @internal */
12782 var ts;
12783 (function (ts) {
12784     ts.resolvingEmptyArray = [];
12785     ts.emptyMap = ts.createMap();
12786     ts.emptyUnderscoreEscapedMap = ts.emptyMap;
12787     ts.externalHelpersModuleNameText = "tslib";
12788     ts.defaultMaximumTruncationLength = 160;
12789     ts.noTruncationMaximumTruncationLength = 1000000;
12790     function getDeclarationOfKind(symbol, kind) {
12791         var declarations = symbol.declarations;
12792         if (declarations) {
12793             for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
12794                 var declaration = declarations_1[_i];
12795                 if (declaration.kind === kind) {
12796                     return declaration;
12797                 }
12798             }
12799         }
12800         return undefined;
12801     }
12802     ts.getDeclarationOfKind = getDeclarationOfKind;
12803     /** Create a new escaped identifier map. */
12804     function createUnderscoreEscapedMap() {
12805         return new ts.Map();
12806     }
12807     ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
12808     function hasEntries(map) {
12809         return !!map && !!map.size;
12810     }
12811     ts.hasEntries = hasEntries;
12812     function createSymbolTable(symbols) {
12813         var result = ts.createMap();
12814         if (symbols) {
12815             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
12816                 var symbol = symbols_1[_i];
12817                 result.set(symbol.escapedName, symbol);
12818             }
12819         }
12820         return result;
12821     }
12822     ts.createSymbolTable = createSymbolTable;
12823     function isTransientSymbol(symbol) {
12824         return (symbol.flags & 33554432 /* Transient */) !== 0;
12825     }
12826     ts.isTransientSymbol = isTransientSymbol;
12827     var stringWriter = createSingleLineStringWriter();
12828     function createSingleLineStringWriter() {
12829         var str = "";
12830         var writeText = function (text) { return str += text; };
12831         return {
12832             getText: function () { return str; },
12833             write: writeText,
12834             rawWrite: writeText,
12835             writeKeyword: writeText,
12836             writeOperator: writeText,
12837             writePunctuation: writeText,
12838             writeSpace: writeText,
12839             writeStringLiteral: writeText,
12840             writeLiteral: writeText,
12841             writeParameter: writeText,
12842             writeProperty: writeText,
12843             writeSymbol: function (s, _) { return writeText(s); },
12844             writeTrailingSemicolon: writeText,
12845             writeComment: writeText,
12846             getTextPos: function () { return str.length; },
12847             getLine: function () { return 0; },
12848             getColumn: function () { return 0; },
12849             getIndent: function () { return 0; },
12850             isAtStartOfLine: function () { return false; },
12851             hasTrailingComment: function () { return false; },
12852             hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
12853             // Completely ignore indentation for string writers.  And map newlines to
12854             // a single space.
12855             writeLine: function () { return str += " "; },
12856             increaseIndent: ts.noop,
12857             decreaseIndent: ts.noop,
12858             clear: function () { return str = ""; },
12859             trackSymbol: ts.noop,
12860             reportInaccessibleThisError: ts.noop,
12861             reportInaccessibleUniqueSymbolError: ts.noop,
12862             reportPrivateInBaseOfClassExpression: ts.noop,
12863         };
12864     }
12865     function changesAffectModuleResolution(oldOptions, newOptions) {
12866         return oldOptions.configFilePath !== newOptions.configFilePath ||
12867             optionsHaveModuleResolutionChanges(oldOptions, newOptions);
12868     }
12869     ts.changesAffectModuleResolution = changesAffectModuleResolution;
12870     function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
12871         return ts.moduleResolutionOptionDeclarations.some(function (o) {
12872             return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
12873         });
12874     }
12875     ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
12876     function findAncestor(node, callback) {
12877         while (node) {
12878             var result = callback(node);
12879             if (result === "quit") {
12880                 return undefined;
12881             }
12882             else if (result) {
12883                 return node;
12884             }
12885             node = node.parent;
12886         }
12887         return undefined;
12888     }
12889     ts.findAncestor = findAncestor;
12890     function forEachAncestor(node, callback) {
12891         while (true) {
12892             var res = callback(node);
12893             if (res === "quit")
12894                 return undefined;
12895             if (res !== undefined)
12896                 return res;
12897             if (ts.isSourceFile(node))
12898                 return undefined;
12899             node = node.parent;
12900         }
12901     }
12902     ts.forEachAncestor = forEachAncestor;
12903     function forEachEntry(map, callback) {
12904         var iterator = map.entries();
12905         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12906             var _a = iterResult.value, key = _a[0], value = _a[1];
12907             var result = callback(value, key);
12908             if (result) {
12909                 return result;
12910             }
12911         }
12912         return undefined;
12913     }
12914     ts.forEachEntry = forEachEntry;
12915     function forEachKey(map, callback) {
12916         var iterator = map.keys();
12917         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12918             var result = callback(iterResult.value);
12919             if (result) {
12920                 return result;
12921             }
12922         }
12923         return undefined;
12924     }
12925     ts.forEachKey = forEachKey;
12926     function copyEntries(source, target) {
12927         source.forEach(function (value, key) {
12928             target.set(key, value);
12929         });
12930     }
12931     ts.copyEntries = copyEntries;
12932     function arrayToSet(array, makeKey) {
12933         return ts.arrayToMap(array, makeKey || (function (s) { return s; }), ts.returnTrue);
12934     }
12935     ts.arrayToSet = arrayToSet;
12936     function cloneMap(map) {
12937         var clone = ts.createMap();
12938         copyEntries(map, clone);
12939         return clone;
12940     }
12941     ts.cloneMap = cloneMap;
12942     function usingSingleLineStringWriter(action) {
12943         var oldString = stringWriter.getText();
12944         try {
12945             action(stringWriter);
12946             return stringWriter.getText();
12947         }
12948         finally {
12949             stringWriter.clear();
12950             stringWriter.writeKeyword(oldString);
12951         }
12952     }
12953     ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
12954     function getFullWidth(node) {
12955         return node.end - node.pos;
12956     }
12957     ts.getFullWidth = getFullWidth;
12958     function getResolvedModule(sourceFile, moduleNameText) {
12959         return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
12960     }
12961     ts.getResolvedModule = getResolvedModule;
12962     function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
12963         if (!sourceFile.resolvedModules) {
12964             sourceFile.resolvedModules = ts.createMap();
12965         }
12966         sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
12967     }
12968     ts.setResolvedModule = setResolvedModule;
12969     function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
12970         if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
12971             sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
12972         }
12973         sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
12974     }
12975     ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
12976     function projectReferenceIsEqualTo(oldRef, newRef) {
12977         return oldRef.path === newRef.path &&
12978             !oldRef.prepend === !newRef.prepend &&
12979             !oldRef.circular === !newRef.circular;
12980     }
12981     ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
12982     function moduleResolutionIsEqualTo(oldResolution, newResolution) {
12983         return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
12984             oldResolution.extension === newResolution.extension &&
12985             oldResolution.resolvedFileName === newResolution.resolvedFileName &&
12986             oldResolution.originalPath === newResolution.originalPath &&
12987             packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
12988     }
12989     ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
12990     function packageIdIsEqual(a, b) {
12991         return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
12992     }
12993     function packageIdToString(_a) {
12994         var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
12995         var fullName = subModuleName ? name + "/" + subModuleName : name;
12996         return fullName + "@" + version;
12997     }
12998     ts.packageIdToString = packageIdToString;
12999     function typeDirectiveIsEqualTo(oldResolution, newResolution) {
13000         return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
13001     }
13002     ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
13003     function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
13004         ts.Debug.assert(names.length === newResolutions.length);
13005         for (var i = 0; i < names.length; i++) {
13006             var newResolution = newResolutions[i];
13007             var oldResolution = oldResolutions && oldResolutions.get(names[i]);
13008             var changed = oldResolution
13009                 ? !newResolution || !comparer(oldResolution, newResolution)
13010                 : newResolution;
13011             if (changed) {
13012                 return true;
13013             }
13014         }
13015         return false;
13016     }
13017     ts.hasChangesInResolutions = hasChangesInResolutions;
13018     // Returns true if this node contains a parse error anywhere underneath it.
13019     function containsParseError(node) {
13020         aggregateChildData(node);
13021         return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
13022     }
13023     ts.containsParseError = containsParseError;
13024     function aggregateChildData(node) {
13025         if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
13026             // A node is considered to contain a parse error if:
13027             //  a) the parser explicitly marked that it had an error
13028             //  b) any of it's children reported that it had an error.
13029             var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
13030                 ts.forEachChild(node, containsParseError);
13031             // If so, mark ourselves accordingly.
13032             if (thisNodeOrAnySubNodesHasError) {
13033                 node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
13034             }
13035             // Also mark that we've propagated the child information to this node.  This way we can
13036             // always consult the bit directly on this node without needing to check its children
13037             // again.
13038             node.flags |= 524288 /* HasAggregatedChildData */;
13039         }
13040     }
13041     function getSourceFileOfNode(node) {
13042         while (node && node.kind !== 290 /* SourceFile */) {
13043             node = node.parent;
13044         }
13045         return node;
13046     }
13047     ts.getSourceFileOfNode = getSourceFileOfNode;
13048     function isStatementWithLocals(node) {
13049         switch (node.kind) {
13050             case 223 /* Block */:
13051             case 251 /* CaseBlock */:
13052             case 230 /* ForStatement */:
13053             case 231 /* ForInStatement */:
13054             case 232 /* ForOfStatement */:
13055                 return true;
13056         }
13057         return false;
13058     }
13059     ts.isStatementWithLocals = isStatementWithLocals;
13060     function getStartPositionOfLine(line, sourceFile) {
13061         ts.Debug.assert(line >= 0);
13062         return ts.getLineStarts(sourceFile)[line];
13063     }
13064     ts.getStartPositionOfLine = getStartPositionOfLine;
13065     // This is a useful function for debugging purposes.
13066     function nodePosToString(node) {
13067         var file = getSourceFileOfNode(node);
13068         var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
13069         return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
13070     }
13071     ts.nodePosToString = nodePosToString;
13072     function getEndLinePosition(line, sourceFile) {
13073         ts.Debug.assert(line >= 0);
13074         var lineStarts = ts.getLineStarts(sourceFile);
13075         var lineIndex = line;
13076         var sourceText = sourceFile.text;
13077         if (lineIndex + 1 === lineStarts.length) {
13078             // last line - return EOF
13079             return sourceText.length - 1;
13080         }
13081         else {
13082             // current line start
13083             var start = lineStarts[lineIndex];
13084             // take the start position of the next line - 1 = it should be some line break
13085             var pos = lineStarts[lineIndex + 1] - 1;
13086             ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
13087             // walk backwards skipping line breaks, stop the the beginning of current line.
13088             // i.e:
13089             // <some text>
13090             // $ <- end of line for this position should match the start position
13091             while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
13092                 pos--;
13093             }
13094             return pos;
13095         }
13096     }
13097     ts.getEndLinePosition = getEndLinePosition;
13098     /**
13099      * Returns a value indicating whether a name is unique globally or within the current file.
13100      * 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`.
13101      */
13102     function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
13103         return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
13104     }
13105     ts.isFileLevelUniqueName = isFileLevelUniqueName;
13106     // Returns true if this node is missing from the actual source code. A 'missing' node is different
13107     // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
13108     // in the tree), it is definitely missing. However, a node may be defined, but still be
13109     // missing.  This happens whenever the parser knows it needs to parse something, but can't
13110     // get anything in the source code that it expects at that location. For example:
13111     //
13112     //          let a: ;
13113     //
13114     // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
13115     // code). So the parser will attempt to parse out a type, and will create an actual node.
13116     // However, this node will be 'missing' in the sense that no actual source-code/tokens are
13117     // contained within it.
13118     function nodeIsMissing(node) {
13119         if (node === undefined) {
13120             return true;
13121         }
13122         return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
13123     }
13124     ts.nodeIsMissing = nodeIsMissing;
13125     function nodeIsPresent(node) {
13126         return !nodeIsMissing(node);
13127     }
13128     ts.nodeIsPresent = nodeIsPresent;
13129     function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
13130         if (from === undefined || from.length === 0)
13131             return to;
13132         var statementIndex = 0;
13133         // skip all prologue directives to insert at the correct position
13134         for (; statementIndex < to.length; ++statementIndex) {
13135             if (!isPrologueDirective(to[statementIndex])) {
13136                 break;
13137             }
13138         }
13139         to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
13140         return to;
13141     }
13142     function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
13143         if (statement === undefined)
13144             return to;
13145         var statementIndex = 0;
13146         // skip all prologue directives to insert at the correct position
13147         for (; statementIndex < to.length; ++statementIndex) {
13148             if (!isPrologueDirective(to[statementIndex])) {
13149                 break;
13150             }
13151         }
13152         to.splice(statementIndex, 0, statement);
13153         return to;
13154     }
13155     function isAnyPrologueDirective(node) {
13156         return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13157     }
13158     /**
13159      * Prepends statements to an array while taking care of prologue directives.
13160      */
13161     function insertStatementsAfterStandardPrologue(to, from) {
13162         return insertStatementsAfterPrologue(to, from, isPrologueDirective);
13163     }
13164     ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
13165     function insertStatementsAfterCustomPrologue(to, from) {
13166         return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
13167     }
13168     ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
13169     /**
13170      * Prepends statements to an array while taking care of prologue directives.
13171      */
13172     function insertStatementAfterStandardPrologue(to, statement) {
13173         return insertStatementAfterPrologue(to, statement, isPrologueDirective);
13174     }
13175     ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
13176     function insertStatementAfterCustomPrologue(to, statement) {
13177         return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
13178     }
13179     ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
13180     /**
13181      * Determine if the given comment is a triple-slash
13182      *
13183      * @return true if the comment is a triple-slash comment else false
13184      */
13185     function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
13186         // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
13187         // so that we don't end up computing comment string and doing match for all // comments
13188         if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
13189             commentPos + 2 < commentEnd &&
13190             text.charCodeAt(commentPos + 2) === 47 /* slash */) {
13191             var textSubStr = text.substring(commentPos, commentEnd);
13192             return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
13193                 textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
13194                 textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
13195                 textSubStr.match(defaultLibReferenceRegEx) ?
13196                 true : false;
13197         }
13198         return false;
13199     }
13200     ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
13201     function isPinnedComment(text, start) {
13202         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
13203             text.charCodeAt(start + 2) === 33 /* exclamation */;
13204     }
13205     ts.isPinnedComment = isPinnedComment;
13206     function createCommentDirectivesMap(sourceFile, commentDirectives) {
13207         var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([
13208             "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line,
13209             commentDirective,
13210         ]); }));
13211         var usedLines = ts.createMap();
13212         return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
13213         function getUnusedExpectations() {
13214             return ts.arrayFrom(directivesByLine.entries())
13215                 .filter(function (_a) {
13216                 var line = _a[0], directive = _a[1];
13217                 return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
13218             })
13219                 .map(function (_a) {
13220                 var _ = _a[0], directive = _a[1];
13221                 return directive;
13222             });
13223         }
13224         function markUsed(line) {
13225             if (!directivesByLine.has("" + line)) {
13226                 return false;
13227             }
13228             usedLines.set("" + line, true);
13229             return true;
13230         }
13231     }
13232     ts.createCommentDirectivesMap = createCommentDirectivesMap;
13233     function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
13234         // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
13235         // want to skip trivia because this will launch us forward to the next token.
13236         if (nodeIsMissing(node)) {
13237             return node.pos;
13238         }
13239         if (ts.isJSDocNode(node)) {
13240             return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
13241         }
13242         if (includeJsDoc && ts.hasJSDocNodes(node)) {
13243             return getTokenPosOfNode(node.jsDoc[0], sourceFile);
13244         }
13245         // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
13246         // the syntax list itself considers them as normal trivia. Therefore if we simply skip
13247         // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
13248         // first child to determine the actual position of its first token.
13249         if (node.kind === 324 /* SyntaxList */ && node._children.length > 0) {
13250             return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
13251         }
13252         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
13253     }
13254     ts.getTokenPosOfNode = getTokenPosOfNode;
13255     function getNonDecoratorTokenPosOfNode(node, sourceFile) {
13256         if (nodeIsMissing(node) || !node.decorators) {
13257             return getTokenPosOfNode(node, sourceFile);
13258         }
13259         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
13260     }
13261     ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
13262     function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
13263         if (includeTrivia === void 0) { includeTrivia = false; }
13264         return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
13265     }
13266     ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
13267     function isJSDocTypeExpressionOrChild(node) {
13268         return !!findAncestor(node, ts.isJSDocTypeExpression);
13269     }
13270     function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
13271         if (includeTrivia === void 0) { includeTrivia = false; }
13272         if (nodeIsMissing(node)) {
13273             return "";
13274         }
13275         var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
13276         if (isJSDocTypeExpressionOrChild(node)) {
13277             // strip space + asterisk at line start
13278             text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
13279         }
13280         return text;
13281     }
13282     ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
13283     function getTextOfNode(node, includeTrivia) {
13284         if (includeTrivia === void 0) { includeTrivia = false; }
13285         return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
13286     }
13287     ts.getTextOfNode = getTextOfNode;
13288     function getPos(range) {
13289         return range.pos;
13290     }
13291     /**
13292      * Note: it is expected that the `nodeArray` and the `node` are within the same file.
13293      * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
13294      */
13295     function indexOfNode(nodeArray, node) {
13296         return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
13297     }
13298     ts.indexOfNode = indexOfNode;
13299     /**
13300      * Gets flags that control emit behavior of a node.
13301      */
13302     function getEmitFlags(node) {
13303         var emitNode = node.emitNode;
13304         return emitNode && emitNode.flags || 0;
13305     }
13306     ts.getEmitFlags = getEmitFlags;
13307     function getLiteralText(node, sourceFile, neverAsciiEscape, jsxAttributeEscape) {
13308         // If we don't need to downlevel and we can reach the original source text using
13309         // the node's parent reference, then simply get the text as it was originally written.
13310         if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
13311             ts.isBigIntLiteral(node))) {
13312             return getSourceTextOfNodeFromSourceFile(sourceFile, node);
13313         }
13314         // If we can't reach the original source text, use the canonical form if it's a number,
13315         // or a (possibly escaped) quoted form of the original text if it's string-like.
13316         switch (node.kind) {
13317             case 10 /* StringLiteral */: {
13318                 var escapeText = jsxAttributeEscape ? escapeJsxAttributeString :
13319                     neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13320                         escapeNonAsciiString;
13321                 if (node.singleQuote) {
13322                     return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
13323                 }
13324                 else {
13325                     return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
13326                 }
13327             }
13328             case 14 /* NoSubstitutionTemplateLiteral */:
13329             case 15 /* TemplateHead */:
13330             case 16 /* TemplateMiddle */:
13331             case 17 /* TemplateTail */: {
13332                 // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
13333                 // had to include a backslash: `not \${a} substitution`.
13334                 var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13335                     escapeNonAsciiString;
13336                 var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
13337                 switch (node.kind) {
13338                     case 14 /* NoSubstitutionTemplateLiteral */:
13339                         return "`" + rawText + "`";
13340                     case 15 /* TemplateHead */:
13341                         return "`" + rawText + "${";
13342                     case 16 /* TemplateMiddle */:
13343                         return "}" + rawText + "${";
13344                     case 17 /* TemplateTail */:
13345                         return "}" + rawText + "`";
13346                 }
13347                 break;
13348             }
13349             case 8 /* NumericLiteral */:
13350             case 9 /* BigIntLiteral */:
13351             case 13 /* RegularExpressionLiteral */:
13352                 return node.text;
13353         }
13354         return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
13355     }
13356     ts.getLiteralText = getLiteralText;
13357     function getTextOfConstantValue(value) {
13358         return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
13359     }
13360     ts.getTextOfConstantValue = getTextOfConstantValue;
13361     // Make an identifier from an external module name by extracting the string after the last "/" and replacing
13362     // all non-alphanumeric characters with underscores
13363     function makeIdentifierFromModuleName(moduleName) {
13364         return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
13365     }
13366     ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
13367     function isBlockOrCatchScoped(declaration) {
13368         return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
13369             isCatchClauseVariableDeclarationOrBindingElement(declaration);
13370     }
13371     ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
13372     function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
13373         var node = getRootDeclaration(declaration);
13374         return node.kind === 242 /* VariableDeclaration */ && node.parent.kind === 280 /* CatchClause */;
13375     }
13376     ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
13377     function isAmbientModule(node) {
13378         return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
13379     }
13380     ts.isAmbientModule = isAmbientModule;
13381     function isModuleWithStringLiteralName(node) {
13382         return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
13383     }
13384     ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
13385     function isNonGlobalAmbientModule(node) {
13386         return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
13387     }
13388     ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
13389     /**
13390      * An effective module (namespace) declaration is either
13391      * 1. An actual declaration: namespace X { ... }
13392      * 2. A Javascript declaration, which is:
13393      *    An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
13394      */
13395     function isEffectiveModuleDeclaration(node) {
13396         return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
13397     }
13398     ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
13399     /** Given a symbol for a module, checks that it is a shorthand ambient module. */
13400     function isShorthandAmbientModuleSymbol(moduleSymbol) {
13401         return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
13402     }
13403     ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
13404     function isShorthandAmbientModule(node) {
13405         // The only kind of module that can be missing a body is a shorthand ambient module.
13406         return node && node.kind === 249 /* ModuleDeclaration */ && (!node.body);
13407     }
13408     function isBlockScopedContainerTopLevel(node) {
13409         return node.kind === 290 /* SourceFile */ ||
13410             node.kind === 249 /* ModuleDeclaration */ ||
13411             ts.isFunctionLike(node);
13412     }
13413     ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
13414     function isGlobalScopeAugmentation(module) {
13415         return !!(module.flags & 1024 /* GlobalAugmentation */);
13416     }
13417     ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
13418     function isExternalModuleAugmentation(node) {
13419         return isAmbientModule(node) && isModuleAugmentationExternal(node);
13420     }
13421     ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
13422     function isModuleAugmentationExternal(node) {
13423         // external module augmentation is a ambient module declaration that is either:
13424         // - defined in the top level scope and source file is an external module
13425         // - defined inside ambient module declaration located in the top level scope and source file not an external module
13426         switch (node.parent.kind) {
13427             case 290 /* SourceFile */:
13428                 return ts.isExternalModule(node.parent);
13429             case 250 /* ModuleBlock */:
13430                 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
13431         }
13432         return false;
13433     }
13434     ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
13435     function getNonAugmentationDeclaration(symbol) {
13436         return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
13437     }
13438     ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
13439     function isEffectiveExternalModule(node, compilerOptions) {
13440         return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
13441     }
13442     ts.isEffectiveExternalModule = isEffectiveExternalModule;
13443     /**
13444      * Returns whether the source file will be treated as if it were in strict mode at runtime.
13445      */
13446     function isEffectiveStrictModeSourceFile(node, compilerOptions) {
13447         // We can only verify strict mode for JS/TS files
13448         switch (node.scriptKind) {
13449             case 1 /* JS */:
13450             case 3 /* TS */:
13451             case 2 /* JSX */:
13452             case 4 /* TSX */:
13453                 break;
13454             default:
13455                 return false;
13456         }
13457         // Strict mode does not matter for declaration files.
13458         if (node.isDeclarationFile) {
13459             return false;
13460         }
13461         // If `alwaysStrict` is set, then treat the file as strict.
13462         if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
13463             return true;
13464         }
13465         // Starting with a "use strict" directive indicates the file is strict.
13466         if (ts.startsWithUseStrict(node.statements)) {
13467             return true;
13468         }
13469         if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
13470             // ECMAScript Modules are always strict.
13471             if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
13472                 return true;
13473             }
13474             // Other modules are strict unless otherwise specified.
13475             return !compilerOptions.noImplicitUseStrict;
13476         }
13477         return false;
13478     }
13479     ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
13480     function isBlockScope(node, parentNode) {
13481         switch (node.kind) {
13482             case 290 /* SourceFile */:
13483             case 251 /* CaseBlock */:
13484             case 280 /* CatchClause */:
13485             case 249 /* ModuleDeclaration */:
13486             case 230 /* ForStatement */:
13487             case 231 /* ForInStatement */:
13488             case 232 /* ForOfStatement */:
13489             case 162 /* Constructor */:
13490             case 161 /* MethodDeclaration */:
13491             case 163 /* GetAccessor */:
13492             case 164 /* SetAccessor */:
13493             case 244 /* FunctionDeclaration */:
13494             case 201 /* FunctionExpression */:
13495             case 202 /* ArrowFunction */:
13496                 return true;
13497             case 223 /* Block */:
13498                 // function block is not considered block-scope container
13499                 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
13500                 return !ts.isFunctionLike(parentNode);
13501         }
13502         return false;
13503     }
13504     ts.isBlockScope = isBlockScope;
13505     function isDeclarationWithTypeParameters(node) {
13506         switch (node.kind) {
13507             case 315 /* JSDocCallbackTag */:
13508             case 322 /* JSDocTypedefTag */:
13509             case 305 /* JSDocSignature */:
13510                 return true;
13511             default:
13512                 ts.assertType(node);
13513                 return isDeclarationWithTypeParameterChildren(node);
13514         }
13515     }
13516     ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
13517     function isDeclarationWithTypeParameterChildren(node) {
13518         switch (node.kind) {
13519             case 165 /* CallSignature */:
13520             case 166 /* ConstructSignature */:
13521             case 160 /* MethodSignature */:
13522             case 167 /* IndexSignature */:
13523             case 170 /* FunctionType */:
13524             case 171 /* ConstructorType */:
13525             case 300 /* JSDocFunctionType */:
13526             case 245 /* ClassDeclaration */:
13527             case 214 /* ClassExpression */:
13528             case 246 /* InterfaceDeclaration */:
13529             case 247 /* TypeAliasDeclaration */:
13530             case 321 /* JSDocTemplateTag */:
13531             case 244 /* FunctionDeclaration */:
13532             case 161 /* MethodDeclaration */:
13533             case 162 /* Constructor */:
13534             case 163 /* GetAccessor */:
13535             case 164 /* SetAccessor */:
13536             case 201 /* FunctionExpression */:
13537             case 202 /* ArrowFunction */:
13538                 return true;
13539             default:
13540                 ts.assertType(node);
13541                 return false;
13542         }
13543     }
13544     ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
13545     function isAnyImportSyntax(node) {
13546         switch (node.kind) {
13547             case 254 /* ImportDeclaration */:
13548             case 253 /* ImportEqualsDeclaration */:
13549                 return true;
13550             default:
13551                 return false;
13552         }
13553     }
13554     ts.isAnyImportSyntax = isAnyImportSyntax;
13555     function isLateVisibilityPaintedStatement(node) {
13556         switch (node.kind) {
13557             case 254 /* ImportDeclaration */:
13558             case 253 /* ImportEqualsDeclaration */:
13559             case 225 /* VariableStatement */:
13560             case 245 /* ClassDeclaration */:
13561             case 244 /* FunctionDeclaration */:
13562             case 249 /* ModuleDeclaration */:
13563             case 247 /* TypeAliasDeclaration */:
13564             case 246 /* InterfaceDeclaration */:
13565             case 248 /* EnumDeclaration */:
13566                 return true;
13567             default:
13568                 return false;
13569         }
13570     }
13571     ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
13572     function isAnyImportOrReExport(node) {
13573         return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
13574     }
13575     ts.isAnyImportOrReExport = isAnyImportOrReExport;
13576     // Gets the nearest enclosing block scope container that has the provided node
13577     // as a descendant, that is not the provided node.
13578     function getEnclosingBlockScopeContainer(node) {
13579         return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
13580     }
13581     ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
13582     // Return display name of an identifier
13583     // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
13584     // text of the expression in the computed property.
13585     function declarationNameToString(name) {
13586         return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
13587     }
13588     ts.declarationNameToString = declarationNameToString;
13589     function getNameFromIndexInfo(info) {
13590         return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
13591     }
13592     ts.getNameFromIndexInfo = getNameFromIndexInfo;
13593     function isComputedNonLiteralName(name) {
13594         return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
13595     }
13596     ts.isComputedNonLiteralName = isComputedNonLiteralName;
13597     function getTextOfPropertyName(name) {
13598         switch (name.kind) {
13599             case 75 /* Identifier */:
13600             case 76 /* PrivateIdentifier */:
13601                 return name.escapedText;
13602             case 10 /* StringLiteral */:
13603             case 8 /* NumericLiteral */:
13604             case 14 /* NoSubstitutionTemplateLiteral */:
13605                 return ts.escapeLeadingUnderscores(name.text);
13606             case 154 /* ComputedPropertyName */:
13607                 if (isStringOrNumericLiteralLike(name.expression))
13608                     return ts.escapeLeadingUnderscores(name.expression.text);
13609                 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
13610             default:
13611                 return ts.Debug.assertNever(name);
13612         }
13613     }
13614     ts.getTextOfPropertyName = getTextOfPropertyName;
13615     function entityNameToString(name) {
13616         switch (name.kind) {
13617             case 104 /* ThisKeyword */:
13618                 return "this";
13619             case 76 /* PrivateIdentifier */:
13620             case 75 /* Identifier */:
13621                 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
13622             case 153 /* QualifiedName */:
13623                 return entityNameToString(name.left) + "." + entityNameToString(name.right);
13624             case 194 /* PropertyAccessExpression */:
13625                 if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
13626                     return entityNameToString(name.expression) + "." + entityNameToString(name.name);
13627                 }
13628                 else {
13629                     return ts.Debug.assertNever(name.name);
13630                 }
13631             default:
13632                 return ts.Debug.assertNever(name);
13633         }
13634     }
13635     ts.entityNameToString = entityNameToString;
13636     function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
13637         var sourceFile = getSourceFileOfNode(node);
13638         return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
13639     }
13640     ts.createDiagnosticForNode = createDiagnosticForNode;
13641     function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
13642         var start = ts.skipTrivia(sourceFile.text, nodes.pos);
13643         return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
13644     }
13645     ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
13646     function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
13647         var span = getErrorSpanForNode(sourceFile, node);
13648         return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
13649     }
13650     ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
13651     function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
13652         var sourceFile = getSourceFileOfNode(node);
13653         var span = getErrorSpanForNode(sourceFile, node);
13654         return {
13655             file: sourceFile,
13656             start: span.start,
13657             length: span.length,
13658             code: messageChain.code,
13659             category: messageChain.category,
13660             messageText: messageChain.next ? messageChain : messageChain.messageText,
13661             relatedInformation: relatedInformation
13662         };
13663     }
13664     ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
13665     function createDiagnosticForRange(sourceFile, range, message) {
13666         return {
13667             file: sourceFile,
13668             start: range.pos,
13669             length: range.end - range.pos,
13670             code: message.code,
13671             category: message.category,
13672             messageText: message.message,
13673         };
13674     }
13675     ts.createDiagnosticForRange = createDiagnosticForRange;
13676     function getSpanOfTokenAtPosition(sourceFile, pos) {
13677         var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
13678         scanner.scan();
13679         var start = scanner.getTokenPos();
13680         return ts.createTextSpanFromBounds(start, scanner.getTextPos());
13681     }
13682     ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
13683     function getErrorSpanForArrowFunction(sourceFile, node) {
13684         var pos = ts.skipTrivia(sourceFile.text, node.pos);
13685         if (node.body && node.body.kind === 223 /* Block */) {
13686             var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
13687             var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
13688             if (startLine < endLine) {
13689                 // The arrow function spans multiple lines,
13690                 // make the error span be the first line, inclusive.
13691                 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
13692             }
13693         }
13694         return ts.createTextSpanFromBounds(pos, node.end);
13695     }
13696     function getErrorSpanForNode(sourceFile, node) {
13697         var errorNode = node;
13698         switch (node.kind) {
13699             case 290 /* SourceFile */:
13700                 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
13701                 if (pos_1 === sourceFile.text.length) {
13702                     // file is empty - return span for the beginning of the file
13703                     return ts.createTextSpan(0, 0);
13704                 }
13705                 return getSpanOfTokenAtPosition(sourceFile, pos_1);
13706             // This list is a work in progress. Add missing node kinds to improve their error
13707             // spans.
13708             case 242 /* VariableDeclaration */:
13709             case 191 /* BindingElement */:
13710             case 245 /* ClassDeclaration */:
13711             case 214 /* ClassExpression */:
13712             case 246 /* InterfaceDeclaration */:
13713             case 249 /* ModuleDeclaration */:
13714             case 248 /* EnumDeclaration */:
13715             case 284 /* EnumMember */:
13716             case 244 /* FunctionDeclaration */:
13717             case 201 /* FunctionExpression */:
13718             case 161 /* MethodDeclaration */:
13719             case 163 /* GetAccessor */:
13720             case 164 /* SetAccessor */:
13721             case 247 /* TypeAliasDeclaration */:
13722             case 159 /* PropertyDeclaration */:
13723             case 158 /* PropertySignature */:
13724                 errorNode = node.name;
13725                 break;
13726             case 202 /* ArrowFunction */:
13727                 return getErrorSpanForArrowFunction(sourceFile, node);
13728             case 277 /* CaseClause */:
13729             case 278 /* DefaultClause */:
13730                 var start = ts.skipTrivia(sourceFile.text, node.pos);
13731                 var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
13732                 return ts.createTextSpanFromBounds(start, end);
13733         }
13734         if (errorNode === undefined) {
13735             // If we don't have a better node, then just set the error on the first token of
13736             // construct.
13737             return getSpanOfTokenAtPosition(sourceFile, node.pos);
13738         }
13739         ts.Debug.assert(!ts.isJSDoc(errorNode));
13740         var isMissing = nodeIsMissing(errorNode);
13741         var pos = isMissing || ts.isJsxText(node)
13742             ? errorNode.pos
13743             : ts.skipTrivia(sourceFile.text, errorNode.pos);
13744         // These asserts should all be satisfied for a properly constructed `errorNode`.
13745         if (isMissing) {
13746             ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13747             ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13748         }
13749         else {
13750             ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13751             ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13752         }
13753         return ts.createTextSpanFromBounds(pos, errorNode.end);
13754     }
13755     ts.getErrorSpanForNode = getErrorSpanForNode;
13756     function isExternalOrCommonJsModule(file) {
13757         return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
13758     }
13759     ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
13760     function isJsonSourceFile(file) {
13761         return file.scriptKind === 6 /* JSON */;
13762     }
13763     ts.isJsonSourceFile = isJsonSourceFile;
13764     function isEnumConst(node) {
13765         return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
13766     }
13767     ts.isEnumConst = isEnumConst;
13768     function isDeclarationReadonly(declaration) {
13769         return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
13770     }
13771     ts.isDeclarationReadonly = isDeclarationReadonly;
13772     function isVarConst(node) {
13773         return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
13774     }
13775     ts.isVarConst = isVarConst;
13776     function isLet(node) {
13777         return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
13778     }
13779     ts.isLet = isLet;
13780     function isSuperCall(n) {
13781         return n.kind === 196 /* CallExpression */ && n.expression.kind === 102 /* SuperKeyword */;
13782     }
13783     ts.isSuperCall = isSuperCall;
13784     function isImportCall(n) {
13785         return n.kind === 196 /* CallExpression */ && n.expression.kind === 96 /* ImportKeyword */;
13786     }
13787     ts.isImportCall = isImportCall;
13788     function isImportMeta(n) {
13789         return ts.isMetaProperty(n)
13790             && n.keywordToken === 96 /* ImportKeyword */
13791             && n.name.escapedText === "meta";
13792     }
13793     ts.isImportMeta = isImportMeta;
13794     function isLiteralImportTypeNode(n) {
13795         return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
13796     }
13797     ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
13798     function isPrologueDirective(node) {
13799         return node.kind === 226 /* ExpressionStatement */
13800             && node.expression.kind === 10 /* StringLiteral */;
13801     }
13802     ts.isPrologueDirective = isPrologueDirective;
13803     function isCustomPrologue(node) {
13804         return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13805     }
13806     ts.isCustomPrologue = isCustomPrologue;
13807     function isHoistedFunction(node) {
13808         return isCustomPrologue(node)
13809             && ts.isFunctionDeclaration(node);
13810     }
13811     ts.isHoistedFunction = isHoistedFunction;
13812     function isHoistedVariable(node) {
13813         return ts.isIdentifier(node.name)
13814             && !node.initializer;
13815     }
13816     function isHoistedVariableStatement(node) {
13817         return isCustomPrologue(node)
13818             && ts.isVariableStatement(node)
13819             && ts.every(node.declarationList.declarations, isHoistedVariable);
13820     }
13821     ts.isHoistedVariableStatement = isHoistedVariableStatement;
13822     function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
13823         return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
13824     }
13825     ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
13826     function getJSDocCommentRanges(node, text) {
13827         var commentRanges = (node.kind === 156 /* Parameter */ ||
13828             node.kind === 155 /* TypeParameter */ ||
13829             node.kind === 201 /* FunctionExpression */ ||
13830             node.kind === 202 /* ArrowFunction */ ||
13831             node.kind === 200 /* ParenthesizedExpression */) ?
13832             ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
13833             ts.getLeadingCommentRanges(text, node.pos);
13834         // True if the comment starts with '/**' but not if it is '/**/'
13835         return ts.filter(commentRanges, function (comment) {
13836             return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
13837                 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
13838                 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
13839         });
13840     }
13841     ts.getJSDocCommentRanges = getJSDocCommentRanges;
13842     ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13843     var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
13844     ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13845     var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
13846     function isPartOfTypeNode(node) {
13847         if (168 /* FirstTypeNode */ <= node.kind && node.kind <= 188 /* LastTypeNode */) {
13848             return true;
13849         }
13850         switch (node.kind) {
13851             case 125 /* AnyKeyword */:
13852             case 148 /* UnknownKeyword */:
13853             case 140 /* NumberKeyword */:
13854             case 151 /* BigIntKeyword */:
13855             case 143 /* StringKeyword */:
13856             case 128 /* BooleanKeyword */:
13857             case 144 /* SymbolKeyword */:
13858             case 141 /* ObjectKeyword */:
13859             case 146 /* UndefinedKeyword */:
13860             case 137 /* NeverKeyword */:
13861                 return true;
13862             case 110 /* VoidKeyword */:
13863                 return node.parent.kind !== 205 /* VoidExpression */;
13864             case 216 /* ExpressionWithTypeArguments */:
13865                 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
13866             case 155 /* TypeParameter */:
13867                 return node.parent.kind === 186 /* MappedType */ || node.parent.kind === 181 /* InferType */;
13868             // Identifiers and qualified names may be type nodes, depending on their context. Climb
13869             // above them to find the lowest container
13870             case 75 /* Identifier */:
13871                 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
13872                 if (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) {
13873                     node = node.parent;
13874                 }
13875                 else if (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node) {
13876                     node = node.parent;
13877                 }
13878                 // At this point, node is either a qualified name or an identifier
13879                 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'.");
13880             // falls through
13881             case 153 /* QualifiedName */:
13882             case 194 /* PropertyAccessExpression */:
13883             case 104 /* ThisKeyword */: {
13884                 var parent = node.parent;
13885                 if (parent.kind === 172 /* TypeQuery */) {
13886                     return false;
13887                 }
13888                 if (parent.kind === 188 /* ImportType */) {
13889                     return !parent.isTypeOf;
13890                 }
13891                 // Do not recursively call isPartOfTypeNode on the parent. In the example:
13892                 //
13893                 //     let a: A.B.C;
13894                 //
13895                 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
13896                 // Only C and A.B.C are type nodes.
13897                 if (168 /* FirstTypeNode */ <= parent.kind && parent.kind <= 188 /* LastTypeNode */) {
13898                     return true;
13899                 }
13900                 switch (parent.kind) {
13901                     case 216 /* ExpressionWithTypeArguments */:
13902                         return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
13903                     case 155 /* TypeParameter */:
13904                         return node === parent.constraint;
13905                     case 321 /* JSDocTemplateTag */:
13906                         return node === parent.constraint;
13907                     case 159 /* PropertyDeclaration */:
13908                     case 158 /* PropertySignature */:
13909                     case 156 /* Parameter */:
13910                     case 242 /* VariableDeclaration */:
13911                         return node === parent.type;
13912                     case 244 /* FunctionDeclaration */:
13913                     case 201 /* FunctionExpression */:
13914                     case 202 /* ArrowFunction */:
13915                     case 162 /* Constructor */:
13916                     case 161 /* MethodDeclaration */:
13917                     case 160 /* MethodSignature */:
13918                     case 163 /* GetAccessor */:
13919                     case 164 /* SetAccessor */:
13920                         return node === parent.type;
13921                     case 165 /* CallSignature */:
13922                     case 166 /* ConstructSignature */:
13923                     case 167 /* IndexSignature */:
13924                         return node === parent.type;
13925                     case 199 /* TypeAssertionExpression */:
13926                         return node === parent.type;
13927                     case 196 /* CallExpression */:
13928                     case 197 /* NewExpression */:
13929                         return ts.contains(parent.typeArguments, node);
13930                     case 198 /* TaggedTemplateExpression */:
13931                         // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
13932                         return false;
13933                 }
13934             }
13935         }
13936         return false;
13937     }
13938     ts.isPartOfTypeNode = isPartOfTypeNode;
13939     function isChildOfNodeWithKind(node, kind) {
13940         while (node) {
13941             if (node.kind === kind) {
13942                 return true;
13943             }
13944             node = node.parent;
13945         }
13946         return false;
13947     }
13948     ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
13949     // Warning: This has the same semantics as the forEach family of functions,
13950     //          in that traversal terminates in the event that 'visitor' supplies a truthy value.
13951     function forEachReturnStatement(body, visitor) {
13952         return traverse(body);
13953         function traverse(node) {
13954             switch (node.kind) {
13955                 case 235 /* ReturnStatement */:
13956                     return visitor(node);
13957                 case 251 /* CaseBlock */:
13958                 case 223 /* Block */:
13959                 case 227 /* IfStatement */:
13960                 case 228 /* DoStatement */:
13961                 case 229 /* WhileStatement */:
13962                 case 230 /* ForStatement */:
13963                 case 231 /* ForInStatement */:
13964                 case 232 /* ForOfStatement */:
13965                 case 236 /* WithStatement */:
13966                 case 237 /* SwitchStatement */:
13967                 case 277 /* CaseClause */:
13968                 case 278 /* DefaultClause */:
13969                 case 238 /* LabeledStatement */:
13970                 case 240 /* TryStatement */:
13971                 case 280 /* CatchClause */:
13972                     return ts.forEachChild(node, traverse);
13973             }
13974         }
13975     }
13976     ts.forEachReturnStatement = forEachReturnStatement;
13977     function forEachYieldExpression(body, visitor) {
13978         return traverse(body);
13979         function traverse(node) {
13980             switch (node.kind) {
13981                 case 212 /* YieldExpression */:
13982                     visitor(node);
13983                     var operand = node.expression;
13984                     if (operand) {
13985                         traverse(operand);
13986                     }
13987                     return;
13988                 case 248 /* EnumDeclaration */:
13989                 case 246 /* InterfaceDeclaration */:
13990                 case 249 /* ModuleDeclaration */:
13991                 case 247 /* TypeAliasDeclaration */:
13992                     // These are not allowed inside a generator now, but eventually they may be allowed
13993                     // as local types. Regardless, skip them to avoid the work.
13994                     return;
13995                 default:
13996                     if (ts.isFunctionLike(node)) {
13997                         if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
13998                             // Note that we will not include methods/accessors of a class because they would require
13999                             // first descending into the class. This is by design.
14000                             traverse(node.name.expression);
14001                             return;
14002                         }
14003                     }
14004                     else if (!isPartOfTypeNode(node)) {
14005                         // This is the general case, which should include mostly expressions and statements.
14006                         // Also includes NodeArrays.
14007                         ts.forEachChild(node, traverse);
14008                     }
14009             }
14010         }
14011     }
14012     ts.forEachYieldExpression = forEachYieldExpression;
14013     /**
14014      * Gets the most likely element type for a TypeNode. This is not an exhaustive test
14015      * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
14016      *
14017      * @param node The type node.
14018      */
14019     function getRestParameterElementType(node) {
14020         if (node && node.kind === 174 /* ArrayType */) {
14021             return node.elementType;
14022         }
14023         else if (node && node.kind === 169 /* TypeReference */) {
14024             return ts.singleOrUndefined(node.typeArguments);
14025         }
14026         else {
14027             return undefined;
14028         }
14029     }
14030     ts.getRestParameterElementType = getRestParameterElementType;
14031     function getMembersOfDeclaration(node) {
14032         switch (node.kind) {
14033             case 246 /* InterfaceDeclaration */:
14034             case 245 /* ClassDeclaration */:
14035             case 214 /* ClassExpression */:
14036             case 173 /* TypeLiteral */:
14037                 return node.members;
14038             case 193 /* ObjectLiteralExpression */:
14039                 return node.properties;
14040         }
14041     }
14042     ts.getMembersOfDeclaration = getMembersOfDeclaration;
14043     function isVariableLike(node) {
14044         if (node) {
14045             switch (node.kind) {
14046                 case 191 /* BindingElement */:
14047                 case 284 /* EnumMember */:
14048                 case 156 /* Parameter */:
14049                 case 281 /* PropertyAssignment */:
14050                 case 159 /* PropertyDeclaration */:
14051                 case 158 /* PropertySignature */:
14052                 case 282 /* ShorthandPropertyAssignment */:
14053                 case 242 /* VariableDeclaration */:
14054                     return true;
14055             }
14056         }
14057         return false;
14058     }
14059     ts.isVariableLike = isVariableLike;
14060     function isVariableLikeOrAccessor(node) {
14061         return isVariableLike(node) || ts.isAccessor(node);
14062     }
14063     ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
14064     function isVariableDeclarationInVariableStatement(node) {
14065         return node.parent.kind === 243 /* VariableDeclarationList */
14066             && node.parent.parent.kind === 225 /* VariableStatement */;
14067     }
14068     ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
14069     function isValidESSymbolDeclaration(node) {
14070         return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
14071             ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) :
14072                 ts.isPropertySignature(node) && hasReadonlyModifier(node);
14073     }
14074     ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
14075     function introducesArgumentsExoticObject(node) {
14076         switch (node.kind) {
14077             case 161 /* MethodDeclaration */:
14078             case 160 /* MethodSignature */:
14079             case 162 /* Constructor */:
14080             case 163 /* GetAccessor */:
14081             case 164 /* SetAccessor */:
14082             case 244 /* FunctionDeclaration */:
14083             case 201 /* FunctionExpression */:
14084                 return true;
14085         }
14086         return false;
14087     }
14088     ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
14089     function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
14090         while (true) {
14091             if (beforeUnwrapLabelCallback) {
14092                 beforeUnwrapLabelCallback(node);
14093             }
14094             if (node.statement.kind !== 238 /* LabeledStatement */) {
14095                 return node.statement;
14096             }
14097             node = node.statement;
14098         }
14099     }
14100     ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
14101     function isFunctionBlock(node) {
14102         return node && node.kind === 223 /* Block */ && ts.isFunctionLike(node.parent);
14103     }
14104     ts.isFunctionBlock = isFunctionBlock;
14105     function isObjectLiteralMethod(node) {
14106         return node && node.kind === 161 /* MethodDeclaration */ && node.parent.kind === 193 /* ObjectLiteralExpression */;
14107     }
14108     ts.isObjectLiteralMethod = isObjectLiteralMethod;
14109     function isObjectLiteralOrClassExpressionMethod(node) {
14110         return node.kind === 161 /* MethodDeclaration */ &&
14111             (node.parent.kind === 193 /* ObjectLiteralExpression */ ||
14112                 node.parent.kind === 214 /* ClassExpression */);
14113     }
14114     ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
14115     function isIdentifierTypePredicate(predicate) {
14116         return predicate && predicate.kind === 1 /* Identifier */;
14117     }
14118     ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
14119     function isThisTypePredicate(predicate) {
14120         return predicate && predicate.kind === 0 /* This */;
14121     }
14122     ts.isThisTypePredicate = isThisTypePredicate;
14123     function getPropertyAssignment(objectLiteral, key, key2) {
14124         return objectLiteral.properties.filter(function (property) {
14125             if (property.kind === 281 /* PropertyAssignment */) {
14126                 var propName = getTextOfPropertyName(property.name);
14127                 return key === propName || (!!key2 && key2 === propName);
14128             }
14129             return false;
14130         });
14131     }
14132     ts.getPropertyAssignment = getPropertyAssignment;
14133     function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
14134         if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
14135             var expression = tsConfigSourceFile.statements[0].expression;
14136             return ts.tryCast(expression, ts.isObjectLiteralExpression);
14137         }
14138     }
14139     ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
14140     function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
14141         return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
14142             return ts.isArrayLiteralExpression(property.initializer) ?
14143                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
14144                 undefined;
14145         });
14146     }
14147     ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
14148     function getTsConfigPropArray(tsConfigSourceFile, propKey) {
14149         var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
14150         return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
14151     }
14152     ts.getTsConfigPropArray = getTsConfigPropArray;
14153     function getContainingFunction(node) {
14154         return findAncestor(node.parent, ts.isFunctionLike);
14155     }
14156     ts.getContainingFunction = getContainingFunction;
14157     function getContainingFunctionDeclaration(node) {
14158         return findAncestor(node.parent, ts.isFunctionLikeDeclaration);
14159     }
14160     ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
14161     function getContainingClass(node) {
14162         return findAncestor(node.parent, ts.isClassLike);
14163     }
14164     ts.getContainingClass = getContainingClass;
14165     function getThisContainer(node, includeArrowFunctions) {
14166         ts.Debug.assert(node.kind !== 290 /* SourceFile */);
14167         while (true) {
14168             node = node.parent;
14169             if (!node) {
14170                 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
14171             }
14172             switch (node.kind) {
14173                 case 154 /* ComputedPropertyName */:
14174                     // If the grandparent node is an object literal (as opposed to a class),
14175                     // then the computed property is not a 'this' container.
14176                     // A computed property name in a class needs to be a this container
14177                     // so that we can error on it.
14178                     if (ts.isClassLike(node.parent.parent)) {
14179                         return node;
14180                     }
14181                     // If this is a computed property, then the parent should not
14182                     // make it a this container. The parent might be a property
14183                     // in an object literal, like a method or accessor. But in order for
14184                     // such a parent to be a this container, the reference must be in
14185                     // the *body* of the container.
14186                     node = node.parent;
14187                     break;
14188                 case 157 /* Decorator */:
14189                     // Decorators are always applied outside of the body of a class or method.
14190                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14191                         // If the decorator's parent is a Parameter, we resolve the this container from
14192                         // the grandparent class declaration.
14193                         node = node.parent.parent;
14194                     }
14195                     else if (ts.isClassElement(node.parent)) {
14196                         // If the decorator's parent is a class element, we resolve the 'this' container
14197                         // from the parent class declaration.
14198                         node = node.parent;
14199                     }
14200                     break;
14201                 case 202 /* ArrowFunction */:
14202                     if (!includeArrowFunctions) {
14203                         continue;
14204                     }
14205                 // falls through
14206                 case 244 /* FunctionDeclaration */:
14207                 case 201 /* FunctionExpression */:
14208                 case 249 /* ModuleDeclaration */:
14209                 case 159 /* PropertyDeclaration */:
14210                 case 158 /* PropertySignature */:
14211                 case 161 /* MethodDeclaration */:
14212                 case 160 /* MethodSignature */:
14213                 case 162 /* Constructor */:
14214                 case 163 /* GetAccessor */:
14215                 case 164 /* SetAccessor */:
14216                 case 165 /* CallSignature */:
14217                 case 166 /* ConstructSignature */:
14218                 case 167 /* IndexSignature */:
14219                 case 248 /* EnumDeclaration */:
14220                 case 290 /* SourceFile */:
14221                     return node;
14222             }
14223         }
14224     }
14225     ts.getThisContainer = getThisContainer;
14226     function getNewTargetContainer(node) {
14227         var container = getThisContainer(node, /*includeArrowFunctions*/ false);
14228         if (container) {
14229             switch (container.kind) {
14230                 case 162 /* Constructor */:
14231                 case 244 /* FunctionDeclaration */:
14232                 case 201 /* FunctionExpression */:
14233                     return container;
14234             }
14235         }
14236         return undefined;
14237     }
14238     ts.getNewTargetContainer = getNewTargetContainer;
14239     /**
14240      * Given an super call/property node, returns the closest node where
14241      * - a super call/property access is legal in the node and not legal in the parent node the node.
14242      *   i.e. super call is legal in constructor but not legal in the class body.
14243      * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
14244      * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
14245      *   i.e. super property access is illegal in function declaration but can be legal in the statement list
14246      */
14247     function getSuperContainer(node, stopOnFunctions) {
14248         while (true) {
14249             node = node.parent;
14250             if (!node) {
14251                 return node;
14252             }
14253             switch (node.kind) {
14254                 case 154 /* ComputedPropertyName */:
14255                     node = node.parent;
14256                     break;
14257                 case 244 /* FunctionDeclaration */:
14258                 case 201 /* FunctionExpression */:
14259                 case 202 /* ArrowFunction */:
14260                     if (!stopOnFunctions) {
14261                         continue;
14262                     }
14263                 // falls through
14264                 case 159 /* PropertyDeclaration */:
14265                 case 158 /* PropertySignature */:
14266                 case 161 /* MethodDeclaration */:
14267                 case 160 /* MethodSignature */:
14268                 case 162 /* Constructor */:
14269                 case 163 /* GetAccessor */:
14270                 case 164 /* SetAccessor */:
14271                     return node;
14272                 case 157 /* Decorator */:
14273                     // Decorators are always applied outside of the body of a class or method.
14274                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14275                         // If the decorator's parent is a Parameter, we resolve the this container from
14276                         // the grandparent class declaration.
14277                         node = node.parent.parent;
14278                     }
14279                     else if (ts.isClassElement(node.parent)) {
14280                         // If the decorator's parent is a class element, we resolve the 'this' container
14281                         // from the parent class declaration.
14282                         node = node.parent;
14283                     }
14284                     break;
14285             }
14286         }
14287     }
14288     ts.getSuperContainer = getSuperContainer;
14289     function getImmediatelyInvokedFunctionExpression(func) {
14290         if (func.kind === 201 /* FunctionExpression */ || func.kind === 202 /* ArrowFunction */) {
14291             var prev = func;
14292             var parent = func.parent;
14293             while (parent.kind === 200 /* ParenthesizedExpression */) {
14294                 prev = parent;
14295                 parent = parent.parent;
14296             }
14297             if (parent.kind === 196 /* CallExpression */ && parent.expression === prev) {
14298                 return parent;
14299             }
14300         }
14301     }
14302     ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
14303     function isSuperOrSuperProperty(node) {
14304         return node.kind === 102 /* SuperKeyword */
14305             || isSuperProperty(node);
14306     }
14307     ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
14308     /**
14309      * Determines whether a node is a property or element access expression for `super`.
14310      */
14311     function isSuperProperty(node) {
14312         var kind = node.kind;
14313         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14314             && node.expression.kind === 102 /* SuperKeyword */;
14315     }
14316     ts.isSuperProperty = isSuperProperty;
14317     /**
14318      * Determines whether a node is a property or element access expression for `this`.
14319      */
14320     function isThisProperty(node) {
14321         var kind = node.kind;
14322         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14323             && node.expression.kind === 104 /* ThisKeyword */;
14324     }
14325     ts.isThisProperty = isThisProperty;
14326     function getEntityNameFromTypeNode(node) {
14327         switch (node.kind) {
14328             case 169 /* TypeReference */:
14329                 return node.typeName;
14330             case 216 /* ExpressionWithTypeArguments */:
14331                 return isEntityNameExpression(node.expression)
14332                     ? node.expression
14333                     : undefined;
14334             case 75 /* Identifier */:
14335             case 153 /* QualifiedName */:
14336                 return node;
14337         }
14338         return undefined;
14339     }
14340     ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
14341     function getInvokedExpression(node) {
14342         switch (node.kind) {
14343             case 198 /* TaggedTemplateExpression */:
14344                 return node.tag;
14345             case 268 /* JsxOpeningElement */:
14346             case 267 /* JsxSelfClosingElement */:
14347                 return node.tagName;
14348             default:
14349                 return node.expression;
14350         }
14351     }
14352     ts.getInvokedExpression = getInvokedExpression;
14353     function nodeCanBeDecorated(node, parent, grandparent) {
14354         // private names cannot be used with decorators yet
14355         if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
14356             return false;
14357         }
14358         switch (node.kind) {
14359             case 245 /* ClassDeclaration */:
14360                 // classes are valid targets
14361                 return true;
14362             case 159 /* PropertyDeclaration */:
14363                 // property declarations are valid if their parent is a class declaration.
14364                 return parent.kind === 245 /* ClassDeclaration */;
14365             case 163 /* GetAccessor */:
14366             case 164 /* SetAccessor */:
14367             case 161 /* MethodDeclaration */:
14368                 // if this method has a body and its parent is a class declaration, this is a valid target.
14369                 return node.body !== undefined
14370                     && parent.kind === 245 /* ClassDeclaration */;
14371             case 156 /* Parameter */:
14372                 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
14373                 return parent.body !== undefined
14374                     && (parent.kind === 162 /* Constructor */
14375                         || parent.kind === 161 /* MethodDeclaration */
14376                         || parent.kind === 164 /* SetAccessor */)
14377                     && grandparent.kind === 245 /* ClassDeclaration */;
14378         }
14379         return false;
14380     }
14381     ts.nodeCanBeDecorated = nodeCanBeDecorated;
14382     function nodeIsDecorated(node, parent, grandparent) {
14383         return node.decorators !== undefined
14384             && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
14385     }
14386     ts.nodeIsDecorated = nodeIsDecorated;
14387     function nodeOrChildIsDecorated(node, parent, grandparent) {
14388         return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
14389     }
14390     ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
14391     function childIsDecorated(node, parent) {
14392         switch (node.kind) {
14393             case 245 /* ClassDeclaration */:
14394                 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
14395             case 161 /* MethodDeclaration */:
14396             case 164 /* SetAccessor */:
14397                 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
14398             default:
14399                 return false;
14400         }
14401     }
14402     ts.childIsDecorated = childIsDecorated;
14403     function isJSXTagName(node) {
14404         var parent = node.parent;
14405         if (parent.kind === 268 /* JsxOpeningElement */ ||
14406             parent.kind === 267 /* JsxSelfClosingElement */ ||
14407             parent.kind === 269 /* JsxClosingElement */) {
14408             return parent.tagName === node;
14409         }
14410         return false;
14411     }
14412     ts.isJSXTagName = isJSXTagName;
14413     function isExpressionNode(node) {
14414         switch (node.kind) {
14415             case 102 /* SuperKeyword */:
14416             case 100 /* NullKeyword */:
14417             case 106 /* TrueKeyword */:
14418             case 91 /* FalseKeyword */:
14419             case 13 /* RegularExpressionLiteral */:
14420             case 192 /* ArrayLiteralExpression */:
14421             case 193 /* ObjectLiteralExpression */:
14422             case 194 /* PropertyAccessExpression */:
14423             case 195 /* ElementAccessExpression */:
14424             case 196 /* CallExpression */:
14425             case 197 /* NewExpression */:
14426             case 198 /* TaggedTemplateExpression */:
14427             case 217 /* AsExpression */:
14428             case 199 /* TypeAssertionExpression */:
14429             case 218 /* NonNullExpression */:
14430             case 200 /* ParenthesizedExpression */:
14431             case 201 /* FunctionExpression */:
14432             case 214 /* ClassExpression */:
14433             case 202 /* ArrowFunction */:
14434             case 205 /* VoidExpression */:
14435             case 203 /* DeleteExpression */:
14436             case 204 /* TypeOfExpression */:
14437             case 207 /* PrefixUnaryExpression */:
14438             case 208 /* PostfixUnaryExpression */:
14439             case 209 /* BinaryExpression */:
14440             case 210 /* ConditionalExpression */:
14441             case 213 /* SpreadElement */:
14442             case 211 /* TemplateExpression */:
14443             case 215 /* OmittedExpression */:
14444             case 266 /* JsxElement */:
14445             case 267 /* JsxSelfClosingElement */:
14446             case 270 /* JsxFragment */:
14447             case 212 /* YieldExpression */:
14448             case 206 /* AwaitExpression */:
14449             case 219 /* MetaProperty */:
14450                 return true;
14451             case 153 /* QualifiedName */:
14452                 while (node.parent.kind === 153 /* QualifiedName */) {
14453                     node = node.parent;
14454                 }
14455                 return node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node);
14456             case 75 /* Identifier */:
14457                 if (node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node)) {
14458                     return true;
14459                 }
14460             // falls through
14461             case 8 /* NumericLiteral */:
14462             case 9 /* BigIntLiteral */:
14463             case 10 /* StringLiteral */:
14464             case 14 /* NoSubstitutionTemplateLiteral */:
14465             case 104 /* ThisKeyword */:
14466                 return isInExpressionContext(node);
14467             default:
14468                 return false;
14469         }
14470     }
14471     ts.isExpressionNode = isExpressionNode;
14472     function isInExpressionContext(node) {
14473         var parent = node.parent;
14474         switch (parent.kind) {
14475             case 242 /* VariableDeclaration */:
14476             case 156 /* Parameter */:
14477             case 159 /* PropertyDeclaration */:
14478             case 158 /* PropertySignature */:
14479             case 284 /* EnumMember */:
14480             case 281 /* PropertyAssignment */:
14481             case 191 /* BindingElement */:
14482                 return parent.initializer === node;
14483             case 226 /* ExpressionStatement */:
14484             case 227 /* IfStatement */:
14485             case 228 /* DoStatement */:
14486             case 229 /* WhileStatement */:
14487             case 235 /* ReturnStatement */:
14488             case 236 /* WithStatement */:
14489             case 237 /* SwitchStatement */:
14490             case 277 /* CaseClause */:
14491             case 239 /* ThrowStatement */:
14492                 return parent.expression === node;
14493             case 230 /* ForStatement */:
14494                 var forStatement = parent;
14495                 return (forStatement.initializer === node && forStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14496                     forStatement.condition === node ||
14497                     forStatement.incrementor === node;
14498             case 231 /* ForInStatement */:
14499             case 232 /* ForOfStatement */:
14500                 var forInStatement = parent;
14501                 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14502                     forInStatement.expression === node;
14503             case 199 /* TypeAssertionExpression */:
14504             case 217 /* AsExpression */:
14505                 return node === parent.expression;
14506             case 221 /* TemplateSpan */:
14507                 return node === parent.expression;
14508             case 154 /* ComputedPropertyName */:
14509                 return node === parent.expression;
14510             case 157 /* Decorator */:
14511             case 276 /* JsxExpression */:
14512             case 275 /* JsxSpreadAttribute */:
14513             case 283 /* SpreadAssignment */:
14514                 return true;
14515             case 216 /* ExpressionWithTypeArguments */:
14516                 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14517             case 282 /* ShorthandPropertyAssignment */:
14518                 return parent.objectAssignmentInitializer === node;
14519             default:
14520                 return isExpressionNode(parent);
14521         }
14522     }
14523     ts.isInExpressionContext = isInExpressionContext;
14524     function isPartOfTypeQuery(node) {
14525         while (node.kind === 153 /* QualifiedName */ || node.kind === 75 /* Identifier */) {
14526             node = node.parent;
14527         }
14528         return node.kind === 172 /* TypeQuery */;
14529     }
14530     ts.isPartOfTypeQuery = isPartOfTypeQuery;
14531     function isExternalModuleImportEqualsDeclaration(node) {
14532         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */;
14533     }
14534     ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
14535     function getExternalModuleImportEqualsDeclarationExpression(node) {
14536         ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
14537         return node.moduleReference.expression;
14538     }
14539     ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
14540     function isInternalModuleImportEqualsDeclaration(node) {
14541         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 265 /* ExternalModuleReference */;
14542     }
14543     ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
14544     function isSourceFileJS(file) {
14545         return isInJSFile(file);
14546     }
14547     ts.isSourceFileJS = isSourceFileJS;
14548     function isSourceFileNotJS(file) {
14549         return !isInJSFile(file);
14550     }
14551     ts.isSourceFileNotJS = isSourceFileNotJS;
14552     function isInJSFile(node) {
14553         return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
14554     }
14555     ts.isInJSFile = isInJSFile;
14556     function isInJsonFile(node) {
14557         return !!node && !!(node.flags & 33554432 /* JsonFile */);
14558     }
14559     ts.isInJsonFile = isInJsonFile;
14560     function isSourceFileNotJson(file) {
14561         return !isJsonSourceFile(file);
14562     }
14563     ts.isSourceFileNotJson = isSourceFileNotJson;
14564     function isInJSDoc(node) {
14565         return !!node && !!(node.flags & 4194304 /* JSDoc */);
14566     }
14567     ts.isInJSDoc = isInJSDoc;
14568     function isJSDocIndexSignature(node) {
14569         return ts.isTypeReferenceNode(node) &&
14570             ts.isIdentifier(node.typeName) &&
14571             node.typeName.escapedText === "Object" &&
14572             node.typeArguments && node.typeArguments.length === 2 &&
14573             (node.typeArguments[0].kind === 143 /* StringKeyword */ || node.typeArguments[0].kind === 140 /* NumberKeyword */);
14574     }
14575     ts.isJSDocIndexSignature = isJSDocIndexSignature;
14576     function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
14577         if (callExpression.kind !== 196 /* CallExpression */) {
14578             return false;
14579         }
14580         var _a = callExpression, expression = _a.expression, args = _a.arguments;
14581         if (expression.kind !== 75 /* Identifier */ || expression.escapedText !== "require") {
14582             return false;
14583         }
14584         if (args.length !== 1) {
14585             return false;
14586         }
14587         var arg = args[0];
14588         return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
14589     }
14590     ts.isRequireCall = isRequireCall;
14591     function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) {
14592         return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument);
14593     }
14594     ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
14595     function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) {
14596         if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; }
14597         return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); });
14598     }
14599     ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement;
14600     function isSingleOrDoubleQuote(charCode) {
14601         return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
14602     }
14603     ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
14604     function isStringDoubleQuoted(str, sourceFile) {
14605         return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
14606     }
14607     ts.isStringDoubleQuoted = isStringDoubleQuoted;
14608     function getDeclarationOfExpando(node) {
14609         if (!node.parent) {
14610             return undefined;
14611         }
14612         var name;
14613         var decl;
14614         if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
14615             if (!isInJSFile(node) && !isVarConst(node.parent)) {
14616                 return undefined;
14617             }
14618             name = node.parent.name;
14619             decl = node.parent;
14620         }
14621         else if (ts.isBinaryExpression(node.parent)) {
14622             var parentNode = node.parent;
14623             var parentNodeOperator = node.parent.operatorToken.kind;
14624             if (parentNodeOperator === 62 /* EqualsToken */ && parentNode.right === node) {
14625                 name = parentNode.left;
14626                 decl = name;
14627             }
14628             else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
14629                 if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
14630                     name = parentNode.parent.name;
14631                     decl = parentNode.parent;
14632                 }
14633                 else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && parentNode.parent.right === parentNode) {
14634                     name = parentNode.parent.left;
14635                     decl = name;
14636                 }
14637                 if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) {
14638                     return undefined;
14639                 }
14640             }
14641         }
14642         if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
14643             return undefined;
14644         }
14645         return decl;
14646     }
14647     ts.getDeclarationOfExpando = getDeclarationOfExpando;
14648     function isAssignmentDeclaration(decl) {
14649         return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
14650     }
14651     ts.isAssignmentDeclaration = isAssignmentDeclaration;
14652     /** Get the initializer, taking into account defaulted Javascript initializers */
14653     function getEffectiveInitializer(node) {
14654         if (isInJSFile(node) && node.initializer &&
14655             ts.isBinaryExpression(node.initializer) &&
14656             (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
14657             node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
14658             return node.initializer.right;
14659         }
14660         return node.initializer;
14661     }
14662     ts.getEffectiveInitializer = getEffectiveInitializer;
14663     /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
14664     function getDeclaredExpandoInitializer(node) {
14665         var init = getEffectiveInitializer(node);
14666         return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
14667     }
14668     ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
14669     function hasExpandoValueProperty(node, isPrototypeAssignment) {
14670         return ts.forEach(node.properties, function (p) {
14671             return ts.isPropertyAssignment(p) &&
14672                 ts.isIdentifier(p.name) &&
14673                 p.name.escapedText === "value" &&
14674                 p.initializer &&
14675                 getExpandoInitializer(p.initializer, isPrototypeAssignment);
14676         });
14677     }
14678     /**
14679      * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
14680      * We treat the right hand side of assignments with container-like initalizers as declarations.
14681      */
14682     function getAssignedExpandoInitializer(node) {
14683         if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
14684             var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
14685             return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
14686                 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
14687         }
14688         if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
14689             var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
14690             if (result) {
14691                 return result;
14692             }
14693         }
14694     }
14695     ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
14696     /**
14697      * Recognized expando initializers are:
14698      * 1. (function() {})() -- IIFEs
14699      * 2. function() { } -- Function expressions
14700      * 3. class { } -- Class expressions
14701      * 4. {} -- Empty object literals
14702      * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
14703      *
14704      * This function returns the provided initializer, or undefined if it is not valid.
14705      */
14706     function getExpandoInitializer(initializer, isPrototypeAssignment) {
14707         if (ts.isCallExpression(initializer)) {
14708             var e = skipParentheses(initializer.expression);
14709             return e.kind === 201 /* FunctionExpression */ || e.kind === 202 /* ArrowFunction */ ? initializer : undefined;
14710         }
14711         if (initializer.kind === 201 /* FunctionExpression */ ||
14712             initializer.kind === 214 /* ClassExpression */ ||
14713             initializer.kind === 202 /* ArrowFunction */) {
14714             return initializer;
14715         }
14716         if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
14717             return initializer;
14718         }
14719     }
14720     ts.getExpandoInitializer = getExpandoInitializer;
14721     /**
14722      * A defaulted expando initializer matches the pattern
14723      * `Lhs = Lhs || ExpandoInitializer`
14724      * or `var Lhs = Lhs || ExpandoInitializer`
14725      *
14726      * The second Lhs is required to be the same as the first except that it may be prefixed with
14727      * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
14728      */
14729     function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
14730         var e = ts.isBinaryExpression(initializer)
14731             && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
14732             && getExpandoInitializer(initializer.right, isPrototypeAssignment);
14733         if (e && isSameEntityName(name, initializer.left)) {
14734             return e;
14735         }
14736     }
14737     function isDefaultedExpandoInitializer(node) {
14738         var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
14739             ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
14740                 undefined;
14741         return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
14742     }
14743     ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
14744     /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
14745     function getNameOfExpando(node) {
14746         if (ts.isBinaryExpression(node.parent)) {
14747             var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
14748             if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
14749                 return parent.left;
14750             }
14751         }
14752         else if (ts.isVariableDeclaration(node.parent)) {
14753             return node.parent.name;
14754         }
14755     }
14756     ts.getNameOfExpando = getNameOfExpando;
14757     /**
14758      * Is the 'declared' name the same as the one in the initializer?
14759      * @return true for identical entity names, as well as ones where the initializer is prefixed with
14760      * 'window', 'self' or 'global'. For example:
14761      *
14762      * var my = my || {}
14763      * var min = window.min || {}
14764      * my.app = self.my.app || class { }
14765      */
14766     function isSameEntityName(name, initializer) {
14767         if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
14768             return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(name);
14769         }
14770         if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
14771             (initializer.expression.kind === 104 /* ThisKeyword */ ||
14772                 ts.isIdentifier(initializer.expression) &&
14773                     (initializer.expression.escapedText === "window" ||
14774                         initializer.expression.escapedText === "self" ||
14775                         initializer.expression.escapedText === "global"))) {
14776             var nameOrArgument = getNameOrArgument(initializer);
14777             if (ts.isPrivateIdentifier(nameOrArgument)) {
14778                 ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
14779             }
14780             return isSameEntityName(name, nameOrArgument);
14781         }
14782         if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
14783             return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
14784                 && isSameEntityName(name.expression, initializer.expression);
14785         }
14786         return false;
14787     }
14788     function getRightMostAssignedExpression(node) {
14789         while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
14790             node = node.right;
14791         }
14792         return node;
14793     }
14794     ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
14795     function isExportsIdentifier(node) {
14796         return ts.isIdentifier(node) && node.escapedText === "exports";
14797     }
14798     ts.isExportsIdentifier = isExportsIdentifier;
14799     function isModuleIdentifier(node) {
14800         return ts.isIdentifier(node) && node.escapedText === "module";
14801     }
14802     ts.isModuleIdentifier = isModuleIdentifier;
14803     function isModuleExportsAccessExpression(node) {
14804         return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
14805             && isModuleIdentifier(node.expression)
14806             && getElementOrPropertyAccessName(node) === "exports";
14807     }
14808     ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
14809     /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
14810     /// assignments we treat as special in the binder
14811     function getAssignmentDeclarationKind(expr) {
14812         var special = getAssignmentDeclarationKindWorker(expr);
14813         return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
14814     }
14815     ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
14816     function isBindableObjectDefinePropertyCall(expr) {
14817         return ts.length(expr.arguments) === 3 &&
14818             ts.isPropertyAccessExpression(expr.expression) &&
14819             ts.isIdentifier(expr.expression.expression) &&
14820             ts.idText(expr.expression.expression) === "Object" &&
14821             ts.idText(expr.expression.name) === "defineProperty" &&
14822             isStringOrNumericLiteralLike(expr.arguments[1]) &&
14823             isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
14824     }
14825     ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
14826     /** x.y OR x[0] */
14827     function isLiteralLikeAccess(node) {
14828         return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
14829     }
14830     ts.isLiteralLikeAccess = isLiteralLikeAccess;
14831     /** x[0] OR x['a'] OR x[Symbol.y] */
14832     function isLiteralLikeElementAccess(node) {
14833         return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
14834             isWellKnownSymbolSyntactically(node.argumentExpression));
14835     }
14836     ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
14837     /** Any series of property and element accesses. */
14838     function isBindableStaticAccessExpression(node, excludeThisKeyword) {
14839         return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
14840             || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
14841     }
14842     ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
14843     /** Any series of property and element accesses, ending in a literal element access */
14844     function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
14845         return isLiteralLikeElementAccess(node)
14846             && ((!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */) ||
14847                 isEntityNameExpression(node.expression) ||
14848                 isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
14849     }
14850     ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
14851     function isBindableStaticNameExpression(node, excludeThisKeyword) {
14852         return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
14853     }
14854     ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
14855     function getNameOrArgument(expr) {
14856         if (ts.isPropertyAccessExpression(expr)) {
14857             return expr.name;
14858         }
14859         return expr.argumentExpression;
14860     }
14861     ts.getNameOrArgument = getNameOrArgument;
14862     function getAssignmentDeclarationKindWorker(expr) {
14863         if (ts.isCallExpression(expr)) {
14864             if (!isBindableObjectDefinePropertyCall(expr)) {
14865                 return 0 /* None */;
14866             }
14867             var entityName = expr.arguments[0];
14868             if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
14869                 return 8 /* ObjectDefinePropertyExports */;
14870             }
14871             if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
14872                 return 9 /* ObjectDefinePrototypeProperty */;
14873             }
14874             return 7 /* ObjectDefinePropertyValue */;
14875         }
14876         if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) {
14877             return 0 /* None */;
14878         }
14879         if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
14880             // F.prototype = { ... }
14881             return 6 /* Prototype */;
14882         }
14883         return getAssignmentDeclarationPropertyAccessKind(expr.left);
14884     }
14885     /**
14886      * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
14887      * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
14888      */
14889     /* @internal */
14890     function getElementOrPropertyAccessArgumentExpressionOrName(node) {
14891         if (ts.isPropertyAccessExpression(node)) {
14892             return node.name;
14893         }
14894         var arg = skipParentheses(node.argumentExpression);
14895         if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
14896             return arg;
14897         }
14898         return node;
14899     }
14900     ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
14901     function getElementOrPropertyAccessName(node) {
14902         var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
14903         if (name) {
14904             if (ts.isIdentifier(name)) {
14905                 return name.escapedText;
14906             }
14907             if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
14908                 return ts.escapeLeadingUnderscores(name.text);
14909             }
14910         }
14911         if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
14912             return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
14913         }
14914         return undefined;
14915     }
14916     ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
14917     function getAssignmentDeclarationPropertyAccessKind(lhs) {
14918         if (lhs.expression.kind === 104 /* ThisKeyword */) {
14919             return 4 /* ThisProperty */;
14920         }
14921         else if (isModuleExportsAccessExpression(lhs)) {
14922             // module.exports = expr
14923             return 2 /* ModuleExports */;
14924         }
14925         else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
14926             if (isPrototypeAccess(lhs.expression)) {
14927                 // F.G....prototype.x = expr
14928                 return 3 /* PrototypeProperty */;
14929             }
14930             var nextToLast = lhs;
14931             while (!ts.isIdentifier(nextToLast.expression)) {
14932                 nextToLast = nextToLast.expression;
14933             }
14934             var id = nextToLast.expression;
14935             if ((id.escapedText === "exports" ||
14936                 id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
14937                 // ExportsProperty does not support binding with computed names
14938                 isBindableStaticAccessExpression(lhs)) {
14939                 // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
14940                 return 1 /* ExportsProperty */;
14941             }
14942             if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
14943                 // F.G...x = expr
14944                 return 5 /* Property */;
14945             }
14946         }
14947         return 0 /* None */;
14948     }
14949     ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
14950     function getInitializerOfBinaryExpression(expr) {
14951         while (ts.isBinaryExpression(expr.right)) {
14952             expr = expr.right;
14953         }
14954         return expr.right;
14955     }
14956     ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
14957     function isPrototypePropertyAssignment(node) {
14958         return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
14959     }
14960     ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
14961     function isSpecialPropertyDeclaration(expr) {
14962         return isInJSFile(expr) &&
14963             expr.parent && expr.parent.kind === 226 /* ExpressionStatement */ &&
14964             (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
14965             !!ts.getJSDocTypeTag(expr.parent);
14966     }
14967     ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
14968     function setValueDeclaration(symbol, node) {
14969         var valueDeclaration = symbol.valueDeclaration;
14970         if (!valueDeclaration ||
14971             !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
14972                 (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
14973             (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
14974             // other kinds of value declarations take precedence over modules and assignment declarations
14975             symbol.valueDeclaration = node;
14976         }
14977     }
14978     ts.setValueDeclaration = setValueDeclaration;
14979     function isFunctionSymbol(symbol) {
14980         if (!symbol || !symbol.valueDeclaration) {
14981             return false;
14982         }
14983         var decl = symbol.valueDeclaration;
14984         return decl.kind === 244 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
14985     }
14986     ts.isFunctionSymbol = isFunctionSymbol;
14987     function importFromModuleSpecifier(node) {
14988         return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
14989     }
14990     ts.importFromModuleSpecifier = importFromModuleSpecifier;
14991     function tryGetImportFromModuleSpecifier(node) {
14992         switch (node.parent.kind) {
14993             case 254 /* ImportDeclaration */:
14994             case 260 /* ExportDeclaration */:
14995                 return node.parent;
14996             case 265 /* ExternalModuleReference */:
14997                 return node.parent.parent;
14998             case 196 /* CallExpression */:
14999                 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
15000             case 187 /* LiteralType */:
15001                 ts.Debug.assert(ts.isStringLiteral(node));
15002                 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
15003             default:
15004                 return undefined;
15005         }
15006     }
15007     ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
15008     function getExternalModuleName(node) {
15009         switch (node.kind) {
15010             case 254 /* ImportDeclaration */:
15011             case 260 /* ExportDeclaration */:
15012                 return node.moduleSpecifier;
15013             case 253 /* ImportEqualsDeclaration */:
15014                 return node.moduleReference.kind === 265 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
15015             case 188 /* ImportType */:
15016                 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
15017             default:
15018                 return ts.Debug.assertNever(node);
15019         }
15020     }
15021     ts.getExternalModuleName = getExternalModuleName;
15022     function getNamespaceDeclarationNode(node) {
15023         switch (node.kind) {
15024             case 254 /* ImportDeclaration */:
15025                 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
15026             case 253 /* ImportEqualsDeclaration */:
15027                 return node;
15028             case 260 /* ExportDeclaration */:
15029                 return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
15030             default:
15031                 return ts.Debug.assertNever(node);
15032         }
15033     }
15034     ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
15035     function isDefaultImport(node) {
15036         return node.kind === 254 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
15037     }
15038     ts.isDefaultImport = isDefaultImport;
15039     function forEachImportClauseDeclaration(node, action) {
15040         if (node.name) {
15041             var result = action(node);
15042             if (result)
15043                 return result;
15044         }
15045         if (node.namedBindings) {
15046             var result = ts.isNamespaceImport(node.namedBindings)
15047                 ? action(node.namedBindings)
15048                 : ts.forEach(node.namedBindings.elements, action);
15049             if (result)
15050                 return result;
15051         }
15052     }
15053     ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
15054     function hasQuestionToken(node) {
15055         if (node) {
15056             switch (node.kind) {
15057                 case 156 /* Parameter */:
15058                 case 161 /* MethodDeclaration */:
15059                 case 160 /* MethodSignature */:
15060                 case 282 /* ShorthandPropertyAssignment */:
15061                 case 281 /* PropertyAssignment */:
15062                 case 159 /* PropertyDeclaration */:
15063                 case 158 /* PropertySignature */:
15064                     return node.questionToken !== undefined;
15065             }
15066         }
15067         return false;
15068     }
15069     ts.hasQuestionToken = hasQuestionToken;
15070     function isJSDocConstructSignature(node) {
15071         var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
15072         var name = ts.tryCast(param && param.name, ts.isIdentifier);
15073         return !!name && name.escapedText === "new";
15074     }
15075     ts.isJSDocConstructSignature = isJSDocConstructSignature;
15076     function isJSDocTypeAlias(node) {
15077         return node.kind === 322 /* JSDocTypedefTag */ || node.kind === 315 /* JSDocCallbackTag */ || node.kind === 316 /* JSDocEnumTag */;
15078     }
15079     ts.isJSDocTypeAlias = isJSDocTypeAlias;
15080     function isTypeAlias(node) {
15081         return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
15082     }
15083     ts.isTypeAlias = isTypeAlias;
15084     function getSourceOfAssignment(node) {
15085         return ts.isExpressionStatement(node) &&
15086             ts.isBinaryExpression(node.expression) &&
15087             node.expression.operatorToken.kind === 62 /* EqualsToken */
15088             ? getRightMostAssignedExpression(node.expression)
15089             : undefined;
15090     }
15091     function getSourceOfDefaultedAssignment(node) {
15092         return ts.isExpressionStatement(node) &&
15093             ts.isBinaryExpression(node.expression) &&
15094             getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
15095             ts.isBinaryExpression(node.expression.right) &&
15096             (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
15097             ? node.expression.right.right
15098             : undefined;
15099     }
15100     function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
15101         switch (node.kind) {
15102             case 225 /* VariableStatement */:
15103                 var v = getSingleVariableOfVariableStatement(node);
15104                 return v && v.initializer;
15105             case 159 /* PropertyDeclaration */:
15106                 return node.initializer;
15107             case 281 /* PropertyAssignment */:
15108                 return node.initializer;
15109         }
15110     }
15111     ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
15112     function getSingleVariableOfVariableStatement(node) {
15113         return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
15114     }
15115     function getNestedModuleDeclaration(node) {
15116         return ts.isModuleDeclaration(node) &&
15117             node.body &&
15118             node.body.kind === 249 /* ModuleDeclaration */
15119             ? node.body
15120             : undefined;
15121     }
15122     function getJSDocCommentsAndTags(hostNode) {
15123         var result;
15124         // Pull parameter comments from declaring function as well
15125         if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
15126             result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
15127         }
15128         var node = hostNode;
15129         while (node && node.parent) {
15130             if (ts.hasJSDocNodes(node)) {
15131                 result = ts.append(result, ts.last(node.jsDoc));
15132             }
15133             if (node.kind === 156 /* Parameter */) {
15134                 result = ts.addRange(result, ts.getJSDocParameterTags(node));
15135                 break;
15136             }
15137             if (node.kind === 155 /* TypeParameter */) {
15138                 result = ts.addRange(result, ts.getJSDocTypeParameterTags(node));
15139                 break;
15140             }
15141             node = getNextJSDocCommentLocation(node);
15142         }
15143         return result || ts.emptyArray;
15144     }
15145     ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
15146     function getNextJSDocCommentLocation(node) {
15147         var parent = node.parent;
15148         if (parent.kind === 281 /* PropertyAssignment */ ||
15149             parent.kind === 259 /* ExportAssignment */ ||
15150             parent.kind === 159 /* PropertyDeclaration */ ||
15151             parent.kind === 226 /* ExpressionStatement */ && node.kind === 194 /* PropertyAccessExpression */ ||
15152             getNestedModuleDeclaration(parent) ||
15153             ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
15154             return parent;
15155         }
15156         // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
15157         // /**
15158         //   * @param {number} name
15159         //   * @returns {number}
15160         //   */
15161         // var x = function(name) { return name.length; }
15162         else if (parent.parent &&
15163             (getSingleVariableOfVariableStatement(parent.parent) === node ||
15164                 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
15165             return parent.parent;
15166         }
15167         else if (parent.parent && parent.parent.parent &&
15168             (getSingleVariableOfVariableStatement(parent.parent.parent) ||
15169                 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
15170                 getSourceOfDefaultedAssignment(parent.parent.parent))) {
15171             return parent.parent.parent;
15172         }
15173     }
15174     /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
15175     function getParameterSymbolFromJSDoc(node) {
15176         if (node.symbol) {
15177             return node.symbol;
15178         }
15179         if (!ts.isIdentifier(node.name)) {
15180             return undefined;
15181         }
15182         var name = node.name.escapedText;
15183         var decl = getHostSignatureFromJSDoc(node);
15184         if (!decl) {
15185             return undefined;
15186         }
15187         var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 75 /* Identifier */ && p.name.escapedText === name; });
15188         return parameter && parameter.symbol;
15189     }
15190     ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
15191     function getHostSignatureFromJSDoc(node) {
15192         var host = getEffectiveJSDocHost(node);
15193         return host && ts.isFunctionLike(host) ? host : undefined;
15194     }
15195     ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
15196     function getEffectiveJSDocHost(node) {
15197         var host = getJSDocHost(node);
15198         var decl = getSourceOfDefaultedAssignment(host) ||
15199             getSourceOfAssignment(host) ||
15200             getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
15201             getSingleVariableOfVariableStatement(host) ||
15202             getNestedModuleDeclaration(host) ||
15203             host;
15204         return decl;
15205     }
15206     ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
15207     /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments.  */
15208     function getJSDocHost(node) {
15209         return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent;
15210     }
15211     ts.getJSDocHost = getJSDocHost;
15212     function getTypeParameterFromJsDoc(node) {
15213         var name = node.name.escapedText;
15214         var typeParameters = node.parent.parent.parent.typeParameters;
15215         return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
15216     }
15217     ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
15218     function hasRestParameter(s) {
15219         var last = ts.lastOrUndefined(s.parameters);
15220         return !!last && isRestParameter(last);
15221     }
15222     ts.hasRestParameter = hasRestParameter;
15223     function isRestParameter(node) {
15224         var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
15225         return node.dotDotDotToken !== undefined || !!type && type.kind === 301 /* JSDocVariadicType */;
15226     }
15227     ts.isRestParameter = isRestParameter;
15228     function hasTypeArguments(node) {
15229         return !!node.typeArguments;
15230     }
15231     ts.hasTypeArguments = hasTypeArguments;
15232     var AssignmentKind;
15233     (function (AssignmentKind) {
15234         AssignmentKind[AssignmentKind["None"] = 0] = "None";
15235         AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
15236         AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
15237     })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
15238     function getAssignmentTargetKind(node) {
15239         var parent = node.parent;
15240         while (true) {
15241             switch (parent.kind) {
15242                 case 209 /* BinaryExpression */:
15243                     var binaryOperator = parent.operatorToken.kind;
15244                     return isAssignmentOperator(binaryOperator) && parent.left === node ?
15245                         binaryOperator === 62 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
15246                         0 /* None */;
15247                 case 207 /* PrefixUnaryExpression */:
15248                 case 208 /* PostfixUnaryExpression */:
15249                     var unaryOperator = parent.operator;
15250                     return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
15251                 case 231 /* ForInStatement */:
15252                 case 232 /* ForOfStatement */:
15253                     return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
15254                 case 200 /* ParenthesizedExpression */:
15255                 case 192 /* ArrayLiteralExpression */:
15256                 case 213 /* SpreadElement */:
15257                 case 218 /* NonNullExpression */:
15258                     node = parent;
15259                     break;
15260                 case 282 /* ShorthandPropertyAssignment */:
15261                     if (parent.name !== node) {
15262                         return 0 /* None */;
15263                     }
15264                     node = parent.parent;
15265                     break;
15266                 case 281 /* PropertyAssignment */:
15267                     if (parent.name === node) {
15268                         return 0 /* None */;
15269                     }
15270                     node = parent.parent;
15271                     break;
15272                 default:
15273                     return 0 /* None */;
15274             }
15275             parent = node.parent;
15276         }
15277     }
15278     ts.getAssignmentTargetKind = getAssignmentTargetKind;
15279     // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
15280     // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
15281     // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
15282     // (Note that `p` is not a target in the above examples, only `a`.)
15283     function isAssignmentTarget(node) {
15284         return getAssignmentTargetKind(node) !== 0 /* None */;
15285     }
15286     ts.isAssignmentTarget = isAssignmentTarget;
15287     /**
15288      * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
15289      * the same `var` declaration scope as the node's parent.
15290      */
15291     function isNodeWithPossibleHoistedDeclaration(node) {
15292         switch (node.kind) {
15293             case 223 /* Block */:
15294             case 225 /* VariableStatement */:
15295             case 236 /* WithStatement */:
15296             case 227 /* IfStatement */:
15297             case 237 /* SwitchStatement */:
15298             case 251 /* CaseBlock */:
15299             case 277 /* CaseClause */:
15300             case 278 /* DefaultClause */:
15301             case 238 /* LabeledStatement */:
15302             case 230 /* ForStatement */:
15303             case 231 /* ForInStatement */:
15304             case 232 /* ForOfStatement */:
15305             case 228 /* DoStatement */:
15306             case 229 /* WhileStatement */:
15307             case 240 /* TryStatement */:
15308             case 280 /* CatchClause */:
15309                 return true;
15310         }
15311         return false;
15312     }
15313     ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
15314     function isValueSignatureDeclaration(node) {
15315         return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
15316     }
15317     ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
15318     function walkUp(node, kind) {
15319         while (node && node.kind === kind) {
15320             node = node.parent;
15321         }
15322         return node;
15323     }
15324     function walkUpParenthesizedTypes(node) {
15325         return walkUp(node, 182 /* ParenthesizedType */);
15326     }
15327     ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
15328     function walkUpParenthesizedExpressions(node) {
15329         return walkUp(node, 200 /* ParenthesizedExpression */);
15330     }
15331     ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
15332     function skipParentheses(node) {
15333         return ts.skipOuterExpressions(node, 1 /* Parentheses */);
15334     }
15335     ts.skipParentheses = skipParentheses;
15336     function skipParenthesesUp(node) {
15337         while (node.kind === 200 /* ParenthesizedExpression */) {
15338             node = node.parent;
15339         }
15340         return node;
15341     }
15342     // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
15343     function isDeleteTarget(node) {
15344         if (node.kind !== 194 /* PropertyAccessExpression */ && node.kind !== 195 /* ElementAccessExpression */) {
15345             return false;
15346         }
15347         node = walkUpParenthesizedExpressions(node.parent);
15348         return node && node.kind === 203 /* DeleteExpression */;
15349     }
15350     ts.isDeleteTarget = isDeleteTarget;
15351     function isNodeDescendantOf(node, ancestor) {
15352         while (node) {
15353             if (node === ancestor)
15354                 return true;
15355             node = node.parent;
15356         }
15357         return false;
15358     }
15359     ts.isNodeDescendantOf = isNodeDescendantOf;
15360     // True if `name` is the name of a declaration node
15361     function isDeclarationName(name) {
15362         return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
15363     }
15364     ts.isDeclarationName = isDeclarationName;
15365     // See GH#16030
15366     function getDeclarationFromName(name) {
15367         var parent = name.parent;
15368         switch (name.kind) {
15369             case 10 /* StringLiteral */:
15370             case 14 /* NoSubstitutionTemplateLiteral */:
15371             case 8 /* NumericLiteral */:
15372                 if (ts.isComputedPropertyName(parent))
15373                     return parent.parent;
15374             // falls through
15375             case 75 /* Identifier */:
15376                 if (ts.isDeclaration(parent)) {
15377                     return parent.name === name ? parent : undefined;
15378                 }
15379                 else if (ts.isQualifiedName(parent)) {
15380                     var tag = parent.parent;
15381                     return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
15382                 }
15383                 else {
15384                     var binExp = parent.parent;
15385                     return ts.isBinaryExpression(binExp) &&
15386                         getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
15387                         (binExp.left.symbol || binExp.symbol) &&
15388                         ts.getNameOfDeclaration(binExp) === name
15389                         ? binExp
15390                         : undefined;
15391                 }
15392             case 76 /* PrivateIdentifier */:
15393                 return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
15394             default:
15395                 return undefined;
15396         }
15397     }
15398     ts.getDeclarationFromName = getDeclarationFromName;
15399     function isLiteralComputedPropertyDeclarationName(node) {
15400         return isStringOrNumericLiteralLike(node) &&
15401             node.parent.kind === 154 /* ComputedPropertyName */ &&
15402             ts.isDeclaration(node.parent.parent);
15403     }
15404     ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
15405     // Return true if the given identifier is classified as an IdentifierName
15406     function isIdentifierName(node) {
15407         var parent = node.parent;
15408         switch (parent.kind) {
15409             case 159 /* PropertyDeclaration */:
15410             case 158 /* PropertySignature */:
15411             case 161 /* MethodDeclaration */:
15412             case 160 /* MethodSignature */:
15413             case 163 /* GetAccessor */:
15414             case 164 /* SetAccessor */:
15415             case 284 /* EnumMember */:
15416             case 281 /* PropertyAssignment */:
15417             case 194 /* PropertyAccessExpression */:
15418                 // Name in member declaration or property name in property access
15419                 return parent.name === node;
15420             case 153 /* QualifiedName */:
15421                 // Name on right hand side of dot in a type query or type reference
15422                 if (parent.right === node) {
15423                     while (parent.kind === 153 /* QualifiedName */) {
15424                         parent = parent.parent;
15425                     }
15426                     return parent.kind === 172 /* TypeQuery */ || parent.kind === 169 /* TypeReference */;
15427                 }
15428                 return false;
15429             case 191 /* BindingElement */:
15430             case 258 /* ImportSpecifier */:
15431                 // Property name in binding element or import specifier
15432                 return parent.propertyName === node;
15433             case 263 /* ExportSpecifier */:
15434             case 273 /* JsxAttribute */:
15435                 // Any name in an export specifier or JSX Attribute
15436                 return true;
15437         }
15438         return false;
15439     }
15440     ts.isIdentifierName = isIdentifierName;
15441     // An alias symbol is created by one of the following declarations:
15442     // import <symbol> = ...
15443     // import <symbol> from ...
15444     // import * as <symbol> from ...
15445     // import { x as <symbol> } from ...
15446     // export { x as <symbol> } from ...
15447     // export * as ns <symbol> from ...
15448     // export = <EntityNameExpression>
15449     // export default <EntityNameExpression>
15450     // module.exports = <EntityNameExpression>
15451     // {<Identifier>}
15452     // {name: <EntityNameExpression>}
15453     function isAliasSymbolDeclaration(node) {
15454         return node.kind === 253 /* ImportEqualsDeclaration */ ||
15455             node.kind === 252 /* NamespaceExportDeclaration */ ||
15456             node.kind === 255 /* ImportClause */ && !!node.name ||
15457             node.kind === 256 /* NamespaceImport */ ||
15458             node.kind === 262 /* NamespaceExport */ ||
15459             node.kind === 258 /* ImportSpecifier */ ||
15460             node.kind === 263 /* ExportSpecifier */ ||
15461             node.kind === 259 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
15462             ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
15463             ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
15464             node.kind === 282 /* ShorthandPropertyAssignment */ ||
15465             node.kind === 281 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
15466     }
15467     ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
15468     function getAliasDeclarationFromName(node) {
15469         switch (node.parent.kind) {
15470             case 255 /* ImportClause */:
15471             case 258 /* ImportSpecifier */:
15472             case 256 /* NamespaceImport */:
15473             case 263 /* ExportSpecifier */:
15474             case 259 /* ExportAssignment */:
15475             case 253 /* ImportEqualsDeclaration */:
15476                 return node.parent;
15477             case 153 /* QualifiedName */:
15478                 do {
15479                     node = node.parent;
15480                 } while (node.parent.kind === 153 /* QualifiedName */);
15481                 return getAliasDeclarationFromName(node);
15482         }
15483     }
15484     ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
15485     function isAliasableExpression(e) {
15486         return isEntityNameExpression(e) || ts.isClassExpression(e);
15487     }
15488     ts.isAliasableExpression = isAliasableExpression;
15489     function exportAssignmentIsAlias(node) {
15490         var e = getExportAssignmentExpression(node);
15491         return isAliasableExpression(e);
15492     }
15493     ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
15494     function getExportAssignmentExpression(node) {
15495         return ts.isExportAssignment(node) ? node.expression : node.right;
15496     }
15497     ts.getExportAssignmentExpression = getExportAssignmentExpression;
15498     function getPropertyAssignmentAliasLikeExpression(node) {
15499         return node.kind === 282 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 281 /* PropertyAssignment */ ? node.initializer :
15500             node.parent.right;
15501     }
15502     ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
15503     function getEffectiveBaseTypeNode(node) {
15504         var baseType = getClassExtendsHeritageElement(node);
15505         if (baseType && isInJSFile(node)) {
15506             // Prefer an @augments tag because it may have type parameters.
15507             var tag = ts.getJSDocAugmentsTag(node);
15508             if (tag) {
15509                 return tag.class;
15510             }
15511         }
15512         return baseType;
15513     }
15514     ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
15515     function getClassExtendsHeritageElement(node) {
15516         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15517         return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
15518     }
15519     ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
15520     function getEffectiveImplementsTypeNodes(node) {
15521         if (isInJSFile(node)) {
15522             return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
15523         }
15524         else {
15525             var heritageClause = getHeritageClause(node.heritageClauses, 113 /* ImplementsKeyword */);
15526             return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
15527         }
15528     }
15529     ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
15530     /** Returns the node in an `extends` or `implements` clause of a class or interface. */
15531     function getAllSuperTypeNodes(node) {
15532         return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
15533             ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
15534                 ts.emptyArray;
15535     }
15536     ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
15537     function getInterfaceBaseTypeNodes(node) {
15538         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15539         return heritageClause ? heritageClause.types : undefined;
15540     }
15541     ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
15542     function getHeritageClause(clauses, kind) {
15543         if (clauses) {
15544             for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
15545                 var clause = clauses_1[_i];
15546                 if (clause.token === kind) {
15547                     return clause;
15548                 }
15549             }
15550         }
15551         return undefined;
15552     }
15553     ts.getHeritageClause = getHeritageClause;
15554     function getAncestor(node, kind) {
15555         while (node) {
15556             if (node.kind === kind) {
15557                 return node;
15558             }
15559             node = node.parent;
15560         }
15561         return undefined;
15562     }
15563     ts.getAncestor = getAncestor;
15564     function isKeyword(token) {
15565         return 77 /* FirstKeyword */ <= token && token <= 152 /* LastKeyword */;
15566     }
15567     ts.isKeyword = isKeyword;
15568     function isContextualKeyword(token) {
15569         return 122 /* FirstContextualKeyword */ <= token && token <= 152 /* LastContextualKeyword */;
15570     }
15571     ts.isContextualKeyword = isContextualKeyword;
15572     function isNonContextualKeyword(token) {
15573         return isKeyword(token) && !isContextualKeyword(token);
15574     }
15575     ts.isNonContextualKeyword = isNonContextualKeyword;
15576     function isFutureReservedKeyword(token) {
15577         return 113 /* FirstFutureReservedWord */ <= token && token <= 121 /* LastFutureReservedWord */;
15578     }
15579     ts.isFutureReservedKeyword = isFutureReservedKeyword;
15580     function isStringANonContextualKeyword(name) {
15581         var token = ts.stringToToken(name);
15582         return token !== undefined && isNonContextualKeyword(token);
15583     }
15584     ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
15585     function isStringAKeyword(name) {
15586         var token = ts.stringToToken(name);
15587         return token !== undefined && isKeyword(token);
15588     }
15589     ts.isStringAKeyword = isStringAKeyword;
15590     function isIdentifierANonContextualKeyword(_a) {
15591         var originalKeywordKind = _a.originalKeywordKind;
15592         return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
15593     }
15594     ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
15595     function isTrivia(token) {
15596         return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
15597     }
15598     ts.isTrivia = isTrivia;
15599     var FunctionFlags;
15600     (function (FunctionFlags) {
15601         FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
15602         FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
15603         FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
15604         FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
15605         FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
15606     })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
15607     function getFunctionFlags(node) {
15608         if (!node) {
15609             return 4 /* Invalid */;
15610         }
15611         var flags = 0 /* Normal */;
15612         switch (node.kind) {
15613             case 244 /* FunctionDeclaration */:
15614             case 201 /* FunctionExpression */:
15615             case 161 /* MethodDeclaration */:
15616                 if (node.asteriskToken) {
15617                     flags |= 1 /* Generator */;
15618                 }
15619             // falls through
15620             case 202 /* ArrowFunction */:
15621                 if (hasModifier(node, 256 /* Async */)) {
15622                     flags |= 2 /* Async */;
15623                 }
15624                 break;
15625         }
15626         if (!node.body) {
15627             flags |= 4 /* Invalid */;
15628         }
15629         return flags;
15630     }
15631     ts.getFunctionFlags = getFunctionFlags;
15632     function isAsyncFunction(node) {
15633         switch (node.kind) {
15634             case 244 /* FunctionDeclaration */:
15635             case 201 /* FunctionExpression */:
15636             case 202 /* ArrowFunction */:
15637             case 161 /* MethodDeclaration */:
15638                 return node.body !== undefined
15639                     && node.asteriskToken === undefined
15640                     && hasModifier(node, 256 /* Async */);
15641         }
15642         return false;
15643     }
15644     ts.isAsyncFunction = isAsyncFunction;
15645     function isStringOrNumericLiteralLike(node) {
15646         return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
15647     }
15648     ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
15649     function isSignedNumericLiteral(node) {
15650         return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
15651     }
15652     ts.isSignedNumericLiteral = isSignedNumericLiteral;
15653     /**
15654      * A declaration has a dynamic name if all of the following are true:
15655      *   1. The declaration has a computed property name.
15656      *   2. The computed name is *not* expressed as a StringLiteral.
15657      *   3. The computed name is *not* expressed as a NumericLiteral.
15658      *   4. The computed name is *not* expressed as a PlusToken or MinusToken
15659      *      immediately followed by a NumericLiteral.
15660      *   5. The computed name is *not* expressed as `Symbol.<name>`, where `<name>`
15661      *      is a property of the Symbol constructor that denotes a built-in
15662      *      Symbol.
15663      */
15664     function hasDynamicName(declaration) {
15665         var name = ts.getNameOfDeclaration(declaration);
15666         return !!name && isDynamicName(name);
15667     }
15668     ts.hasDynamicName = hasDynamicName;
15669     function isDynamicName(name) {
15670         if (!(name.kind === 154 /* ComputedPropertyName */ || name.kind === 195 /* ElementAccessExpression */)) {
15671             return false;
15672         }
15673         var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression;
15674         return !isStringOrNumericLiteralLike(expr) &&
15675             !isSignedNumericLiteral(expr) &&
15676             !isWellKnownSymbolSyntactically(expr);
15677     }
15678     ts.isDynamicName = isDynamicName;
15679     /**
15680      * Checks if the expression is of the form:
15681      *    Symbol.name
15682      * where Symbol is literally the word "Symbol", and name is any identifierName
15683      */
15684     function isWellKnownSymbolSyntactically(node) {
15685         return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
15686     }
15687     ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
15688     function getPropertyNameForPropertyNameNode(name) {
15689         switch (name.kind) {
15690             case 75 /* Identifier */:
15691             case 76 /* PrivateIdentifier */:
15692                 return name.escapedText;
15693             case 10 /* StringLiteral */:
15694             case 8 /* NumericLiteral */:
15695                 return ts.escapeLeadingUnderscores(name.text);
15696             case 154 /* ComputedPropertyName */:
15697                 var nameExpression = name.expression;
15698                 if (isWellKnownSymbolSyntactically(nameExpression)) {
15699                     return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
15700                 }
15701                 else if (isStringOrNumericLiteralLike(nameExpression)) {
15702                     return ts.escapeLeadingUnderscores(nameExpression.text);
15703                 }
15704                 return undefined;
15705             default:
15706                 return ts.Debug.assertNever(name);
15707         }
15708     }
15709     ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
15710     function isPropertyNameLiteral(node) {
15711         switch (node.kind) {
15712             case 75 /* Identifier */:
15713             case 10 /* StringLiteral */:
15714             case 14 /* NoSubstitutionTemplateLiteral */:
15715             case 8 /* NumericLiteral */:
15716                 return true;
15717             default:
15718                 return false;
15719         }
15720     }
15721     ts.isPropertyNameLiteral = isPropertyNameLiteral;
15722     function getTextOfIdentifierOrLiteral(node) {
15723         return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
15724     }
15725     ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
15726     function getEscapedTextOfIdentifierOrLiteral(node) {
15727         return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
15728     }
15729     ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
15730     function getPropertyNameForUniqueESSymbol(symbol) {
15731         return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
15732     }
15733     ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
15734     function getPropertyNameForKnownSymbolName(symbolName) {
15735         return "__@" + symbolName;
15736     }
15737     ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
15738     function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
15739         return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
15740     }
15741     ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
15742     function isKnownSymbol(symbol) {
15743         return ts.startsWith(symbol.escapedName, "__@");
15744     }
15745     ts.isKnownSymbol = isKnownSymbol;
15746     /**
15747      * Includes the word "Symbol" with unicode escapes
15748      */
15749     function isESSymbolIdentifier(node) {
15750         return node.kind === 75 /* Identifier */ && node.escapedText === "Symbol";
15751     }
15752     ts.isESSymbolIdentifier = isESSymbolIdentifier;
15753     function isPushOrUnshiftIdentifier(node) {
15754         return node.escapedText === "push" || node.escapedText === "unshift";
15755     }
15756     ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
15757     function isParameterDeclaration(node) {
15758         var root = getRootDeclaration(node);
15759         return root.kind === 156 /* Parameter */;
15760     }
15761     ts.isParameterDeclaration = isParameterDeclaration;
15762     function getRootDeclaration(node) {
15763         while (node.kind === 191 /* BindingElement */) {
15764             node = node.parent.parent;
15765         }
15766         return node;
15767     }
15768     ts.getRootDeclaration = getRootDeclaration;
15769     function nodeStartsNewLexicalEnvironment(node) {
15770         var kind = node.kind;
15771         return kind === 162 /* Constructor */
15772             || kind === 201 /* FunctionExpression */
15773             || kind === 244 /* FunctionDeclaration */
15774             || kind === 202 /* ArrowFunction */
15775             || kind === 161 /* MethodDeclaration */
15776             || kind === 163 /* GetAccessor */
15777             || kind === 164 /* SetAccessor */
15778             || kind === 249 /* ModuleDeclaration */
15779             || kind === 290 /* SourceFile */;
15780     }
15781     ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
15782     function nodeIsSynthesized(range) {
15783         return positionIsSynthesized(range.pos)
15784             || positionIsSynthesized(range.end);
15785     }
15786     ts.nodeIsSynthesized = nodeIsSynthesized;
15787     function getOriginalSourceFile(sourceFile) {
15788         return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
15789     }
15790     ts.getOriginalSourceFile = getOriginalSourceFile;
15791     var Associativity;
15792     (function (Associativity) {
15793         Associativity[Associativity["Left"] = 0] = "Left";
15794         Associativity[Associativity["Right"] = 1] = "Right";
15795     })(Associativity = ts.Associativity || (ts.Associativity = {}));
15796     function getExpressionAssociativity(expression) {
15797         var operator = getOperator(expression);
15798         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15799         return getOperatorAssociativity(expression.kind, operator, hasArguments);
15800     }
15801     ts.getExpressionAssociativity = getExpressionAssociativity;
15802     function getOperatorAssociativity(kind, operator, hasArguments) {
15803         switch (kind) {
15804             case 197 /* NewExpression */:
15805                 return hasArguments ? 0 /* Left */ : 1 /* Right */;
15806             case 207 /* PrefixUnaryExpression */:
15807             case 204 /* TypeOfExpression */:
15808             case 205 /* VoidExpression */:
15809             case 203 /* DeleteExpression */:
15810             case 206 /* AwaitExpression */:
15811             case 210 /* ConditionalExpression */:
15812             case 212 /* YieldExpression */:
15813                 return 1 /* Right */;
15814             case 209 /* BinaryExpression */:
15815                 switch (operator) {
15816                     case 42 /* AsteriskAsteriskToken */:
15817                     case 62 /* EqualsToken */:
15818                     case 63 /* PlusEqualsToken */:
15819                     case 64 /* MinusEqualsToken */:
15820                     case 66 /* AsteriskAsteriskEqualsToken */:
15821                     case 65 /* AsteriskEqualsToken */:
15822                     case 67 /* SlashEqualsToken */:
15823                     case 68 /* PercentEqualsToken */:
15824                     case 69 /* LessThanLessThanEqualsToken */:
15825                     case 70 /* GreaterThanGreaterThanEqualsToken */:
15826                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15827                     case 72 /* AmpersandEqualsToken */:
15828                     case 74 /* CaretEqualsToken */:
15829                     case 73 /* BarEqualsToken */:
15830                         return 1 /* Right */;
15831                 }
15832         }
15833         return 0 /* Left */;
15834     }
15835     ts.getOperatorAssociativity = getOperatorAssociativity;
15836     function getExpressionPrecedence(expression) {
15837         var operator = getOperator(expression);
15838         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15839         return getOperatorPrecedence(expression.kind, operator, hasArguments);
15840     }
15841     ts.getExpressionPrecedence = getExpressionPrecedence;
15842     function getOperator(expression) {
15843         if (expression.kind === 209 /* BinaryExpression */) {
15844             return expression.operatorToken.kind;
15845         }
15846         else if (expression.kind === 207 /* PrefixUnaryExpression */ || expression.kind === 208 /* PostfixUnaryExpression */) {
15847             return expression.operator;
15848         }
15849         else {
15850             return expression.kind;
15851         }
15852     }
15853     ts.getOperator = getOperator;
15854     function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
15855         switch (nodeKind) {
15856             case 327 /* CommaListExpression */:
15857                 return 0;
15858             case 213 /* SpreadElement */:
15859                 return 1;
15860             case 212 /* YieldExpression */:
15861                 return 2;
15862             case 210 /* ConditionalExpression */:
15863                 return 4;
15864             case 209 /* BinaryExpression */:
15865                 switch (operatorKind) {
15866                     case 27 /* CommaToken */:
15867                         return 0;
15868                     case 62 /* EqualsToken */:
15869                     case 63 /* PlusEqualsToken */:
15870                     case 64 /* MinusEqualsToken */:
15871                     case 66 /* AsteriskAsteriskEqualsToken */:
15872                     case 65 /* AsteriskEqualsToken */:
15873                     case 67 /* SlashEqualsToken */:
15874                     case 68 /* PercentEqualsToken */:
15875                     case 69 /* LessThanLessThanEqualsToken */:
15876                     case 70 /* GreaterThanGreaterThanEqualsToken */:
15877                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15878                     case 72 /* AmpersandEqualsToken */:
15879                     case 74 /* CaretEqualsToken */:
15880                     case 73 /* BarEqualsToken */:
15881                         return 3;
15882                     default:
15883                         return getBinaryOperatorPrecedence(operatorKind);
15884                 }
15885             case 207 /* PrefixUnaryExpression */:
15886             case 204 /* TypeOfExpression */:
15887             case 205 /* VoidExpression */:
15888             case 203 /* DeleteExpression */:
15889             case 206 /* AwaitExpression */:
15890                 return 16;
15891             case 208 /* PostfixUnaryExpression */:
15892                 return 17;
15893             case 196 /* CallExpression */:
15894                 return 18;
15895             case 197 /* NewExpression */:
15896                 return hasArguments ? 19 : 18;
15897             case 198 /* TaggedTemplateExpression */:
15898             case 194 /* PropertyAccessExpression */:
15899             case 195 /* ElementAccessExpression */:
15900                 return 19;
15901             case 104 /* ThisKeyword */:
15902             case 102 /* SuperKeyword */:
15903             case 75 /* Identifier */:
15904             case 100 /* NullKeyword */:
15905             case 106 /* TrueKeyword */:
15906             case 91 /* FalseKeyword */:
15907             case 8 /* NumericLiteral */:
15908             case 9 /* BigIntLiteral */:
15909             case 10 /* StringLiteral */:
15910             case 192 /* ArrayLiteralExpression */:
15911             case 193 /* ObjectLiteralExpression */:
15912             case 201 /* FunctionExpression */:
15913             case 202 /* ArrowFunction */:
15914             case 214 /* ClassExpression */:
15915             case 266 /* JsxElement */:
15916             case 267 /* JsxSelfClosingElement */:
15917             case 270 /* JsxFragment */:
15918             case 13 /* RegularExpressionLiteral */:
15919             case 14 /* NoSubstitutionTemplateLiteral */:
15920             case 211 /* TemplateExpression */:
15921             case 200 /* ParenthesizedExpression */:
15922             case 215 /* OmittedExpression */:
15923                 return 20;
15924             default:
15925                 return -1;
15926         }
15927     }
15928     ts.getOperatorPrecedence = getOperatorPrecedence;
15929     function getBinaryOperatorPrecedence(kind) {
15930         switch (kind) {
15931             case 60 /* QuestionQuestionToken */:
15932                 return 4;
15933             case 56 /* BarBarToken */:
15934                 return 5;
15935             case 55 /* AmpersandAmpersandToken */:
15936                 return 6;
15937             case 51 /* BarToken */:
15938                 return 7;
15939             case 52 /* CaretToken */:
15940                 return 8;
15941             case 50 /* AmpersandToken */:
15942                 return 9;
15943             case 34 /* EqualsEqualsToken */:
15944             case 35 /* ExclamationEqualsToken */:
15945             case 36 /* EqualsEqualsEqualsToken */:
15946             case 37 /* ExclamationEqualsEqualsToken */:
15947                 return 10;
15948             case 29 /* LessThanToken */:
15949             case 31 /* GreaterThanToken */:
15950             case 32 /* LessThanEqualsToken */:
15951             case 33 /* GreaterThanEqualsToken */:
15952             case 98 /* InstanceOfKeyword */:
15953             case 97 /* InKeyword */:
15954             case 123 /* AsKeyword */:
15955                 return 11;
15956             case 47 /* LessThanLessThanToken */:
15957             case 48 /* GreaterThanGreaterThanToken */:
15958             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
15959                 return 12;
15960             case 39 /* PlusToken */:
15961             case 40 /* MinusToken */:
15962                 return 13;
15963             case 41 /* AsteriskToken */:
15964             case 43 /* SlashToken */:
15965             case 44 /* PercentToken */:
15966                 return 14;
15967             case 42 /* AsteriskAsteriskToken */:
15968                 return 15;
15969         }
15970         // -1 is lower than all other precedences.  Returning it will cause binary expression
15971         // parsing to stop.
15972         return -1;
15973     }
15974     ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
15975     function createDiagnosticCollection() {
15976         var nonFileDiagnostics = []; // See GH#19873
15977         var filesWithDiagnostics = [];
15978         var fileDiagnostics = ts.createMap();
15979         var hasReadNonFileDiagnostics = false;
15980         return {
15981             add: add,
15982             lookup: lookup,
15983             getGlobalDiagnostics: getGlobalDiagnostics,
15984             getDiagnostics: getDiagnostics,
15985             reattachFileDiagnostics: reattachFileDiagnostics
15986         };
15987         function reattachFileDiagnostics(newFile) {
15988             ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
15989         }
15990         function lookup(diagnostic) {
15991             var diagnostics;
15992             if (diagnostic.file) {
15993                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
15994             }
15995             else {
15996                 diagnostics = nonFileDiagnostics;
15997             }
15998             if (!diagnostics) {
15999                 return undefined;
16000             }
16001             var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
16002             if (result >= 0) {
16003                 return diagnostics[result];
16004             }
16005             return undefined;
16006         }
16007         function add(diagnostic) {
16008             var diagnostics;
16009             if (diagnostic.file) {
16010                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16011                 if (!diagnostics) {
16012                     diagnostics = []; // See GH#19873
16013                     fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
16014                     ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
16015                 }
16016             }
16017             else {
16018                 // If we've already read the non-file diagnostics, do not modify the existing array.
16019                 if (hasReadNonFileDiagnostics) {
16020                     hasReadNonFileDiagnostics = false;
16021                     nonFileDiagnostics = nonFileDiagnostics.slice();
16022                 }
16023                 diagnostics = nonFileDiagnostics;
16024             }
16025             ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
16026         }
16027         function getGlobalDiagnostics() {
16028             hasReadNonFileDiagnostics = true;
16029             return nonFileDiagnostics;
16030         }
16031         function getDiagnostics(fileName) {
16032             if (fileName) {
16033                 return fileDiagnostics.get(fileName) || [];
16034             }
16035             var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
16036             if (!nonFileDiagnostics.length) {
16037                 return fileDiags;
16038             }
16039             fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
16040             return fileDiags;
16041         }
16042     }
16043     ts.createDiagnosticCollection = createDiagnosticCollection;
16044     var templateSubstitutionRegExp = /\$\{/g;
16045     function escapeTemplateSubstitution(str) {
16046         return str.replace(templateSubstitutionRegExp, "\\${");
16047     }
16048     /** @internal */
16049     function hasInvalidEscape(template) {
16050         return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
16051             ? template.templateFlags
16052             : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
16053     }
16054     ts.hasInvalidEscape = hasInvalidEscape;
16055     // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
16056     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16057     // the language service. These characters should be escaped when printing, and if any characters are added,
16058     // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
16059     // There is no reason for this other than that JSON.stringify does not handle it either.
16060     var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16061     var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16062     // Template strings should be preserved as much as possible
16063     var backtickQuoteEscapedCharsRegExp = /[\\`]/g;
16064     var escapedCharsMap = ts.createMapFromTemplate({
16065         "\t": "\\t",
16066         "\v": "\\v",
16067         "\f": "\\f",
16068         "\b": "\\b",
16069         "\r": "\\r",
16070         "\n": "\\n",
16071         "\\": "\\\\",
16072         "\"": "\\\"",
16073         "\'": "\\\'",
16074         "\`": "\\\`",
16075         "\u2028": "\\u2028",
16076         "\u2029": "\\u2029",
16077         "\u0085": "\\u0085" // nextLine
16078     });
16079     function encodeUtf16EscapeSequence(charCode) {
16080         var hexCharCode = charCode.toString(16).toUpperCase();
16081         var paddedHexCode = ("0000" + hexCharCode).slice(-4);
16082         return "\\u" + paddedHexCode;
16083     }
16084     function getReplacement(c, offset, input) {
16085         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16086             var lookAhead = input.charCodeAt(offset + c.length);
16087             if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
16088                 // 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)
16089                 return "\\x00";
16090             }
16091             // Otherwise, keep printing a literal \0 for the null character
16092             return "\\0";
16093         }
16094         return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
16095     }
16096     /**
16097      * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
16098      * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
16099      * Note that this doesn't actually wrap the input in double quotes.
16100      */
16101     function escapeString(s, quoteChar) {
16102         var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
16103             quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
16104                 doubleQuoteEscapedCharsRegExp;
16105         return s.replace(escapedCharsRegExp, getReplacement);
16106     }
16107     ts.escapeString = escapeString;
16108     var nonAsciiCharacters = /[^\u0000-\u007F]/g;
16109     function escapeNonAsciiString(s, quoteChar) {
16110         s = escapeString(s, quoteChar);
16111         // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
16112         // Otherwise just return the original string.
16113         return nonAsciiCharacters.test(s) ?
16114             s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
16115             s;
16116     }
16117     ts.escapeNonAsciiString = escapeNonAsciiString;
16118     // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
16119     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16120     // the language service. These characters should be escaped when printing, and if any characters are added,
16121     // the map below must be updated.
16122     var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
16123     var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
16124     var jsxEscapedCharsMap = ts.createMapFromTemplate({
16125         "\"": "&quot;",
16126         "\'": "&apos;"
16127     });
16128     function encodeJsxCharacterEntity(charCode) {
16129         var hexCharCode = charCode.toString(16).toUpperCase();
16130         return "&#x" + hexCharCode + ";";
16131     }
16132     function getJsxAttributeStringReplacement(c) {
16133         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16134             return "&#0;";
16135         }
16136         return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
16137     }
16138     function escapeJsxAttributeString(s, quoteChar) {
16139         var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
16140             jsxDoubleQuoteEscapedCharsRegExp;
16141         return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
16142     }
16143     ts.escapeJsxAttributeString = escapeJsxAttributeString;
16144     /**
16145      * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
16146      *
16147      * @return non-quoted string
16148      */
16149     function stripQuotes(name) {
16150         var length = name.length;
16151         if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
16152             return name.substring(1, length - 1);
16153         }
16154         return name;
16155     }
16156     ts.stripQuotes = stripQuotes;
16157     function isQuoteOrBacktick(charCode) {
16158         return charCode === 39 /* singleQuote */ ||
16159             charCode === 34 /* doubleQuote */ ||
16160             charCode === 96 /* backtick */;
16161     }
16162     function isIntrinsicJsxName(name) {
16163         var ch = name.charCodeAt(0);
16164         return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
16165     }
16166     ts.isIntrinsicJsxName = isIntrinsicJsxName;
16167     var indentStrings = ["", "    "];
16168     function getIndentString(level) {
16169         if (indentStrings[level] === undefined) {
16170             indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
16171         }
16172         return indentStrings[level];
16173     }
16174     ts.getIndentString = getIndentString;
16175     function getIndentSize() {
16176         return indentStrings[1].length;
16177     }
16178     ts.getIndentSize = getIndentSize;
16179     function createTextWriter(newLine) {
16180         var output;
16181         var indent;
16182         var lineStart;
16183         var lineCount;
16184         var linePos;
16185         var hasTrailingComment = false;
16186         function updateLineCountAndPosFor(s) {
16187             var lineStartsOfS = ts.computeLineStarts(s);
16188             if (lineStartsOfS.length > 1) {
16189                 lineCount = lineCount + lineStartsOfS.length - 1;
16190                 linePos = output.length - s.length + ts.last(lineStartsOfS);
16191                 lineStart = (linePos - output.length) === 0;
16192             }
16193             else {
16194                 lineStart = false;
16195             }
16196         }
16197         function writeText(s) {
16198             if (s && s.length) {
16199                 if (lineStart) {
16200                     s = getIndentString(indent) + s;
16201                     lineStart = false;
16202                 }
16203                 output += s;
16204                 updateLineCountAndPosFor(s);
16205             }
16206         }
16207         function write(s) {
16208             if (s)
16209                 hasTrailingComment = false;
16210             writeText(s);
16211         }
16212         function writeComment(s) {
16213             if (s)
16214                 hasTrailingComment = true;
16215             writeText(s);
16216         }
16217         function reset() {
16218             output = "";
16219             indent = 0;
16220             lineStart = true;
16221             lineCount = 0;
16222             linePos = 0;
16223             hasTrailingComment = false;
16224         }
16225         function rawWrite(s) {
16226             if (s !== undefined) {
16227                 output += s;
16228                 updateLineCountAndPosFor(s);
16229                 hasTrailingComment = false;
16230             }
16231         }
16232         function writeLiteral(s) {
16233             if (s && s.length) {
16234                 write(s);
16235             }
16236         }
16237         function writeLine(force) {
16238             if (!lineStart || force) {
16239                 output += newLine;
16240                 lineCount++;
16241                 linePos = output.length;
16242                 lineStart = true;
16243                 hasTrailingComment = false;
16244             }
16245         }
16246         function getTextPosWithWriteLine() {
16247             return lineStart ? output.length : (output.length + newLine.length);
16248         }
16249         reset();
16250         return {
16251             write: write,
16252             rawWrite: rawWrite,
16253             writeLiteral: writeLiteral,
16254             writeLine: writeLine,
16255             increaseIndent: function () { indent++; },
16256             decreaseIndent: function () { indent--; },
16257             getIndent: function () { return indent; },
16258             getTextPos: function () { return output.length; },
16259             getLine: function () { return lineCount; },
16260             getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
16261             getText: function () { return output; },
16262             isAtStartOfLine: function () { return lineStart; },
16263             hasTrailingComment: function () { return hasTrailingComment; },
16264             hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
16265             clear: reset,
16266             reportInaccessibleThisError: ts.noop,
16267             reportPrivateInBaseOfClassExpression: ts.noop,
16268             reportInaccessibleUniqueSymbolError: ts.noop,
16269             trackSymbol: ts.noop,
16270             writeKeyword: write,
16271             writeOperator: write,
16272             writeParameter: write,
16273             writeProperty: write,
16274             writePunctuation: write,
16275             writeSpace: write,
16276             writeStringLiteral: write,
16277             writeSymbol: function (s, _) { return write(s); },
16278             writeTrailingSemicolon: write,
16279             writeComment: writeComment,
16280             getTextPosWithWriteLine: getTextPosWithWriteLine
16281         };
16282     }
16283     ts.createTextWriter = createTextWriter;
16284     function getTrailingSemicolonDeferringWriter(writer) {
16285         var pendingTrailingSemicolon = false;
16286         function commitPendingTrailingSemicolon() {
16287             if (pendingTrailingSemicolon) {
16288                 writer.writeTrailingSemicolon(";");
16289                 pendingTrailingSemicolon = false;
16290             }
16291         }
16292         return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
16293                 pendingTrailingSemicolon = true;
16294             },
16295             writeLiteral: function (s) {
16296                 commitPendingTrailingSemicolon();
16297                 writer.writeLiteral(s);
16298             },
16299             writeStringLiteral: function (s) {
16300                 commitPendingTrailingSemicolon();
16301                 writer.writeStringLiteral(s);
16302             },
16303             writeSymbol: function (s, sym) {
16304                 commitPendingTrailingSemicolon();
16305                 writer.writeSymbol(s, sym);
16306             },
16307             writePunctuation: function (s) {
16308                 commitPendingTrailingSemicolon();
16309                 writer.writePunctuation(s);
16310             },
16311             writeKeyword: function (s) {
16312                 commitPendingTrailingSemicolon();
16313                 writer.writeKeyword(s);
16314             },
16315             writeOperator: function (s) {
16316                 commitPendingTrailingSemicolon();
16317                 writer.writeOperator(s);
16318             },
16319             writeParameter: function (s) {
16320                 commitPendingTrailingSemicolon();
16321                 writer.writeParameter(s);
16322             },
16323             writeSpace: function (s) {
16324                 commitPendingTrailingSemicolon();
16325                 writer.writeSpace(s);
16326             },
16327             writeProperty: function (s) {
16328                 commitPendingTrailingSemicolon();
16329                 writer.writeProperty(s);
16330             },
16331             writeComment: function (s) {
16332                 commitPendingTrailingSemicolon();
16333                 writer.writeComment(s);
16334             },
16335             writeLine: function () {
16336                 commitPendingTrailingSemicolon();
16337                 writer.writeLine();
16338             },
16339             increaseIndent: function () {
16340                 commitPendingTrailingSemicolon();
16341                 writer.increaseIndent();
16342             },
16343             decreaseIndent: function () {
16344                 commitPendingTrailingSemicolon();
16345                 writer.decreaseIndent();
16346             } });
16347     }
16348     ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
16349     function hostUsesCaseSensitiveFileNames(host) {
16350         return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
16351     }
16352     ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
16353     function hostGetCanonicalFileName(host) {
16354         return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
16355     }
16356     ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
16357     function getResolvedExternalModuleName(host, file, referenceFile) {
16358         return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
16359     }
16360     ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
16361     function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
16362         var file = resolver.getExternalModuleFileFromDeclaration(declaration);
16363         if (!file || file.isDeclarationFile) {
16364             return undefined;
16365         }
16366         return getResolvedExternalModuleName(host, file);
16367     }
16368     ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
16369     /**
16370      * Resolves a local path to a path which is absolute to the base of the emit
16371      */
16372     function getExternalModuleNameFromPath(host, fileName, referencePath) {
16373         var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
16374         var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
16375         var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
16376         var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
16377         var extensionless = removeFileExtension(relativePath);
16378         return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
16379     }
16380     ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
16381     function getOwnEmitOutputFilePath(fileName, host, extension) {
16382         var compilerOptions = host.getCompilerOptions();
16383         var emitOutputFilePathWithoutExtension;
16384         if (compilerOptions.outDir) {
16385             emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
16386         }
16387         else {
16388             emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
16389         }
16390         return emitOutputFilePathWithoutExtension + extension;
16391     }
16392     ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
16393     function getDeclarationEmitOutputFilePath(fileName, host) {
16394         return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16395     }
16396     ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
16397     function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16398         var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
16399         var path = outputDir
16400             ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
16401             : fileName;
16402         return removeFileExtension(path) + ".d.ts" /* Dts */;
16403     }
16404     ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
16405     /**
16406      * Gets the source files that are expected to have an emit output.
16407      *
16408      * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
16409      * transformations.
16410      *
16411      * @param host An EmitHost.
16412      * @param targetSourceFile An optional target source file to emit.
16413      */
16414     function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
16415         var options = host.getCompilerOptions();
16416         if (options.outFile || options.out) {
16417             var moduleKind = getEmitModuleKind(options);
16418             var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
16419             // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
16420             return ts.filter(host.getSourceFiles(), function (sourceFile) {
16421                 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
16422                     sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
16423             });
16424         }
16425         else {
16426             var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
16427             return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
16428         }
16429     }
16430     ts.getSourceFilesToEmit = getSourceFilesToEmit;
16431     /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
16432     function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
16433         var options = host.getCompilerOptions();
16434         return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
16435             !sourceFile.isDeclarationFile &&
16436             !host.isSourceFileFromExternalLibrary(sourceFile) &&
16437             !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
16438             (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
16439     }
16440     ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
16441     function getSourceFilePathInNewDir(fileName, host, newDirPath) {
16442         return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16443     }
16444     ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
16445     function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16446         var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
16447         var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
16448         sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
16449         return ts.combinePaths(newDirPath, sourceFilePath);
16450     }
16451     ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
16452     function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
16453         host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
16454             diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
16455         }, sourceFiles);
16456     }
16457     ts.writeFile = writeFile;
16458     function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
16459         if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
16460             var parentDirectory = ts.getDirectoryPath(directoryPath);
16461             ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
16462             createDirectory(directoryPath);
16463         }
16464     }
16465     function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
16466         // PERF: Checking for directory existence is expensive.  Instead, assume the directory exists
16467         // and fall back to creating it if the file write fails.
16468         try {
16469             writeFile(path, data, writeByteOrderMark);
16470         }
16471         catch (_a) {
16472             ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
16473             writeFile(path, data, writeByteOrderMark);
16474         }
16475     }
16476     ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
16477     function getLineOfLocalPosition(sourceFile, pos) {
16478         var lineStarts = ts.getLineStarts(sourceFile);
16479         return ts.computeLineOfPosition(lineStarts, pos);
16480     }
16481     ts.getLineOfLocalPosition = getLineOfLocalPosition;
16482     function getLineOfLocalPositionFromLineMap(lineMap, pos) {
16483         return ts.computeLineOfPosition(lineMap, pos);
16484     }
16485     ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
16486     function getFirstConstructorWithBody(node) {
16487         return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
16488     }
16489     ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
16490     function getSetAccessorValueParameter(accessor) {
16491         if (accessor && accessor.parameters.length > 0) {
16492             var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
16493             return accessor.parameters[hasThis ? 1 : 0];
16494         }
16495     }
16496     ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
16497     /** Get the type annotation for the value parameter. */
16498     function getSetAccessorTypeAnnotationNode(accessor) {
16499         var parameter = getSetAccessorValueParameter(accessor);
16500         return parameter && parameter.type;
16501     }
16502     ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
16503     function getThisParameter(signature) {
16504         // callback tags do not currently support this parameters
16505         if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
16506             var thisParameter = signature.parameters[0];
16507             if (parameterIsThisKeyword(thisParameter)) {
16508                 return thisParameter;
16509             }
16510         }
16511     }
16512     ts.getThisParameter = getThisParameter;
16513     function parameterIsThisKeyword(parameter) {
16514         return isThisIdentifier(parameter.name);
16515     }
16516     ts.parameterIsThisKeyword = parameterIsThisKeyword;
16517     function isThisIdentifier(node) {
16518         return !!node && node.kind === 75 /* Identifier */ && identifierIsThisKeyword(node);
16519     }
16520     ts.isThisIdentifier = isThisIdentifier;
16521     function identifierIsThisKeyword(id) {
16522         return id.originalKeywordKind === 104 /* ThisKeyword */;
16523     }
16524     ts.identifierIsThisKeyword = identifierIsThisKeyword;
16525     function getAllAccessorDeclarations(declarations, accessor) {
16526         // TODO: GH#18217
16527         var firstAccessor;
16528         var secondAccessor;
16529         var getAccessor;
16530         var setAccessor;
16531         if (hasDynamicName(accessor)) {
16532             firstAccessor = accessor;
16533             if (accessor.kind === 163 /* GetAccessor */) {
16534                 getAccessor = accessor;
16535             }
16536             else if (accessor.kind === 164 /* SetAccessor */) {
16537                 setAccessor = accessor;
16538             }
16539             else {
16540                 ts.Debug.fail("Accessor has wrong kind");
16541             }
16542         }
16543         else {
16544             ts.forEach(declarations, function (member) {
16545                 if (ts.isAccessor(member)
16546                     && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
16547                     var memberName = getPropertyNameForPropertyNameNode(member.name);
16548                     var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
16549                     if (memberName === accessorName) {
16550                         if (!firstAccessor) {
16551                             firstAccessor = member;
16552                         }
16553                         else if (!secondAccessor) {
16554                             secondAccessor = member;
16555                         }
16556                         if (member.kind === 163 /* GetAccessor */ && !getAccessor) {
16557                             // eslint-disable-next-line
16558                             getAccessor = member;
16559                         }
16560                         if (member.kind === 164 /* SetAccessor */ && !setAccessor) {
16561                             // eslint-disable-next-line
16562                             setAccessor = member;
16563                         }
16564                     }
16565                 }
16566             });
16567         }
16568         return {
16569             firstAccessor: firstAccessor,
16570             secondAccessor: secondAccessor,
16571             getAccessor: getAccessor,
16572             setAccessor: setAccessor
16573         };
16574     }
16575     ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
16576     /**
16577      * Gets the effective type annotation of a variable, parameter, or property. If the node was
16578      * parsed in a JavaScript file, gets the type annotation from JSDoc.  Also gets the type of
16579      * functions only the JSDoc case.
16580      */
16581     function getEffectiveTypeAnnotationNode(node) {
16582         if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
16583             return undefined;
16584         var type = node.type;
16585         if (type || !isInJSFile(node))
16586             return type;
16587         return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
16588     }
16589     ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
16590     function getTypeAnnotationNode(node) {
16591         return node.type;
16592     }
16593     ts.getTypeAnnotationNode = getTypeAnnotationNode;
16594     /**
16595      * Gets the effective return type annotation of a signature. If the node was parsed in a
16596      * JavaScript file, gets the return type annotation from JSDoc.
16597      */
16598     function getEffectiveReturnTypeNode(node) {
16599         return ts.isJSDocSignature(node) ?
16600             node.type && node.type.typeExpression && node.type.typeExpression.type :
16601             node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
16602     }
16603     ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
16604     function getJSDocTypeParameterDeclarations(node) {
16605         return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
16606     }
16607     ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
16608     /** template tags are only available when a typedef isn't already using them */
16609     function isNonTypeAliasTemplate(tag) {
16610         return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 303 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
16611     }
16612     /**
16613      * Gets the effective type annotation of the value parameter of a set accessor. If the node
16614      * was parsed in a JavaScript file, gets the type annotation from JSDoc.
16615      */
16616     function getEffectiveSetAccessorTypeAnnotationNode(node) {
16617         var parameter = getSetAccessorValueParameter(node);
16618         return parameter && getEffectiveTypeAnnotationNode(parameter);
16619     }
16620     ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
16621     function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
16622         emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
16623     }
16624     ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
16625     function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
16626         // If the leading comments start on different line than the start of node, write new line
16627         if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
16628             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
16629             writer.writeLine();
16630         }
16631     }
16632     ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
16633     function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
16634         // If the leading comments start on different line than the start of node, write new line
16635         if (pos !== commentPos &&
16636             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
16637             writer.writeLine();
16638         }
16639     }
16640     ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
16641     function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
16642         if (comments && comments.length > 0) {
16643             if (leadingSeparator) {
16644                 writer.writeSpace(" ");
16645             }
16646             var emitInterveningSeparator = false;
16647             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
16648                 var comment = comments_1[_i];
16649                 if (emitInterveningSeparator) {
16650                     writer.writeSpace(" ");
16651                     emitInterveningSeparator = false;
16652                 }
16653                 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
16654                 if (comment.hasTrailingNewLine) {
16655                     writer.writeLine();
16656                 }
16657                 else {
16658                     emitInterveningSeparator = true;
16659                 }
16660             }
16661             if (emitInterveningSeparator && trailingSeparator) {
16662                 writer.writeSpace(" ");
16663             }
16664         }
16665     }
16666     ts.emitComments = emitComments;
16667     /**
16668      * Detached comment is a comment at the top of file or function body that is separated from
16669      * the next statement by space.
16670      */
16671     function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
16672         var leadingComments;
16673         var currentDetachedCommentInfo;
16674         if (removeComments) {
16675             // removeComments is true, only reserve pinned comment at the top of file
16676             // For example:
16677             //      /*! Pinned Comment */
16678             //
16679             //      var x = 10;
16680             if (node.pos === 0) {
16681                 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
16682             }
16683         }
16684         else {
16685             // removeComments is false, just get detached as normal and bypass the process to filter comment
16686             leadingComments = ts.getLeadingCommentRanges(text, node.pos);
16687         }
16688         if (leadingComments) {
16689             var detachedComments = [];
16690             var lastComment = void 0;
16691             for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
16692                 var comment = leadingComments_1[_i];
16693                 if (lastComment) {
16694                     var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
16695                     var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
16696                     if (commentLine >= lastCommentLine + 2) {
16697                         // There was a blank line between the last comment and this comment.  This
16698                         // comment is not part of the copyright comments.  Return what we have so
16699                         // far.
16700                         break;
16701                     }
16702                 }
16703                 detachedComments.push(comment);
16704                 lastComment = comment;
16705             }
16706             if (detachedComments.length) {
16707                 // All comments look like they could have been part of the copyright header.  Make
16708                 // sure there is at least one blank line between it and the node.  If not, it's not
16709                 // a copyright header.
16710                 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
16711                 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
16712                 if (nodeLine >= lastCommentLine + 2) {
16713                     // Valid detachedComments
16714                     emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
16715                     emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
16716                     currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
16717                 }
16718             }
16719         }
16720         return currentDetachedCommentInfo;
16721         function isPinnedCommentLocal(comment) {
16722             return isPinnedComment(text, comment.pos);
16723         }
16724     }
16725     ts.emitDetachedComments = emitDetachedComments;
16726     function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
16727         if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
16728             var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
16729             var lineCount = lineMap.length;
16730             var firstCommentLineIndent = void 0;
16731             for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
16732                 var nextLineStart = (currentLine + 1) === lineCount
16733                     ? text.length + 1
16734                     : lineMap[currentLine + 1];
16735                 if (pos !== commentPos) {
16736                     // If we are not emitting first line, we need to write the spaces to adjust the alignment
16737                     if (firstCommentLineIndent === undefined) {
16738                         firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
16739                     }
16740                     // These are number of spaces writer is going to write at current indent
16741                     var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
16742                     // Number of spaces we want to be writing
16743                     // eg: Assume writer indent
16744                     // module m {
16745                     //         /* starts at character 9 this is line 1
16746                     //    * starts at character pos 4 line                        --1  = 8 - 8 + 3
16747                     //   More left indented comment */                            --2  = 8 - 8 + 2
16748                     //     class c { }
16749                     // }
16750                     // module m {
16751                     //     /* this is line 1 -- Assume current writer indent 8
16752                     //      * line                                                --3 = 8 - 4 + 5
16753                     //            More right indented comment */                  --4 = 8 - 4 + 11
16754                     //     class c { }
16755                     // }
16756                     var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
16757                     if (spacesToEmit > 0) {
16758                         var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
16759                         var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
16760                         // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
16761                         writer.rawWrite(indentSizeSpaceString);
16762                         // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
16763                         while (numberOfSingleSpacesToEmit) {
16764                             writer.rawWrite(" ");
16765                             numberOfSingleSpacesToEmit--;
16766                         }
16767                     }
16768                     else {
16769                         // No spaces to emit write empty string
16770                         writer.rawWrite("");
16771                     }
16772                 }
16773                 // Write the comment line text
16774                 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
16775                 pos = nextLineStart;
16776             }
16777         }
16778         else {
16779             // Single line comment of style //....
16780             writer.writeComment(text.substring(commentPos, commentEnd));
16781         }
16782     }
16783     ts.writeCommentRange = writeCommentRange;
16784     function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
16785         var end = Math.min(commentEnd, nextLineStart - 1);
16786         var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
16787         if (currentLineText) {
16788             // trimmed forward and ending spaces text
16789             writer.writeComment(currentLineText);
16790             if (end !== commentEnd) {
16791                 writer.writeLine();
16792             }
16793         }
16794         else {
16795             // Empty string - make sure we write empty line
16796             writer.rawWrite(newLine);
16797         }
16798     }
16799     function calculateIndent(text, pos, end) {
16800         var currentLineIndent = 0;
16801         for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
16802             if (text.charCodeAt(pos) === 9 /* tab */) {
16803                 // Tabs = TabSize = indent size and go to next tabStop
16804                 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
16805             }
16806             else {
16807                 // Single space
16808                 currentLineIndent++;
16809             }
16810         }
16811         return currentLineIndent;
16812     }
16813     function hasModifiers(node) {
16814         return getModifierFlags(node) !== 0 /* None */;
16815     }
16816     ts.hasModifiers = hasModifiers;
16817     function hasModifier(node, flags) {
16818         return !!getSelectedModifierFlags(node, flags);
16819     }
16820     ts.hasModifier = hasModifier;
16821     function hasStaticModifier(node) {
16822         return hasModifier(node, 32 /* Static */);
16823     }
16824     ts.hasStaticModifier = hasStaticModifier;
16825     function hasReadonlyModifier(node) {
16826         return hasModifier(node, 64 /* Readonly */);
16827     }
16828     ts.hasReadonlyModifier = hasReadonlyModifier;
16829     function getSelectedModifierFlags(node, flags) {
16830         return getModifierFlags(node) & flags;
16831     }
16832     ts.getSelectedModifierFlags = getSelectedModifierFlags;
16833     function getModifierFlags(node) {
16834         if (node.kind >= 0 /* FirstToken */ && node.kind <= 152 /* LastToken */) {
16835             return 0 /* None */;
16836         }
16837         if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
16838             return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
16839         }
16840         var flags = getModifierFlagsNoCache(node);
16841         node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
16842         return flags;
16843     }
16844     ts.getModifierFlags = getModifierFlags;
16845     function getModifierFlagsNoCache(node) {
16846         var flags = 0 /* None */;
16847         if (node.modifiers) {
16848             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
16849                 var modifier = _a[_i];
16850                 flags |= modifierToFlag(modifier.kind);
16851             }
16852         }
16853         if (isInJSFile(node) && !!node.parent) {
16854             // getModifierFlagsNoCache should only be called when parent pointers are set,
16855             // or when !(node.flags & NodeFlags.Synthesized) && node.kind !== SyntaxKind.SourceFile)
16856             var tags = (ts.getJSDocPublicTag(node) ? 4 /* Public */ : 0 /* None */)
16857                 | (ts.getJSDocPrivateTag(node) ? 8 /* Private */ : 0 /* None */)
16858                 | (ts.getJSDocProtectedTag(node) ? 16 /* Protected */ : 0 /* None */)
16859                 | (ts.getJSDocReadonlyTag(node) ? 64 /* Readonly */ : 0 /* None */);
16860             flags |= tags;
16861         }
16862         if (node.flags & 4 /* NestedNamespace */ || (node.kind === 75 /* Identifier */ && node.isInJSDocNamespace)) {
16863             flags |= 1 /* Export */;
16864         }
16865         return flags;
16866     }
16867     ts.getModifierFlagsNoCache = getModifierFlagsNoCache;
16868     function modifierToFlag(token) {
16869         switch (token) {
16870             case 120 /* StaticKeyword */: return 32 /* Static */;
16871             case 119 /* PublicKeyword */: return 4 /* Public */;
16872             case 118 /* ProtectedKeyword */: return 16 /* Protected */;
16873             case 117 /* PrivateKeyword */: return 8 /* Private */;
16874             case 122 /* AbstractKeyword */: return 128 /* Abstract */;
16875             case 89 /* ExportKeyword */: return 1 /* Export */;
16876             case 130 /* DeclareKeyword */: return 2 /* Ambient */;
16877             case 81 /* ConstKeyword */: return 2048 /* Const */;
16878             case 84 /* DefaultKeyword */: return 512 /* Default */;
16879             case 126 /* AsyncKeyword */: return 256 /* Async */;
16880             case 138 /* ReadonlyKeyword */: return 64 /* Readonly */;
16881         }
16882         return 0 /* None */;
16883     }
16884     ts.modifierToFlag = modifierToFlag;
16885     function isLogicalOperator(token) {
16886         return token === 56 /* BarBarToken */
16887             || token === 55 /* AmpersandAmpersandToken */
16888             || token === 53 /* ExclamationToken */;
16889     }
16890     ts.isLogicalOperator = isLogicalOperator;
16891     function isAssignmentOperator(token) {
16892         return token >= 62 /* FirstAssignment */ && token <= 74 /* LastAssignment */;
16893     }
16894     ts.isAssignmentOperator = isAssignmentOperator;
16895     /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
16896     function tryGetClassExtendingExpressionWithTypeArguments(node) {
16897         var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
16898         return cls && !cls.isImplements ? cls.class : undefined;
16899     }
16900     ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
16901     function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
16902         return ts.isExpressionWithTypeArguments(node)
16903             && ts.isHeritageClause(node.parent)
16904             && ts.isClassLike(node.parent.parent)
16905             ? { class: node.parent.parent, isImplements: node.parent.token === 113 /* ImplementsKeyword */ }
16906             : undefined;
16907     }
16908     ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
16909     function isAssignmentExpression(node, excludeCompoundAssignment) {
16910         return ts.isBinaryExpression(node)
16911             && (excludeCompoundAssignment
16912                 ? node.operatorToken.kind === 62 /* EqualsToken */
16913                 : isAssignmentOperator(node.operatorToken.kind))
16914             && ts.isLeftHandSideExpression(node.left);
16915     }
16916     ts.isAssignmentExpression = isAssignmentExpression;
16917     function isDestructuringAssignment(node) {
16918         if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
16919             var kind = node.left.kind;
16920             return kind === 193 /* ObjectLiteralExpression */
16921                 || kind === 192 /* ArrayLiteralExpression */;
16922         }
16923         return false;
16924     }
16925     ts.isDestructuringAssignment = isDestructuringAssignment;
16926     function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
16927         return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
16928     }
16929     ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
16930     function isEntityNameExpression(node) {
16931         return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
16932     }
16933     ts.isEntityNameExpression = isEntityNameExpression;
16934     function getFirstIdentifier(node) {
16935         switch (node.kind) {
16936             case 75 /* Identifier */:
16937                 return node;
16938             case 153 /* QualifiedName */:
16939                 do {
16940                     node = node.left;
16941                 } while (node.kind !== 75 /* Identifier */);
16942                 return node;
16943             case 194 /* PropertyAccessExpression */:
16944                 do {
16945                     node = node.expression;
16946                 } while (node.kind !== 75 /* Identifier */);
16947                 return node;
16948         }
16949     }
16950     ts.getFirstIdentifier = getFirstIdentifier;
16951     function isDottedName(node) {
16952         return node.kind === 75 /* Identifier */ || node.kind === 104 /* ThisKeyword */ || node.kind === 102 /* SuperKeyword */ ||
16953             node.kind === 194 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
16954             node.kind === 200 /* ParenthesizedExpression */ && isDottedName(node.expression);
16955     }
16956     ts.isDottedName = isDottedName;
16957     function isPropertyAccessEntityNameExpression(node) {
16958         return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
16959     }
16960     ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
16961     function tryGetPropertyAccessOrIdentifierToString(expr) {
16962         if (ts.isPropertyAccessExpression(expr)) {
16963             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
16964             if (baseStr !== undefined) {
16965                 return baseStr + "." + expr.name;
16966             }
16967         }
16968         else if (ts.isIdentifier(expr)) {
16969             return ts.unescapeLeadingUnderscores(expr.escapedText);
16970         }
16971         return undefined;
16972     }
16973     ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
16974     function isPrototypeAccess(node) {
16975         return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
16976     }
16977     ts.isPrototypeAccess = isPrototypeAccess;
16978     function isRightSideOfQualifiedNameOrPropertyAccess(node) {
16979         return (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) ||
16980             (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node);
16981     }
16982     ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
16983     function isEmptyObjectLiteral(expression) {
16984         return expression.kind === 193 /* ObjectLiteralExpression */ &&
16985             expression.properties.length === 0;
16986     }
16987     ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
16988     function isEmptyArrayLiteral(expression) {
16989         return expression.kind === 192 /* ArrayLiteralExpression */ &&
16990             expression.elements.length === 0;
16991     }
16992     ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
16993     function getLocalSymbolForExportDefault(symbol) {
16994         return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined;
16995     }
16996     ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
16997     function isExportDefaultSymbol(symbol) {
16998         return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */);
16999     }
17000     /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
17001     function tryExtractTSExtension(fileName) {
17002         return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
17003     }
17004     ts.tryExtractTSExtension = tryExtractTSExtension;
17005     /**
17006      * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
17007      * representing the UTF-8 encoding of the character, and return the expanded char code list.
17008      */
17009     function getExpandedCharCodes(input) {
17010         var output = [];
17011         var length = input.length;
17012         for (var i = 0; i < length; i++) {
17013             var charCode = input.charCodeAt(i);
17014             // handle utf8
17015             if (charCode < 0x80) {
17016                 output.push(charCode);
17017             }
17018             else if (charCode < 0x800) {
17019                 output.push((charCode >> 6) | 192);
17020                 output.push((charCode & 63) | 128);
17021             }
17022             else if (charCode < 0x10000) {
17023                 output.push((charCode >> 12) | 224);
17024                 output.push(((charCode >> 6) & 63) | 128);
17025                 output.push((charCode & 63) | 128);
17026             }
17027             else if (charCode < 0x20000) {
17028                 output.push((charCode >> 18) | 240);
17029                 output.push(((charCode >> 12) & 63) | 128);
17030                 output.push(((charCode >> 6) & 63) | 128);
17031                 output.push((charCode & 63) | 128);
17032             }
17033             else {
17034                 ts.Debug.assert(false, "Unexpected code point");
17035             }
17036         }
17037         return output;
17038     }
17039     var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17040     /**
17041      * Converts a string to a base-64 encoded ASCII string.
17042      */
17043     function convertToBase64(input) {
17044         var result = "";
17045         var charCodes = getExpandedCharCodes(input);
17046         var i = 0;
17047         var length = charCodes.length;
17048         var byte1, byte2, byte3, byte4;
17049         while (i < length) {
17050             // Convert every 6-bits in the input 3 character points
17051             // into a base64 digit
17052             byte1 = charCodes[i] >> 2;
17053             byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
17054             byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
17055             byte4 = charCodes[i + 2] & 63;
17056             // We are out of characters in the input, set the extra
17057             // digits to 64 (padding character).
17058             if (i + 1 >= length) {
17059                 byte3 = byte4 = 64;
17060             }
17061             else if (i + 2 >= length) {
17062                 byte4 = 64;
17063             }
17064             // Write to the output
17065             result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
17066             i += 3;
17067         }
17068         return result;
17069     }
17070     ts.convertToBase64 = convertToBase64;
17071     function getStringFromExpandedCharCodes(codes) {
17072         var output = "";
17073         var i = 0;
17074         var length = codes.length;
17075         while (i < length) {
17076             var charCode = codes[i];
17077             if (charCode < 0x80) {
17078                 output += String.fromCharCode(charCode);
17079                 i++;
17080             }
17081             else if ((charCode & 192) === 192) {
17082                 var value = charCode & 63;
17083                 i++;
17084                 var nextCode = codes[i];
17085                 while ((nextCode & 192) === 128) {
17086                     value = (value << 6) | (nextCode & 63);
17087                     i++;
17088                     nextCode = codes[i];
17089                 }
17090                 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
17091                 output += String.fromCharCode(value);
17092             }
17093             else {
17094                 // We don't want to kill the process when decoding fails (due to a following char byte not
17095                 // following a leading char), so we just print the (bad) value
17096                 output += String.fromCharCode(charCode);
17097                 i++;
17098             }
17099         }
17100         return output;
17101     }
17102     function base64encode(host, input) {
17103         if (host && host.base64encode) {
17104             return host.base64encode(input);
17105         }
17106         return convertToBase64(input);
17107     }
17108     ts.base64encode = base64encode;
17109     function base64decode(host, input) {
17110         if (host && host.base64decode) {
17111             return host.base64decode(input);
17112         }
17113         var length = input.length;
17114         var expandedCharCodes = [];
17115         var i = 0;
17116         while (i < length) {
17117             // Stop decoding once padding characters are present
17118             if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
17119                 break;
17120             }
17121             // convert 4 input digits into three characters, ignoring padding characters at the end
17122             var ch1 = base64Digits.indexOf(input[i]);
17123             var ch2 = base64Digits.indexOf(input[i + 1]);
17124             var ch3 = base64Digits.indexOf(input[i + 2]);
17125             var ch4 = base64Digits.indexOf(input[i + 3]);
17126             var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
17127             var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
17128             var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
17129             if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
17130                 expandedCharCodes.push(code1);
17131             }
17132             else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
17133                 expandedCharCodes.push(code1, code2);
17134             }
17135             else {
17136                 expandedCharCodes.push(code1, code2, code3);
17137             }
17138             i += 4;
17139         }
17140         return getStringFromExpandedCharCodes(expandedCharCodes);
17141     }
17142     ts.base64decode = base64decode;
17143     function readJson(path, host) {
17144         try {
17145             var jsonText = host.readFile(path);
17146             if (!jsonText)
17147                 return {};
17148             var result = ts.parseConfigFileTextToJson(path, jsonText);
17149             if (result.error) {
17150                 return {};
17151             }
17152             return result.config;
17153         }
17154         catch (e) {
17155             // gracefully handle if readFile fails or returns not JSON
17156             return {};
17157         }
17158     }
17159     ts.readJson = readJson;
17160     function directoryProbablyExists(directoryName, host) {
17161         // if host does not support 'directoryExists' assume that directory will exist
17162         return !host.directoryExists || host.directoryExists(directoryName);
17163     }
17164     ts.directoryProbablyExists = directoryProbablyExists;
17165     var carriageReturnLineFeed = "\r\n";
17166     var lineFeed = "\n";
17167     function getNewLineCharacter(options, getNewLine) {
17168         switch (options.newLine) {
17169             case 0 /* CarriageReturnLineFeed */:
17170                 return carriageReturnLineFeed;
17171             case 1 /* LineFeed */:
17172                 return lineFeed;
17173         }
17174         return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
17175     }
17176     ts.getNewLineCharacter = getNewLineCharacter;
17177     /**
17178      * Creates a new TextRange from the provided pos and end.
17179      *
17180      * @param pos The start position.
17181      * @param end The end position.
17182      */
17183     function createRange(pos, end) {
17184         if (end === void 0) { end = pos; }
17185         ts.Debug.assert(end >= pos || end === -1);
17186         return { pos: pos, end: end };
17187     }
17188     ts.createRange = createRange;
17189     /**
17190      * Creates a new TextRange from a provided range with a new end position.
17191      *
17192      * @param range A TextRange.
17193      * @param end The new end position.
17194      */
17195     function moveRangeEnd(range, end) {
17196         return createRange(range.pos, end);
17197     }
17198     ts.moveRangeEnd = moveRangeEnd;
17199     /**
17200      * Creates a new TextRange from a provided range with a new start position.
17201      *
17202      * @param range A TextRange.
17203      * @param pos The new Start position.
17204      */
17205     function moveRangePos(range, pos) {
17206         return createRange(pos, range.end);
17207     }
17208     ts.moveRangePos = moveRangePos;
17209     /**
17210      * Moves the start position of a range past any decorators.
17211      */
17212     function moveRangePastDecorators(node) {
17213         return node.decorators && node.decorators.length > 0
17214             ? moveRangePos(node, node.decorators.end)
17215             : node;
17216     }
17217     ts.moveRangePastDecorators = moveRangePastDecorators;
17218     /**
17219      * Moves the start position of a range past any decorators or modifiers.
17220      */
17221     function moveRangePastModifiers(node) {
17222         return node.modifiers && node.modifiers.length > 0
17223             ? moveRangePos(node, node.modifiers.end)
17224             : moveRangePastDecorators(node);
17225     }
17226     ts.moveRangePastModifiers = moveRangePastModifiers;
17227     /**
17228      * Determines whether a TextRange has the same start and end positions.
17229      *
17230      * @param range A TextRange.
17231      */
17232     function isCollapsedRange(range) {
17233         return range.pos === range.end;
17234     }
17235     ts.isCollapsedRange = isCollapsedRange;
17236     /**
17237      * Creates a new TextRange for a token at the provides start position.
17238      *
17239      * @param pos The start position.
17240      * @param token The token.
17241      */
17242     function createTokenRange(pos, token) {
17243         return createRange(pos, pos + ts.tokenToString(token).length);
17244     }
17245     ts.createTokenRange = createTokenRange;
17246     function rangeIsOnSingleLine(range, sourceFile) {
17247         return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
17248     }
17249     ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
17250     function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
17251         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17252     }
17253     ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
17254     function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
17255         return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
17256     }
17257     ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
17258     function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
17259         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
17260     }
17261     ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
17262     function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
17263         return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17264     }
17265     ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
17266     function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
17267         var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
17268         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
17269     }
17270     ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
17271     function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
17272         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
17273     }
17274     ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
17275     function isNodeArrayMultiLine(list, sourceFile) {
17276         return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
17277     }
17278     ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
17279     function positionsAreOnSameLine(pos1, pos2, sourceFile) {
17280         return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
17281     }
17282     ts.positionsAreOnSameLine = positionsAreOnSameLine;
17283     function getStartPositionOfRange(range, sourceFile, includeComments) {
17284         return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
17285     }
17286     ts.getStartPositionOfRange = getStartPositionOfRange;
17287     function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17288         var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17289         var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
17290         return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
17291     }
17292     ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
17293     function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17294         var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17295         return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
17296     }
17297     ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
17298     function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
17299         if (stopPos === void 0) { stopPos = 0; }
17300         while (pos-- > stopPos) {
17301             if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
17302                 return pos;
17303             }
17304         }
17305     }
17306     /**
17307      * Determines whether a name was originally the declaration name of an enum or namespace
17308      * declaration.
17309      */
17310     function isDeclarationNameOfEnumOrNamespace(node) {
17311         var parseNode = ts.getParseTreeNode(node);
17312         if (parseNode) {
17313             switch (parseNode.parent.kind) {
17314                 case 248 /* EnumDeclaration */:
17315                 case 249 /* ModuleDeclaration */:
17316                     return parseNode === parseNode.parent.name;
17317             }
17318         }
17319         return false;
17320     }
17321     ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
17322     function getInitializedVariables(node) {
17323         return ts.filter(node.declarations, isInitializedVariable);
17324     }
17325     ts.getInitializedVariables = getInitializedVariables;
17326     function isInitializedVariable(node) {
17327         return node.initializer !== undefined;
17328     }
17329     function isWatchSet(options) {
17330         // Firefox has Object.prototype.watch
17331         return options.watch && options.hasOwnProperty("watch");
17332     }
17333     ts.isWatchSet = isWatchSet;
17334     function closeFileWatcher(watcher) {
17335         watcher.close();
17336     }
17337     ts.closeFileWatcher = closeFileWatcher;
17338     function getCheckFlags(symbol) {
17339         return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
17340     }
17341     ts.getCheckFlags = getCheckFlags;
17342     function getDeclarationModifierFlagsFromSymbol(s) {
17343         if (s.valueDeclaration) {
17344             var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
17345             return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
17346         }
17347         if (getCheckFlags(s) & 6 /* Synthetic */) {
17348             var checkFlags = s.checkFlags;
17349             var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
17350                 checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
17351                     16 /* Protected */;
17352             var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
17353             return accessModifier | staticModifier;
17354         }
17355         if (s.flags & 4194304 /* Prototype */) {
17356             return 4 /* Public */ | 32 /* Static */;
17357         }
17358         return 0;
17359     }
17360     ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
17361     function skipAlias(symbol, checker) {
17362         return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
17363     }
17364     ts.skipAlias = skipAlias;
17365     /** See comment on `declareModuleMember` in `binder.ts`. */
17366     function getCombinedLocalAndExportSymbolFlags(symbol) {
17367         return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
17368     }
17369     ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
17370     function isWriteOnlyAccess(node) {
17371         return accessKind(node) === 1 /* Write */;
17372     }
17373     ts.isWriteOnlyAccess = isWriteOnlyAccess;
17374     function isWriteAccess(node) {
17375         return accessKind(node) !== 0 /* Read */;
17376     }
17377     ts.isWriteAccess = isWriteAccess;
17378     var AccessKind;
17379     (function (AccessKind) {
17380         /** Only reads from a variable. */
17381         AccessKind[AccessKind["Read"] = 0] = "Read";
17382         /** Only writes to a variable without using the result. E.g.: `x++;`. */
17383         AccessKind[AccessKind["Write"] = 1] = "Write";
17384         /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
17385         AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
17386     })(AccessKind || (AccessKind = {}));
17387     function accessKind(node) {
17388         var parent = node.parent;
17389         if (!parent)
17390             return 0 /* Read */;
17391         switch (parent.kind) {
17392             case 200 /* ParenthesizedExpression */:
17393                 return accessKind(parent);
17394             case 208 /* PostfixUnaryExpression */:
17395             case 207 /* PrefixUnaryExpression */:
17396                 var operator = parent.operator;
17397                 return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
17398             case 209 /* BinaryExpression */:
17399                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
17400                 return left === node && isAssignmentOperator(operatorToken.kind) ?
17401                     operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
17402                     : 0 /* Read */;
17403             case 194 /* PropertyAccessExpression */:
17404                 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
17405             case 281 /* PropertyAssignment */: {
17406                 var parentAccess = accessKind(parent.parent);
17407                 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
17408                 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
17409             }
17410             case 282 /* ShorthandPropertyAssignment */:
17411                 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
17412                 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
17413             case 192 /* ArrayLiteralExpression */:
17414                 return accessKind(parent);
17415             default:
17416                 return 0 /* Read */;
17417         }
17418         function writeOrReadWrite() {
17419             // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
17420             return parent.parent && skipParenthesesUp(parent.parent).kind === 226 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
17421         }
17422     }
17423     function reverseAccessKind(a) {
17424         switch (a) {
17425             case 0 /* Read */:
17426                 return 1 /* Write */;
17427             case 1 /* Write */:
17428                 return 0 /* Read */;
17429             case 2 /* ReadWrite */:
17430                 return 2 /* ReadWrite */;
17431             default:
17432                 return ts.Debug.assertNever(a);
17433         }
17434     }
17435     function compareDataObjects(dst, src) {
17436         if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
17437             return false;
17438         }
17439         for (var e in dst) {
17440             if (typeof dst[e] === "object") {
17441                 if (!compareDataObjects(dst[e], src[e])) {
17442                     return false;
17443                 }
17444             }
17445             else if (typeof dst[e] !== "function") {
17446                 if (dst[e] !== src[e]) {
17447                     return false;
17448                 }
17449             }
17450         }
17451         return true;
17452     }
17453     ts.compareDataObjects = compareDataObjects;
17454     /**
17455      * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
17456      */
17457     function clearMap(map, onDeleteValue) {
17458         // Remove all
17459         map.forEach(onDeleteValue);
17460         map.clear();
17461     }
17462     ts.clearMap = clearMap;
17463     /**
17464      * Mutates the map with newMap such that keys in map will be same as newMap.
17465      */
17466     function mutateMapSkippingNewValues(map, newMap, options) {
17467         var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
17468         // Needs update
17469         map.forEach(function (existingValue, key) {
17470             var valueInNewMap = newMap.get(key);
17471             // Not present any more in new map, remove it
17472             if (valueInNewMap === undefined) {
17473                 map.delete(key);
17474                 onDeleteValue(existingValue, key);
17475             }
17476             // If present notify about existing values
17477             else if (onExistingValue) {
17478                 onExistingValue(existingValue, valueInNewMap, key);
17479             }
17480         });
17481     }
17482     ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
17483     /**
17484      * Mutates the map with newMap such that keys in map will be same as newMap.
17485      */
17486     function mutateMap(map, newMap, options) {
17487         // Needs update
17488         mutateMapSkippingNewValues(map, newMap, options);
17489         var createNewValue = options.createNewValue;
17490         // Add new values that are not already present
17491         newMap.forEach(function (valueInNewMap, key) {
17492             if (!map.has(key)) {
17493                 // New values
17494                 map.set(key, createNewValue(key, valueInNewMap));
17495             }
17496         });
17497     }
17498     ts.mutateMap = mutateMap;
17499     // Return true if the given type is the constructor type for an abstract class
17500     function isAbstractConstructorType(type) {
17501         return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
17502     }
17503     ts.isAbstractConstructorType = isAbstractConstructorType;
17504     function isAbstractConstructorSymbol(symbol) {
17505         if (symbol.flags & 32 /* Class */) {
17506             var declaration = getClassLikeDeclarationOfSymbol(symbol);
17507             return !!declaration && hasModifier(declaration, 128 /* Abstract */);
17508         }
17509         return false;
17510     }
17511     ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
17512     function getClassLikeDeclarationOfSymbol(symbol) {
17513         return ts.find(symbol.declarations, ts.isClassLike);
17514     }
17515     ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
17516     function getObjectFlags(type) {
17517         return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
17518     }
17519     ts.getObjectFlags = getObjectFlags;
17520     function typeHasCallOrConstructSignatures(type, checker) {
17521         return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
17522     }
17523     ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
17524     function forSomeAncestorDirectory(directory, callback) {
17525         return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
17526     }
17527     ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
17528     function isUMDExportSymbol(symbol) {
17529         return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
17530     }
17531     ts.isUMDExportSymbol = isUMDExportSymbol;
17532     function showModuleSpecifier(_a) {
17533         var moduleSpecifier = _a.moduleSpecifier;
17534         return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
17535     }
17536     ts.showModuleSpecifier = showModuleSpecifier;
17537     function getLastChild(node) {
17538         var lastChild;
17539         ts.forEachChild(node, function (child) {
17540             if (nodeIsPresent(child))
17541                 lastChild = child;
17542         }, function (children) {
17543             // As an optimization, jump straight to the end of the list.
17544             for (var i = children.length - 1; i >= 0; i--) {
17545                 if (nodeIsPresent(children[i])) {
17546                     lastChild = children[i];
17547                     break;
17548                 }
17549             }
17550         });
17551         return lastChild;
17552     }
17553     ts.getLastChild = getLastChild;
17554     function addToSeen(seen, key, value) {
17555         if (value === void 0) { value = true; }
17556         key = String(key);
17557         if (seen.has(key)) {
17558             return false;
17559         }
17560         seen.set(key, value);
17561         return true;
17562     }
17563     ts.addToSeen = addToSeen;
17564     function isObjectTypeDeclaration(node) {
17565         return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
17566     }
17567     ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
17568     function isTypeNodeKind(kind) {
17569         return (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */)
17570             || kind === 125 /* AnyKeyword */
17571             || kind === 148 /* UnknownKeyword */
17572             || kind === 140 /* NumberKeyword */
17573             || kind === 151 /* BigIntKeyword */
17574             || kind === 141 /* ObjectKeyword */
17575             || kind === 128 /* BooleanKeyword */
17576             || kind === 143 /* StringKeyword */
17577             || kind === 144 /* SymbolKeyword */
17578             || kind === 104 /* ThisKeyword */
17579             || kind === 110 /* VoidKeyword */
17580             || kind === 146 /* UndefinedKeyword */
17581             || kind === 100 /* NullKeyword */
17582             || kind === 137 /* NeverKeyword */
17583             || kind === 216 /* ExpressionWithTypeArguments */
17584             || kind === 295 /* JSDocAllType */
17585             || kind === 296 /* JSDocUnknownType */
17586             || kind === 297 /* JSDocNullableType */
17587             || kind === 298 /* JSDocNonNullableType */
17588             || kind === 299 /* JSDocOptionalType */
17589             || kind === 300 /* JSDocFunctionType */
17590             || kind === 301 /* JSDocVariadicType */;
17591     }
17592     ts.isTypeNodeKind = isTypeNodeKind;
17593     function isAccessExpression(node) {
17594         return node.kind === 194 /* PropertyAccessExpression */ || node.kind === 195 /* ElementAccessExpression */;
17595     }
17596     ts.isAccessExpression = isAccessExpression;
17597     function getNameOfAccessExpression(node) {
17598         if (node.kind === 194 /* PropertyAccessExpression */) {
17599             return node.name;
17600         }
17601         ts.Debug.assert(node.kind === 195 /* ElementAccessExpression */);
17602         return node.argumentExpression;
17603     }
17604     ts.getNameOfAccessExpression = getNameOfAccessExpression;
17605     function isBundleFileTextLike(section) {
17606         switch (section.kind) {
17607             case "text" /* Text */:
17608             case "internal" /* Internal */:
17609                 return true;
17610             default:
17611                 return false;
17612         }
17613     }
17614     ts.isBundleFileTextLike = isBundleFileTextLike;
17615     function isNamedImportsOrExports(node) {
17616         return node.kind === 257 /* NamedImports */ || node.kind === 261 /* NamedExports */;
17617     }
17618     ts.isNamedImportsOrExports = isNamedImportsOrExports;
17619     function Symbol(flags, name) {
17620         this.flags = flags;
17621         this.escapedName = name;
17622         this.declarations = undefined;
17623         this.valueDeclaration = undefined;
17624         this.id = undefined;
17625         this.mergeId = undefined;
17626         this.parent = undefined;
17627     }
17628     function Type(checker, flags) {
17629         this.flags = flags;
17630         if (ts.Debug.isDebugging) {
17631             this.checker = checker;
17632         }
17633     }
17634     function Signature(checker, flags) {
17635         this.flags = flags;
17636         if (ts.Debug.isDebugging) {
17637             this.checker = checker;
17638         }
17639     }
17640     function Node(kind, pos, end) {
17641         this.pos = pos;
17642         this.end = end;
17643         this.kind = kind;
17644         this.id = 0;
17645         this.flags = 0 /* None */;
17646         this.modifierFlagsCache = 0 /* None */;
17647         this.transformFlags = 0 /* None */;
17648         this.parent = undefined;
17649         this.original = undefined;
17650     }
17651     function Token(kind, pos, end) {
17652         this.pos = pos;
17653         this.end = end;
17654         this.kind = kind;
17655         this.id = 0;
17656         this.flags = 0 /* None */;
17657         this.transformFlags = 0 /* None */;
17658         this.parent = undefined;
17659     }
17660     function Identifier(kind, pos, end) {
17661         this.pos = pos;
17662         this.end = end;
17663         this.kind = kind;
17664         this.id = 0;
17665         this.flags = 0 /* None */;
17666         this.transformFlags = 0 /* None */;
17667         this.parent = undefined;
17668         this.original = undefined;
17669         this.flowNode = undefined;
17670     }
17671     function SourceMapSource(fileName, text, skipTrivia) {
17672         this.fileName = fileName;
17673         this.text = text;
17674         this.skipTrivia = skipTrivia || (function (pos) { return pos; });
17675     }
17676     // eslint-disable-next-line prefer-const
17677     ts.objectAllocator = {
17678         getNodeConstructor: function () { return Node; },
17679         getTokenConstructor: function () { return Token; },
17680         getIdentifierConstructor: function () { return Identifier; },
17681         getPrivateIdentifierConstructor: function () { return Node; },
17682         getSourceFileConstructor: function () { return Node; },
17683         getSymbolConstructor: function () { return Symbol; },
17684         getTypeConstructor: function () { return Type; },
17685         getSignatureConstructor: function () { return Signature; },
17686         getSourceMapSourceConstructor: function () { return SourceMapSource; },
17687     };
17688     function setObjectAllocator(alloc) {
17689         ts.objectAllocator = alloc;
17690     }
17691     ts.setObjectAllocator = setObjectAllocator;
17692     function formatStringFromArgs(text, args, baseIndex) {
17693         if (baseIndex === void 0) { baseIndex = 0; }
17694         return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
17695     }
17696     ts.formatStringFromArgs = formatStringFromArgs;
17697     /* @internal */
17698     function setLocalizedDiagnosticMessages(messages) {
17699         ts.localizedDiagnosticMessages = messages;
17700     }
17701     ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
17702     function getLocaleSpecificMessage(message) {
17703         return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
17704     }
17705     ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
17706     function createFileDiagnostic(file, start, length, message) {
17707         ts.Debug.assertGreaterThanOrEqual(start, 0);
17708         ts.Debug.assertGreaterThanOrEqual(length, 0);
17709         if (file) {
17710             ts.Debug.assertLessThanOrEqual(start, file.text.length);
17711             ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
17712         }
17713         var text = getLocaleSpecificMessage(message);
17714         if (arguments.length > 4) {
17715             text = formatStringFromArgs(text, arguments, 4);
17716         }
17717         return {
17718             file: file,
17719             start: start,
17720             length: length,
17721             messageText: text,
17722             category: message.category,
17723             code: message.code,
17724             reportsUnnecessary: message.reportsUnnecessary,
17725         };
17726     }
17727     ts.createFileDiagnostic = createFileDiagnostic;
17728     function formatMessage(_dummy, message) {
17729         var text = getLocaleSpecificMessage(message);
17730         if (arguments.length > 2) {
17731             text = formatStringFromArgs(text, arguments, 2);
17732         }
17733         return text;
17734     }
17735     ts.formatMessage = formatMessage;
17736     function createCompilerDiagnostic(message) {
17737         var text = getLocaleSpecificMessage(message);
17738         if (arguments.length > 1) {
17739             text = formatStringFromArgs(text, arguments, 1);
17740         }
17741         return {
17742             file: undefined,
17743             start: undefined,
17744             length: undefined,
17745             messageText: text,
17746             category: message.category,
17747             code: message.code,
17748             reportsUnnecessary: message.reportsUnnecessary,
17749         };
17750     }
17751     ts.createCompilerDiagnostic = createCompilerDiagnostic;
17752     function createCompilerDiagnosticFromMessageChain(chain) {
17753         return {
17754             file: undefined,
17755             start: undefined,
17756             length: undefined,
17757             code: chain.code,
17758             category: chain.category,
17759             messageText: chain.next ? chain : chain.messageText,
17760         };
17761     }
17762     ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
17763     function chainDiagnosticMessages(details, message) {
17764         var text = getLocaleSpecificMessage(message);
17765         if (arguments.length > 2) {
17766             text = formatStringFromArgs(text, arguments, 2);
17767         }
17768         return {
17769             messageText: text,
17770             category: message.category,
17771             code: message.code,
17772             next: details === undefined || Array.isArray(details) ? details : [details]
17773         };
17774     }
17775     ts.chainDiagnosticMessages = chainDiagnosticMessages;
17776     function concatenateDiagnosticMessageChains(headChain, tailChain) {
17777         var lastChain = headChain;
17778         while (lastChain.next) {
17779             lastChain = lastChain.next[0];
17780         }
17781         lastChain.next = [tailChain];
17782     }
17783     ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
17784     function getDiagnosticFilePath(diagnostic) {
17785         return diagnostic.file ? diagnostic.file.path : undefined;
17786     }
17787     function compareDiagnostics(d1, d2) {
17788         return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
17789             compareRelatedInformation(d1, d2) ||
17790             0 /* EqualTo */;
17791     }
17792     ts.compareDiagnostics = compareDiagnostics;
17793     function compareDiagnosticsSkipRelatedInformation(d1, d2) {
17794         return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
17795             ts.compareValues(d1.start, d2.start) ||
17796             ts.compareValues(d1.length, d2.length) ||
17797             ts.compareValues(d1.code, d2.code) ||
17798             compareMessageText(d1.messageText, d2.messageText) ||
17799             0 /* EqualTo */;
17800     }
17801     ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
17802     function compareRelatedInformation(d1, d2) {
17803         if (!d1.relatedInformation && !d2.relatedInformation) {
17804             return 0 /* EqualTo */;
17805         }
17806         if (d1.relatedInformation && d2.relatedInformation) {
17807             return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
17808                 var d2i = d2.relatedInformation[index];
17809                 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
17810             }) || 0 /* EqualTo */;
17811         }
17812         return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
17813     }
17814     function compareMessageText(t1, t2) {
17815         if (typeof t1 === "string" && typeof t2 === "string") {
17816             return ts.compareStringsCaseSensitive(t1, t2);
17817         }
17818         else if (typeof t1 === "string") {
17819             return -1 /* LessThan */;
17820         }
17821         else if (typeof t2 === "string") {
17822             return 1 /* GreaterThan */;
17823         }
17824         var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
17825         if (res) {
17826             return res;
17827         }
17828         if (!t1.next && !t2.next) {
17829             return 0 /* EqualTo */;
17830         }
17831         if (!t1.next) {
17832             return -1 /* LessThan */;
17833         }
17834         if (!t2.next) {
17835             return 1 /* GreaterThan */;
17836         }
17837         var len = Math.min(t1.next.length, t2.next.length);
17838         for (var i = 0; i < len; i++) {
17839             res = compareMessageText(t1.next[i], t2.next[i]);
17840             if (res) {
17841                 return res;
17842             }
17843         }
17844         if (t1.next.length < t2.next.length) {
17845             return -1 /* LessThan */;
17846         }
17847         else if (t1.next.length > t2.next.length) {
17848             return 1 /* GreaterThan */;
17849         }
17850         return 0 /* EqualTo */;
17851     }
17852     function getEmitScriptTarget(compilerOptions) {
17853         return compilerOptions.target || 0 /* ES3 */;
17854     }
17855     ts.getEmitScriptTarget = getEmitScriptTarget;
17856     function getEmitModuleKind(compilerOptions) {
17857         return typeof compilerOptions.module === "number" ?
17858             compilerOptions.module :
17859             getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
17860     }
17861     ts.getEmitModuleKind = getEmitModuleKind;
17862     function getEmitModuleResolutionKind(compilerOptions) {
17863         var moduleResolution = compilerOptions.moduleResolution;
17864         if (moduleResolution === undefined) {
17865             moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
17866         }
17867         return moduleResolution;
17868     }
17869     ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
17870     function hasJsonModuleEmitEnabled(options) {
17871         switch (getEmitModuleKind(options)) {
17872             case ts.ModuleKind.CommonJS:
17873             case ts.ModuleKind.AMD:
17874             case ts.ModuleKind.ES2015:
17875             case ts.ModuleKind.ES2020:
17876             case ts.ModuleKind.ESNext:
17877                 return true;
17878             default:
17879                 return false;
17880         }
17881     }
17882     ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
17883     function unreachableCodeIsError(options) {
17884         return options.allowUnreachableCode === false;
17885     }
17886     ts.unreachableCodeIsError = unreachableCodeIsError;
17887     function unusedLabelIsError(options) {
17888         return options.allowUnusedLabels === false;
17889     }
17890     ts.unusedLabelIsError = unusedLabelIsError;
17891     function getAreDeclarationMapsEnabled(options) {
17892         return !!(getEmitDeclarations(options) && options.declarationMap);
17893     }
17894     ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
17895     function getAllowSyntheticDefaultImports(compilerOptions) {
17896         var moduleKind = getEmitModuleKind(compilerOptions);
17897         return compilerOptions.allowSyntheticDefaultImports !== undefined
17898             ? compilerOptions.allowSyntheticDefaultImports
17899             : compilerOptions.esModuleInterop ||
17900                 moduleKind === ts.ModuleKind.System;
17901     }
17902     ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
17903     function getEmitDeclarations(compilerOptions) {
17904         return !!(compilerOptions.declaration || compilerOptions.composite);
17905     }
17906     ts.getEmitDeclarations = getEmitDeclarations;
17907     function isIncrementalCompilation(options) {
17908         return !!(options.incremental || options.composite);
17909     }
17910     ts.isIncrementalCompilation = isIncrementalCompilation;
17911     function getStrictOptionValue(compilerOptions, flag) {
17912         return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
17913     }
17914     ts.getStrictOptionValue = getStrictOptionValue;
17915     function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
17916         return oldOptions !== newOptions &&
17917             ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
17918     }
17919     ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
17920     function compilerOptionsAffectEmit(newOptions, oldOptions) {
17921         return oldOptions !== newOptions &&
17922             ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
17923     }
17924     ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
17925     function getCompilerOptionValue(options, option) {
17926         return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
17927     }
17928     ts.getCompilerOptionValue = getCompilerOptionValue;
17929     function hasZeroOrOneAsteriskCharacter(str) {
17930         var seenAsterisk = false;
17931         for (var i = 0; i < str.length; i++) {
17932             if (str.charCodeAt(i) === 42 /* asterisk */) {
17933                 if (!seenAsterisk) {
17934                     seenAsterisk = true;
17935                 }
17936                 else {
17937                     // have already seen asterisk
17938                     return false;
17939                 }
17940             }
17941         }
17942         return true;
17943     }
17944     ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
17945     function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
17946         var result = ts.createMap();
17947         var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
17948             return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
17949                 return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
17950             })));
17951         }));
17952         for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
17953             var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
17954             var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1];
17955             result.set(commonOriginal, commonResolved);
17956         }
17957         return result;
17958     }
17959     ts.discoverProbableSymlinks = discoverProbableSymlinks;
17960     function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
17961         var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
17962         var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
17963         while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
17964             !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
17965             getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
17966             aParts.pop();
17967             bParts.pop();
17968         }
17969         return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)];
17970     }
17971     // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
17972     // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
17973     function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
17974         return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
17975     }
17976     function stripLeadingDirectorySeparator(s) {
17977         return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
17978     }
17979     function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
17980         var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
17981         return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
17982     }
17983     ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
17984     // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
17985     // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
17986     // proof.
17987     var reservedCharacterPattern = /[^\w\s\/]/g;
17988     function regExpEscape(text) {
17989         return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
17990     }
17991     ts.regExpEscape = regExpEscape;
17992     function escapeRegExpCharacter(match) {
17993         return "\\" + match;
17994     }
17995     var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
17996     ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
17997     var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
17998     var filesMatcher = {
17999         /**
18000          * Matches any single directory segment unless it is the last segment and a .min.js file
18001          * Breakdown:
18002          *  [^./]                   # matches everything up to the first . character (excluding directory separators)
18003          *  (\\.(?!min\\.js$))?     # matches . characters but not if they are part of the .min.js file extension
18004          */
18005         singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
18006         /**
18007          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18008          * files or directories, does not match subdirectories that start with a . character
18009          */
18010         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18011         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
18012     };
18013     var directoriesMatcher = {
18014         singleAsteriskRegexFragment: "[^/]*",
18015         /**
18016          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18017          * files or directories, does not match subdirectories that start with a . character
18018          */
18019         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18020         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
18021     };
18022     var excludeMatcher = {
18023         singleAsteriskRegexFragment: "[^/]*",
18024         doubleAsteriskRegexFragment: "(/.+?)?",
18025         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
18026     };
18027     var wildcardMatchers = {
18028         files: filesMatcher,
18029         directories: directoriesMatcher,
18030         exclude: excludeMatcher
18031     };
18032     function getRegularExpressionForWildcard(specs, basePath, usage) {
18033         var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
18034         if (!patterns || !patterns.length) {
18035             return undefined;
18036         }
18037         var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
18038         // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
18039         var terminator = usage === "exclude" ? "($|/)" : "$";
18040         return "^(" + pattern + ")" + terminator;
18041     }
18042     ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
18043     function getRegularExpressionsForWildcards(specs, basePath, usage) {
18044         if (specs === undefined || specs.length === 0) {
18045             return undefined;
18046         }
18047         return ts.flatMap(specs, function (spec) {
18048             return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
18049         });
18050     }
18051     ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
18052     /**
18053      * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
18054      * and does not contain any glob characters itself.
18055      */
18056     function isImplicitGlob(lastPathComponent) {
18057         return !/[.*?]/.test(lastPathComponent);
18058     }
18059     ts.isImplicitGlob = isImplicitGlob;
18060     function getSubPatternFromSpec(spec, basePath, usage, _a) {
18061         var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
18062         var subpattern = "";
18063         var hasWrittenComponent = false;
18064         var components = ts.getNormalizedPathComponents(spec, basePath);
18065         var lastComponent = ts.last(components);
18066         if (usage !== "exclude" && lastComponent === "**") {
18067             return undefined;
18068         }
18069         // getNormalizedPathComponents includes the separator for the root component.
18070         // We need to remove to create our regex correctly.
18071         components[0] = ts.removeTrailingDirectorySeparator(components[0]);
18072         if (isImplicitGlob(lastComponent)) {
18073             components.push("**", "*");
18074         }
18075         var optionalCount = 0;
18076         for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
18077             var component = components_1[_i];
18078             if (component === "**") {
18079                 subpattern += doubleAsteriskRegexFragment;
18080             }
18081             else {
18082                 if (usage === "directories") {
18083                     subpattern += "(";
18084                     optionalCount++;
18085                 }
18086                 if (hasWrittenComponent) {
18087                     subpattern += ts.directorySeparator;
18088                 }
18089                 if (usage !== "exclude") {
18090                     var componentPattern = "";
18091                     // The * and ? wildcards should not match directories or files that start with . if they
18092                     // appear first in a component. Dotted directories and files can be included explicitly
18093                     // like so: **/.*/.*
18094                     if (component.charCodeAt(0) === 42 /* asterisk */) {
18095                         componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
18096                         component = component.substr(1);
18097                     }
18098                     else if (component.charCodeAt(0) === 63 /* question */) {
18099                         componentPattern += "[^./]";
18100                         component = component.substr(1);
18101                     }
18102                     componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18103                     // Patterns should not include subfolders like node_modules unless they are
18104                     // explicitly included as part of the path.
18105                     //
18106                     // As an optimization, if the component pattern is the same as the component,
18107                     // then there definitely were no wildcard characters and we do not need to
18108                     // add the exclusion pattern.
18109                     if (componentPattern !== component) {
18110                         subpattern += implicitExcludePathRegexPattern;
18111                     }
18112                     subpattern += componentPattern;
18113                 }
18114                 else {
18115                     subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18116                 }
18117             }
18118             hasWrittenComponent = true;
18119         }
18120         while (optionalCount > 0) {
18121             subpattern += ")?";
18122             optionalCount--;
18123         }
18124         return subpattern;
18125     }
18126     function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
18127         return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
18128     }
18129     /** @param path directory of the tsconfig.json */
18130     function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
18131         path = ts.normalizePath(path);
18132         currentDirectory = ts.normalizePath(currentDirectory);
18133         var absolutePath = ts.combinePaths(currentDirectory, path);
18134         return {
18135             includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
18136             includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
18137             includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
18138             excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
18139             basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
18140         };
18141     }
18142     ts.getFileMatcherPatterns = getFileMatcherPatterns;
18143     function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
18144         return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
18145     }
18146     ts.getRegexFromPattern = getRegexFromPattern;
18147     /** @param path directory of the tsconfig.json */
18148     function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
18149         path = ts.normalizePath(path);
18150         currentDirectory = ts.normalizePath(currentDirectory);
18151         var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
18152         var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
18153         var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
18154         var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
18155         // Associate an array of results with each include regex. This keeps results in order of the "include" order.
18156         // If there are no "includes", then just put everything in results[0].
18157         var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
18158         var visited = ts.createMap();
18159         var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
18160         for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
18161             var basePath = _a[_i];
18162             visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
18163         }
18164         return ts.flatten(results);
18165         function visitDirectory(path, absolutePath, depth) {
18166             var canonicalPath = toCanonical(realpath(absolutePath));
18167             if (visited.has(canonicalPath))
18168                 return;
18169             visited.set(canonicalPath, true);
18170             var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
18171             var _loop_1 = function (current) {
18172                 var name = ts.combinePaths(path, current);
18173                 var absoluteName = ts.combinePaths(absolutePath, current);
18174                 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
18175                     return "continue";
18176                 if (excludeRegex && excludeRegex.test(absoluteName))
18177                     return "continue";
18178                 if (!includeFileRegexes) {
18179                     results[0].push(name);
18180                 }
18181                 else {
18182                     var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
18183                     if (includeIndex !== -1) {
18184                         results[includeIndex].push(name);
18185                     }
18186                 }
18187             };
18188             for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
18189                 var current = _b[_i];
18190                 _loop_1(current);
18191             }
18192             if (depth !== undefined) {
18193                 depth--;
18194                 if (depth === 0) {
18195                     return;
18196                 }
18197             }
18198             for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
18199                 var current = _d[_c];
18200                 var name = ts.combinePaths(path, current);
18201                 var absoluteName = ts.combinePaths(absolutePath, current);
18202                 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
18203                     (!excludeRegex || !excludeRegex.test(absoluteName))) {
18204                     visitDirectory(name, absoluteName, depth);
18205                 }
18206             }
18207         }
18208     }
18209     ts.matchFiles = matchFiles;
18210     /**
18211      * Computes the unique non-wildcard base paths amongst the provided include patterns.
18212      */
18213     function getBasePaths(path, includes, useCaseSensitiveFileNames) {
18214         // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
18215         var basePaths = [path];
18216         if (includes) {
18217             // Storage for literal base paths amongst the include patterns.
18218             var includeBasePaths = [];
18219             for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
18220                 var include = includes_1[_i];
18221                 // We also need to check the relative paths by converting them to absolute and normalizing
18222                 // in case they escape the base path (e.g "..\somedirectory")
18223                 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
18224                 // Append the literal and canonical candidate base paths.
18225                 includeBasePaths.push(getIncludeBasePath(absolute));
18226             }
18227             // Sort the offsets array using either the literal or canonical path representations.
18228             includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
18229             var _loop_2 = function (includeBasePath) {
18230                 if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
18231                     basePaths.push(includeBasePath);
18232                 }
18233             };
18234             // Iterate over each include base path and include unique base paths that are not a
18235             // subpath of an existing base path
18236             for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
18237                 var includeBasePath = includeBasePaths_1[_a];
18238                 _loop_2(includeBasePath);
18239             }
18240         }
18241         return basePaths;
18242     }
18243     function getIncludeBasePath(absolute) {
18244         var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
18245         if (wildcardOffset < 0) {
18246             // No "*" or "?" in the path
18247             return !ts.hasExtension(absolute)
18248                 ? absolute
18249                 : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
18250         }
18251         return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
18252     }
18253     function ensureScriptKind(fileName, scriptKind) {
18254         // Using scriptKind as a condition handles both:
18255         // - 'scriptKind' is unspecified and thus it is `undefined`
18256         // - 'scriptKind' is set and it is `Unknown` (0)
18257         // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
18258         // to get the ScriptKind from the file name. If it cannot be resolved
18259         // from the file name then the default 'TS' script kind is returned.
18260         return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
18261     }
18262     ts.ensureScriptKind = ensureScriptKind;
18263     function getScriptKindFromFileName(fileName) {
18264         var ext = fileName.substr(fileName.lastIndexOf("."));
18265         switch (ext.toLowerCase()) {
18266             case ".js" /* Js */:
18267                 return 1 /* JS */;
18268             case ".jsx" /* Jsx */:
18269                 return 2 /* JSX */;
18270             case ".ts" /* Ts */:
18271                 return 3 /* TS */;
18272             case ".tsx" /* Tsx */:
18273                 return 4 /* TSX */;
18274             case ".json" /* Json */:
18275                 return 6 /* JSON */;
18276             default:
18277                 return 0 /* Unknown */;
18278         }
18279     }
18280     ts.getScriptKindFromFileName = getScriptKindFromFileName;
18281     /**
18282      *  List of supported extensions in order of file resolution precedence.
18283      */
18284     ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
18285     ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
18286     /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
18287     ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
18288     ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
18289     ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
18290     var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
18291     var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
18292     function getSupportedExtensions(options, extraFileExtensions) {
18293         var needJsExtensions = options && options.allowJs;
18294         if (!extraFileExtensions || extraFileExtensions.length === 0) {
18295             return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
18296         }
18297         var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
18298         return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
18299     }
18300     ts.getSupportedExtensions = getSupportedExtensions;
18301     function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
18302         if (!options || !options.resolveJsonModule) {
18303             return supportedExtensions;
18304         }
18305         if (supportedExtensions === allSupportedExtensions) {
18306             return allSupportedExtensionsWithJson;
18307         }
18308         if (supportedExtensions === ts.supportedTSExtensions) {
18309             return ts.supportedTSExtensionsWithJson;
18310         }
18311         return __spreadArrays(supportedExtensions, [".json" /* Json */]);
18312     }
18313     ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
18314     function isJSLike(scriptKind) {
18315         return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
18316     }
18317     function hasJSFileExtension(fileName) {
18318         return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18319     }
18320     ts.hasJSFileExtension = hasJSFileExtension;
18321     function hasTSFileExtension(fileName) {
18322         return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18323     }
18324     ts.hasTSFileExtension = hasTSFileExtension;
18325     function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
18326         if (!fileName) {
18327             return false;
18328         }
18329         var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
18330         for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
18331             var extension = _a[_i];
18332             if (ts.fileExtensionIs(fileName, extension)) {
18333                 return true;
18334             }
18335         }
18336         return false;
18337     }
18338     ts.isSupportedSourceFileName = isSupportedSourceFileName;
18339     /**
18340      * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
18341      * aligned to the offset of the highest priority extension in the
18342      * allSupportedExtensions array.
18343      */
18344     var ExtensionPriority;
18345     (function (ExtensionPriority) {
18346         ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
18347         ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
18348         ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
18349         ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
18350     })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
18351     function getExtensionPriority(path, supportedExtensions) {
18352         for (var i = supportedExtensions.length - 1; i >= 0; i--) {
18353             if (ts.fileExtensionIs(path, supportedExtensions[i])) {
18354                 return adjustExtensionPriority(i, supportedExtensions);
18355             }
18356         }
18357         // If its not in the list of supported extensions, this is likely a
18358         // TypeScript file with a non-ts extension
18359         return 0 /* Highest */;
18360     }
18361     ts.getExtensionPriority = getExtensionPriority;
18362     /**
18363      * Adjusts an extension priority to be the highest priority within the same range.
18364      */
18365     function adjustExtensionPriority(extensionPriority, supportedExtensions) {
18366         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18367             return 0 /* TypeScriptFiles */;
18368         }
18369         else if (extensionPriority < supportedExtensions.length) {
18370             return 2 /* DeclarationAndJavaScriptFiles */;
18371         }
18372         else {
18373             return supportedExtensions.length;
18374         }
18375     }
18376     ts.adjustExtensionPriority = adjustExtensionPriority;
18377     /**
18378      * Gets the next lowest extension priority for a given priority.
18379      */
18380     function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
18381         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18382             return 2 /* DeclarationAndJavaScriptFiles */;
18383         }
18384         else {
18385             return supportedExtensions.length;
18386         }
18387     }
18388     ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
18389     var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
18390     function removeFileExtension(path) {
18391         for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
18392             var ext = extensionsToRemove_1[_i];
18393             var extensionless = tryRemoveExtension(path, ext);
18394             if (extensionless !== undefined) {
18395                 return extensionless;
18396             }
18397         }
18398         return path;
18399     }
18400     ts.removeFileExtension = removeFileExtension;
18401     function tryRemoveExtension(path, extension) {
18402         return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
18403     }
18404     ts.tryRemoveExtension = tryRemoveExtension;
18405     function removeExtension(path, extension) {
18406         return path.substring(0, path.length - extension.length);
18407     }
18408     ts.removeExtension = removeExtension;
18409     function changeExtension(path, newExtension) {
18410         return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
18411     }
18412     ts.changeExtension = changeExtension;
18413     function tryParsePattern(pattern) {
18414         // This should be verified outside of here and a proper error thrown.
18415         ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
18416         var indexOfStar = pattern.indexOf("*");
18417         return indexOfStar === -1 ? undefined : {
18418             prefix: pattern.substr(0, indexOfStar),
18419             suffix: pattern.substr(indexOfStar + 1)
18420         };
18421     }
18422     ts.tryParsePattern = tryParsePattern;
18423     function positionIsSynthesized(pos) {
18424         // This is a fast way of testing the following conditions:
18425         //  pos === undefined || pos === null || isNaN(pos) || pos < 0;
18426         return !(pos >= 0);
18427     }
18428     ts.positionIsSynthesized = positionIsSynthesized;
18429     /** True if an extension is one of the supported TypeScript extensions. */
18430     function extensionIsTS(ext) {
18431         return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
18432     }
18433     ts.extensionIsTS = extensionIsTS;
18434     function resolutionExtensionIsTSOrJson(ext) {
18435         return extensionIsTS(ext) || ext === ".json" /* Json */;
18436     }
18437     ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
18438     /**
18439      * Gets the extension from a path.
18440      * Path must have a valid extension.
18441      */
18442     function extensionFromPath(path) {
18443         var ext = tryGetExtensionFromPath(path);
18444         return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
18445     }
18446     ts.extensionFromPath = extensionFromPath;
18447     function isAnySupportedFileExtension(path) {
18448         return tryGetExtensionFromPath(path) !== undefined;
18449     }
18450     ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
18451     function tryGetExtensionFromPath(path) {
18452         return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
18453     }
18454     ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
18455     function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
18456         return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
18457     }
18458     ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
18459     ts.emptyFileSystemEntries = {
18460         files: ts.emptyArray,
18461         directories: ts.emptyArray
18462     };
18463     /**
18464      * patternStrings contains both pattern strings (containing "*") and regular strings.
18465      * Return an exact match if possible, or a pattern match, or undefined.
18466      * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
18467      */
18468     function matchPatternOrExact(patternStrings, candidate) {
18469         var patterns = [];
18470         for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
18471             var patternString = patternStrings_1[_i];
18472             if (!hasZeroOrOneAsteriskCharacter(patternString))
18473                 continue;
18474             var pattern = tryParsePattern(patternString);
18475             if (pattern) {
18476                 patterns.push(pattern);
18477             }
18478             else if (patternString === candidate) {
18479                 // pattern was matched as is - no need to search further
18480                 return patternString;
18481             }
18482         }
18483         return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
18484     }
18485     ts.matchPatternOrExact = matchPatternOrExact;
18486     function sliceAfter(arr, value) {
18487         var index = arr.indexOf(value);
18488         ts.Debug.assert(index !== -1);
18489         return arr.slice(index);
18490     }
18491     ts.sliceAfter = sliceAfter;
18492     function addRelatedInfo(diagnostic) {
18493         var _a;
18494         var relatedInformation = [];
18495         for (var _i = 1; _i < arguments.length; _i++) {
18496             relatedInformation[_i - 1] = arguments[_i];
18497         }
18498         if (!relatedInformation.length) {
18499             return diagnostic;
18500         }
18501         if (!diagnostic.relatedInformation) {
18502             diagnostic.relatedInformation = [];
18503         }
18504         (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
18505         return diagnostic;
18506     }
18507     ts.addRelatedInfo = addRelatedInfo;
18508     function minAndMax(arr, getValue) {
18509         ts.Debug.assert(arr.length !== 0);
18510         var min = getValue(arr[0]);
18511         var max = min;
18512         for (var i = 1; i < arr.length; i++) {
18513             var value = getValue(arr[i]);
18514             if (value < min) {
18515                 min = value;
18516             }
18517             else if (value > max) {
18518                 max = value;
18519             }
18520         }
18521         return { min: min, max: max };
18522     }
18523     ts.minAndMax = minAndMax;
18524     var NodeSet = /** @class */ (function () {
18525         function NodeSet() {
18526             this.map = ts.createMap();
18527         }
18528         NodeSet.prototype.add = function (node) {
18529             this.map.set(String(ts.getNodeId(node)), node);
18530         };
18531         NodeSet.prototype.tryAdd = function (node) {
18532             if (this.has(node))
18533                 return false;
18534             this.add(node);
18535             return true;
18536         };
18537         NodeSet.prototype.has = function (node) {
18538             return this.map.has(String(ts.getNodeId(node)));
18539         };
18540         NodeSet.prototype.forEach = function (cb) {
18541             this.map.forEach(cb);
18542         };
18543         NodeSet.prototype.some = function (pred) {
18544             return forEachEntry(this.map, pred) || false;
18545         };
18546         return NodeSet;
18547     }());
18548     ts.NodeSet = NodeSet;
18549     var NodeMap = /** @class */ (function () {
18550         function NodeMap() {
18551             this.map = ts.createMap();
18552         }
18553         NodeMap.prototype.get = function (node) {
18554             var res = this.map.get(String(ts.getNodeId(node)));
18555             return res && res.value;
18556         };
18557         NodeMap.prototype.getOrUpdate = function (node, setValue) {
18558             var res = this.get(node);
18559             if (res)
18560                 return res;
18561             var value = setValue();
18562             this.set(node, value);
18563             return value;
18564         };
18565         NodeMap.prototype.set = function (node, value) {
18566             this.map.set(String(ts.getNodeId(node)), { node: node, value: value });
18567         };
18568         NodeMap.prototype.has = function (node) {
18569             return this.map.has(String(ts.getNodeId(node)));
18570         };
18571         NodeMap.prototype.forEach = function (cb) {
18572             this.map.forEach(function (_a) {
18573                 var node = _a.node, value = _a.value;
18574                 return cb(value, node);
18575             });
18576         };
18577         return NodeMap;
18578     }());
18579     ts.NodeMap = NodeMap;
18580     function rangeOfNode(node) {
18581         return { pos: getTokenPosOfNode(node), end: node.end };
18582     }
18583     ts.rangeOfNode = rangeOfNode;
18584     function rangeOfTypeParameters(typeParameters) {
18585         // Include the `<>`
18586         return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
18587     }
18588     ts.rangeOfTypeParameters = rangeOfTypeParameters;
18589     function skipTypeChecking(sourceFile, options, host) {
18590         // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
18591         // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
18592         // '/// <reference no-default-lib="true"/>' directive.
18593         return (options.skipLibCheck && sourceFile.isDeclarationFile ||
18594             options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
18595             host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
18596     }
18597     ts.skipTypeChecking = skipTypeChecking;
18598     function isJsonEqual(a, b) {
18599         // eslint-disable-next-line no-null/no-null
18600         return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
18601     }
18602     ts.isJsonEqual = isJsonEqual;
18603     function getOrUpdate(map, key, getDefault) {
18604         var got = map.get(key);
18605         if (got === undefined) {
18606             var value = getDefault();
18607             map.set(key, value);
18608             return value;
18609         }
18610         else {
18611             return got;
18612         }
18613     }
18614     ts.getOrUpdate = getOrUpdate;
18615     /**
18616      * Converts a bigint literal string, e.g. `0x1234n`,
18617      * to its decimal string representation, e.g. `4660`.
18618      */
18619     function parsePseudoBigInt(stringValue) {
18620         var log2Base;
18621         switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
18622             case 98 /* b */:
18623             case 66 /* B */: // 0b or 0B
18624                 log2Base = 1;
18625                 break;
18626             case 111 /* o */:
18627             case 79 /* O */: // 0o or 0O
18628                 log2Base = 3;
18629                 break;
18630             case 120 /* x */:
18631             case 88 /* X */: // 0x or 0X
18632                 log2Base = 4;
18633                 break;
18634             default: // already in decimal; omit trailing "n"
18635                 var nIndex = stringValue.length - 1;
18636                 // Skip leading 0s
18637                 var nonZeroStart = 0;
18638                 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
18639                     nonZeroStart++;
18640                 }
18641                 return stringValue.slice(nonZeroStart, nIndex) || "0";
18642         }
18643         // Omit leading "0b", "0o", or "0x", and trailing "n"
18644         var startIndex = 2, endIndex = stringValue.length - 1;
18645         var bitsNeeded = (endIndex - startIndex) * log2Base;
18646         // Stores the value specified by the string as a LE array of 16-bit integers
18647         // using Uint16 instead of Uint32 so combining steps can use bitwise operators
18648         var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
18649         // Add the digits, one at a time
18650         for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
18651             var segment = bitOffset >>> 4;
18652             var digitChar = stringValue.charCodeAt(i);
18653             // Find character range: 0-9 < A-F < a-f
18654             var digit = digitChar <= 57 /* _9 */
18655                 ? digitChar - 48 /* _0 */
18656                 : 10 + digitChar -
18657                     (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
18658             var shiftedDigit = digit << (bitOffset & 15);
18659             segments[segment] |= shiftedDigit;
18660             var residual = shiftedDigit >>> 16;
18661             if (residual)
18662                 segments[segment + 1] |= residual; // overflows segment
18663         }
18664         // Repeatedly divide segments by 10 and add remainder to base10Value
18665         var base10Value = "";
18666         var firstNonzeroSegment = segments.length - 1;
18667         var segmentsRemaining = true;
18668         while (segmentsRemaining) {
18669             var mod10 = 0;
18670             segmentsRemaining = false;
18671             for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
18672                 var newSegment = mod10 << 16 | segments[segment];
18673                 var segmentValue = (newSegment / 10) | 0;
18674                 segments[segment] = segmentValue;
18675                 mod10 = newSegment - segmentValue * 10;
18676                 if (segmentValue && !segmentsRemaining) {
18677                     firstNonzeroSegment = segment;
18678                     segmentsRemaining = true;
18679                 }
18680             }
18681             base10Value = mod10 + base10Value;
18682         }
18683         return base10Value;
18684     }
18685     ts.parsePseudoBigInt = parsePseudoBigInt;
18686     function pseudoBigIntToString(_a) {
18687         var negative = _a.negative, base10Value = _a.base10Value;
18688         return (negative && base10Value !== "0" ? "-" : "") + base10Value;
18689     }
18690     ts.pseudoBigIntToString = pseudoBigIntToString;
18691     function isValidTypeOnlyAliasUseSite(useSite) {
18692         return !!(useSite.flags & 8388608 /* Ambient */)
18693             || isPartOfTypeQuery(useSite)
18694             || isIdentifierInNonEmittingHeritageClause(useSite)
18695             || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
18696             || !isExpressionNode(useSite);
18697     }
18698     ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
18699     function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
18700         return typeOnlyDeclaration.kind === 263 /* ExportSpecifier */;
18701     }
18702     ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
18703     function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
18704         while (node.kind === 75 /* Identifier */ || node.kind === 194 /* PropertyAccessExpression */) {
18705             node = node.parent;
18706         }
18707         if (node.kind !== 154 /* ComputedPropertyName */) {
18708             return false;
18709         }
18710         if (hasModifier(node.parent, 128 /* Abstract */)) {
18711             return true;
18712         }
18713         var containerKind = node.parent.parent.kind;
18714         return containerKind === 246 /* InterfaceDeclaration */ || containerKind === 173 /* TypeLiteral */;
18715     }
18716     /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
18717     function isIdentifierInNonEmittingHeritageClause(node) {
18718         if (node.kind !== 75 /* Identifier */)
18719             return false;
18720         var heritageClause = findAncestor(node.parent, function (parent) {
18721             switch (parent.kind) {
18722                 case 279 /* HeritageClause */:
18723                     return true;
18724                 case 194 /* PropertyAccessExpression */:
18725                 case 216 /* ExpressionWithTypeArguments */:
18726                     return false;
18727                 default:
18728                     return "quit";
18729             }
18730         });
18731         return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */;
18732     }
18733     function isIdentifierTypeReference(node) {
18734         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
18735     }
18736     ts.isIdentifierTypeReference = isIdentifierTypeReference;
18737     function arrayIsHomogeneous(array, comparer) {
18738         if (comparer === void 0) { comparer = ts.equateValues; }
18739         if (array.length < 2)
18740             return true;
18741         var first = array[0];
18742         for (var i = 1, length_1 = array.length; i < length_1; i++) {
18743             var target = array[i];
18744             if (!comparer(first, target))
18745                 return false;
18746         }
18747         return true;
18748     }
18749     ts.arrayIsHomogeneous = arrayIsHomogeneous;
18750 })(ts || (ts = {}));
18751 var ts;
18752 (function (ts) {
18753     var SignatureFlags;
18754     (function (SignatureFlags) {
18755         SignatureFlags[SignatureFlags["None"] = 0] = "None";
18756         SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
18757         SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
18758         SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
18759         SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
18760         SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
18761     })(SignatureFlags || (SignatureFlags = {}));
18762     var NodeConstructor;
18763     var TokenConstructor;
18764     var IdentifierConstructor;
18765     var PrivateIdentifierConstructor;
18766     var SourceFileConstructor;
18767     function createNode(kind, pos, end) {
18768         if (kind === 290 /* SourceFile */) {
18769             return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
18770         }
18771         else if (kind === 75 /* Identifier */) {
18772             return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
18773         }
18774         else if (kind === 76 /* PrivateIdentifier */) {
18775             return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, pos, end);
18776         }
18777         else if (!ts.isNodeKind(kind)) {
18778             return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
18779         }
18780         else {
18781             return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
18782         }
18783     }
18784     ts.createNode = createNode;
18785     function visitNode(cbNode, node) {
18786         return node && cbNode(node);
18787     }
18788     function visitNodes(cbNode, cbNodes, nodes) {
18789         if (nodes) {
18790             if (cbNodes) {
18791                 return cbNodes(nodes);
18792             }
18793             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
18794                 var node = nodes_1[_i];
18795                 var result = cbNode(node);
18796                 if (result) {
18797                     return result;
18798                 }
18799             }
18800         }
18801     }
18802     /*@internal*/
18803     function isJSDocLikeText(text, start) {
18804         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
18805             text.charCodeAt(start + 2) === 42 /* asterisk */ &&
18806             text.charCodeAt(start + 3) !== 47 /* slash */;
18807     }
18808     ts.isJSDocLikeText = isJSDocLikeText;
18809     /**
18810      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
18811      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
18812      * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
18813      * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
18814      *
18815      * @param node a given node to visit its children
18816      * @param cbNode a callback to be invoked for all child nodes
18817      * @param cbNodes a callback to be invoked for embedded array
18818      *
18819      * @remarks `forEachChild` must visit the children of a node in the order
18820      * that they appear in the source code. The language service depends on this property to locate nodes by position.
18821      */
18822     function forEachChild(node, cbNode, cbNodes) {
18823         if (!node || node.kind <= 152 /* LastToken */) {
18824             return;
18825         }
18826         switch (node.kind) {
18827             case 153 /* QualifiedName */:
18828                 return visitNode(cbNode, node.left) ||
18829                     visitNode(cbNode, node.right);
18830             case 155 /* TypeParameter */:
18831                 return visitNode(cbNode, node.name) ||
18832                     visitNode(cbNode, node.constraint) ||
18833                     visitNode(cbNode, node.default) ||
18834                     visitNode(cbNode, node.expression);
18835             case 282 /* ShorthandPropertyAssignment */:
18836                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18837                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18838                     visitNode(cbNode, node.name) ||
18839                     visitNode(cbNode, node.questionToken) ||
18840                     visitNode(cbNode, node.exclamationToken) ||
18841                     visitNode(cbNode, node.equalsToken) ||
18842                     visitNode(cbNode, node.objectAssignmentInitializer);
18843             case 283 /* SpreadAssignment */:
18844                 return visitNode(cbNode, node.expression);
18845             case 156 /* Parameter */:
18846                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18847                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18848                     visitNode(cbNode, node.dotDotDotToken) ||
18849                     visitNode(cbNode, node.name) ||
18850                     visitNode(cbNode, node.questionToken) ||
18851                     visitNode(cbNode, node.type) ||
18852                     visitNode(cbNode, node.initializer);
18853             case 159 /* PropertyDeclaration */:
18854                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18855                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18856                     visitNode(cbNode, node.name) ||
18857                     visitNode(cbNode, node.questionToken) ||
18858                     visitNode(cbNode, node.exclamationToken) ||
18859                     visitNode(cbNode, node.type) ||
18860                     visitNode(cbNode, node.initializer);
18861             case 158 /* PropertySignature */:
18862                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18863                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18864                     visitNode(cbNode, node.name) ||
18865                     visitNode(cbNode, node.questionToken) ||
18866                     visitNode(cbNode, node.type) ||
18867                     visitNode(cbNode, node.initializer);
18868             case 281 /* PropertyAssignment */:
18869                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18870                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18871                     visitNode(cbNode, node.name) ||
18872                     visitNode(cbNode, node.questionToken) ||
18873                     visitNode(cbNode, node.initializer);
18874             case 242 /* VariableDeclaration */:
18875                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18876                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18877                     visitNode(cbNode, node.name) ||
18878                     visitNode(cbNode, node.exclamationToken) ||
18879                     visitNode(cbNode, node.type) ||
18880                     visitNode(cbNode, node.initializer);
18881             case 191 /* BindingElement */:
18882                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18883                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18884                     visitNode(cbNode, node.dotDotDotToken) ||
18885                     visitNode(cbNode, node.propertyName) ||
18886                     visitNode(cbNode, node.name) ||
18887                     visitNode(cbNode, node.initializer);
18888             case 170 /* FunctionType */:
18889             case 171 /* ConstructorType */:
18890             case 165 /* CallSignature */:
18891             case 166 /* ConstructSignature */:
18892             case 167 /* IndexSignature */:
18893                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18894                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18895                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
18896                     visitNodes(cbNode, cbNodes, node.parameters) ||
18897                     visitNode(cbNode, node.type);
18898             case 161 /* MethodDeclaration */:
18899             case 160 /* MethodSignature */:
18900             case 162 /* Constructor */:
18901             case 163 /* GetAccessor */:
18902             case 164 /* SetAccessor */:
18903             case 201 /* FunctionExpression */:
18904             case 244 /* FunctionDeclaration */:
18905             case 202 /* ArrowFunction */:
18906                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18907                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18908                     visitNode(cbNode, node.asteriskToken) ||
18909                     visitNode(cbNode, node.name) ||
18910                     visitNode(cbNode, node.questionToken) ||
18911                     visitNode(cbNode, node.exclamationToken) ||
18912                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
18913                     visitNodes(cbNode, cbNodes, node.parameters) ||
18914                     visitNode(cbNode, node.type) ||
18915                     visitNode(cbNode, node.equalsGreaterThanToken) ||
18916                     visitNode(cbNode, node.body);
18917             case 169 /* TypeReference */:
18918                 return visitNode(cbNode, node.typeName) ||
18919                     visitNodes(cbNode, cbNodes, node.typeArguments);
18920             case 168 /* TypePredicate */:
18921                 return visitNode(cbNode, node.assertsModifier) ||
18922                     visitNode(cbNode, node.parameterName) ||
18923                     visitNode(cbNode, node.type);
18924             case 172 /* TypeQuery */:
18925                 return visitNode(cbNode, node.exprName);
18926             case 173 /* TypeLiteral */:
18927                 return visitNodes(cbNode, cbNodes, node.members);
18928             case 174 /* ArrayType */:
18929                 return visitNode(cbNode, node.elementType);
18930             case 175 /* TupleType */:
18931                 return visitNodes(cbNode, cbNodes, node.elementTypes);
18932             case 178 /* UnionType */:
18933             case 179 /* IntersectionType */:
18934                 return visitNodes(cbNode, cbNodes, node.types);
18935             case 180 /* ConditionalType */:
18936                 return visitNode(cbNode, node.checkType) ||
18937                     visitNode(cbNode, node.extendsType) ||
18938                     visitNode(cbNode, node.trueType) ||
18939                     visitNode(cbNode, node.falseType);
18940             case 181 /* InferType */:
18941                 return visitNode(cbNode, node.typeParameter);
18942             case 188 /* ImportType */:
18943                 return visitNode(cbNode, node.argument) ||
18944                     visitNode(cbNode, node.qualifier) ||
18945                     visitNodes(cbNode, cbNodes, node.typeArguments);
18946             case 182 /* ParenthesizedType */:
18947             case 184 /* TypeOperator */:
18948                 return visitNode(cbNode, node.type);
18949             case 185 /* IndexedAccessType */:
18950                 return visitNode(cbNode, node.objectType) ||
18951                     visitNode(cbNode, node.indexType);
18952             case 186 /* MappedType */:
18953                 return visitNode(cbNode, node.readonlyToken) ||
18954                     visitNode(cbNode, node.typeParameter) ||
18955                     visitNode(cbNode, node.questionToken) ||
18956                     visitNode(cbNode, node.type);
18957             case 187 /* LiteralType */:
18958                 return visitNode(cbNode, node.literal);
18959             case 189 /* ObjectBindingPattern */:
18960             case 190 /* ArrayBindingPattern */:
18961                 return visitNodes(cbNode, cbNodes, node.elements);
18962             case 192 /* ArrayLiteralExpression */:
18963                 return visitNodes(cbNode, cbNodes, node.elements);
18964             case 193 /* ObjectLiteralExpression */:
18965                 return visitNodes(cbNode, cbNodes, node.properties);
18966             case 194 /* PropertyAccessExpression */:
18967                 return visitNode(cbNode, node.expression) ||
18968                     visitNode(cbNode, node.questionDotToken) ||
18969                     visitNode(cbNode, node.name);
18970             case 195 /* ElementAccessExpression */:
18971                 return visitNode(cbNode, node.expression) ||
18972                     visitNode(cbNode, node.questionDotToken) ||
18973                     visitNode(cbNode, node.argumentExpression);
18974             case 196 /* CallExpression */:
18975             case 197 /* NewExpression */:
18976                 return visitNode(cbNode, node.expression) ||
18977                     visitNode(cbNode, node.questionDotToken) ||
18978                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
18979                     visitNodes(cbNode, cbNodes, node.arguments);
18980             case 198 /* TaggedTemplateExpression */:
18981                 return visitNode(cbNode, node.tag) ||
18982                     visitNode(cbNode, node.questionDotToken) ||
18983                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
18984                     visitNode(cbNode, node.template);
18985             case 199 /* TypeAssertionExpression */:
18986                 return visitNode(cbNode, node.type) ||
18987                     visitNode(cbNode, node.expression);
18988             case 200 /* ParenthesizedExpression */:
18989                 return visitNode(cbNode, node.expression);
18990             case 203 /* DeleteExpression */:
18991                 return visitNode(cbNode, node.expression);
18992             case 204 /* TypeOfExpression */:
18993                 return visitNode(cbNode, node.expression);
18994             case 205 /* VoidExpression */:
18995                 return visitNode(cbNode, node.expression);
18996             case 207 /* PrefixUnaryExpression */:
18997                 return visitNode(cbNode, node.operand);
18998             case 212 /* YieldExpression */:
18999                 return visitNode(cbNode, node.asteriskToken) ||
19000                     visitNode(cbNode, node.expression);
19001             case 206 /* AwaitExpression */:
19002                 return visitNode(cbNode, node.expression);
19003             case 208 /* PostfixUnaryExpression */:
19004                 return visitNode(cbNode, node.operand);
19005             case 209 /* BinaryExpression */:
19006                 return visitNode(cbNode, node.left) ||
19007                     visitNode(cbNode, node.operatorToken) ||
19008                     visitNode(cbNode, node.right);
19009             case 217 /* AsExpression */:
19010                 return visitNode(cbNode, node.expression) ||
19011                     visitNode(cbNode, node.type);
19012             case 218 /* NonNullExpression */:
19013                 return visitNode(cbNode, node.expression);
19014             case 219 /* MetaProperty */:
19015                 return visitNode(cbNode, node.name);
19016             case 210 /* ConditionalExpression */:
19017                 return visitNode(cbNode, node.condition) ||
19018                     visitNode(cbNode, node.questionToken) ||
19019                     visitNode(cbNode, node.whenTrue) ||
19020                     visitNode(cbNode, node.colonToken) ||
19021                     visitNode(cbNode, node.whenFalse);
19022             case 213 /* SpreadElement */:
19023                 return visitNode(cbNode, node.expression);
19024             case 223 /* Block */:
19025             case 250 /* ModuleBlock */:
19026                 return visitNodes(cbNode, cbNodes, node.statements);
19027             case 290 /* SourceFile */:
19028                 return visitNodes(cbNode, cbNodes, node.statements) ||
19029                     visitNode(cbNode, node.endOfFileToken);
19030             case 225 /* VariableStatement */:
19031                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19032                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19033                     visitNode(cbNode, node.declarationList);
19034             case 243 /* VariableDeclarationList */:
19035                 return visitNodes(cbNode, cbNodes, node.declarations);
19036             case 226 /* ExpressionStatement */:
19037                 return visitNode(cbNode, node.expression);
19038             case 227 /* IfStatement */:
19039                 return visitNode(cbNode, node.expression) ||
19040                     visitNode(cbNode, node.thenStatement) ||
19041                     visitNode(cbNode, node.elseStatement);
19042             case 228 /* DoStatement */:
19043                 return visitNode(cbNode, node.statement) ||
19044                     visitNode(cbNode, node.expression);
19045             case 229 /* WhileStatement */:
19046                 return visitNode(cbNode, node.expression) ||
19047                     visitNode(cbNode, node.statement);
19048             case 230 /* ForStatement */:
19049                 return visitNode(cbNode, node.initializer) ||
19050                     visitNode(cbNode, node.condition) ||
19051                     visitNode(cbNode, node.incrementor) ||
19052                     visitNode(cbNode, node.statement);
19053             case 231 /* ForInStatement */:
19054                 return visitNode(cbNode, node.initializer) ||
19055                     visitNode(cbNode, node.expression) ||
19056                     visitNode(cbNode, node.statement);
19057             case 232 /* ForOfStatement */:
19058                 return visitNode(cbNode, node.awaitModifier) ||
19059                     visitNode(cbNode, node.initializer) ||
19060                     visitNode(cbNode, node.expression) ||
19061                     visitNode(cbNode, node.statement);
19062             case 233 /* ContinueStatement */:
19063             case 234 /* BreakStatement */:
19064                 return visitNode(cbNode, node.label);
19065             case 235 /* ReturnStatement */:
19066                 return visitNode(cbNode, node.expression);
19067             case 236 /* WithStatement */:
19068                 return visitNode(cbNode, node.expression) ||
19069                     visitNode(cbNode, node.statement);
19070             case 237 /* SwitchStatement */:
19071                 return visitNode(cbNode, node.expression) ||
19072                     visitNode(cbNode, node.caseBlock);
19073             case 251 /* CaseBlock */:
19074                 return visitNodes(cbNode, cbNodes, node.clauses);
19075             case 277 /* CaseClause */:
19076                 return visitNode(cbNode, node.expression) ||
19077                     visitNodes(cbNode, cbNodes, node.statements);
19078             case 278 /* DefaultClause */:
19079                 return visitNodes(cbNode, cbNodes, node.statements);
19080             case 238 /* LabeledStatement */:
19081                 return visitNode(cbNode, node.label) ||
19082                     visitNode(cbNode, node.statement);
19083             case 239 /* ThrowStatement */:
19084                 return visitNode(cbNode, node.expression);
19085             case 240 /* TryStatement */:
19086                 return visitNode(cbNode, node.tryBlock) ||
19087                     visitNode(cbNode, node.catchClause) ||
19088                     visitNode(cbNode, node.finallyBlock);
19089             case 280 /* CatchClause */:
19090                 return visitNode(cbNode, node.variableDeclaration) ||
19091                     visitNode(cbNode, node.block);
19092             case 157 /* Decorator */:
19093                 return visitNode(cbNode, node.expression);
19094             case 245 /* ClassDeclaration */:
19095             case 214 /* ClassExpression */:
19096                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19097                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19098                     visitNode(cbNode, node.name) ||
19099                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19100                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19101                     visitNodes(cbNode, cbNodes, node.members);
19102             case 246 /* InterfaceDeclaration */:
19103                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19104                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19105                     visitNode(cbNode, node.name) ||
19106                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19107                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19108                     visitNodes(cbNode, cbNodes, node.members);
19109             case 247 /* TypeAliasDeclaration */:
19110                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19111                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19112                     visitNode(cbNode, node.name) ||
19113                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19114                     visitNode(cbNode, node.type);
19115             case 248 /* EnumDeclaration */:
19116                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19117                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19118                     visitNode(cbNode, node.name) ||
19119                     visitNodes(cbNode, cbNodes, node.members);
19120             case 284 /* EnumMember */:
19121                 return visitNode(cbNode, node.name) ||
19122                     visitNode(cbNode, node.initializer);
19123             case 249 /* ModuleDeclaration */:
19124                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19125                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19126                     visitNode(cbNode, node.name) ||
19127                     visitNode(cbNode, node.body);
19128             case 253 /* ImportEqualsDeclaration */:
19129                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19130                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19131                     visitNode(cbNode, node.name) ||
19132                     visitNode(cbNode, node.moduleReference);
19133             case 254 /* ImportDeclaration */:
19134                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19135                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19136                     visitNode(cbNode, node.importClause) ||
19137                     visitNode(cbNode, node.moduleSpecifier);
19138             case 255 /* ImportClause */:
19139                 return visitNode(cbNode, node.name) ||
19140                     visitNode(cbNode, node.namedBindings);
19141             case 252 /* NamespaceExportDeclaration */:
19142                 return visitNode(cbNode, node.name);
19143             case 256 /* NamespaceImport */:
19144                 return visitNode(cbNode, node.name);
19145             case 262 /* NamespaceExport */:
19146                 return visitNode(cbNode, node.name);
19147             case 257 /* NamedImports */:
19148             case 261 /* NamedExports */:
19149                 return visitNodes(cbNode, cbNodes, node.elements);
19150             case 260 /* ExportDeclaration */:
19151                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19152                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19153                     visitNode(cbNode, node.exportClause) ||
19154                     visitNode(cbNode, node.moduleSpecifier);
19155             case 258 /* ImportSpecifier */:
19156             case 263 /* ExportSpecifier */:
19157                 return visitNode(cbNode, node.propertyName) ||
19158                     visitNode(cbNode, node.name);
19159             case 259 /* ExportAssignment */:
19160                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19161                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19162                     visitNode(cbNode, node.expression);
19163             case 211 /* TemplateExpression */:
19164                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
19165             case 221 /* TemplateSpan */:
19166                 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
19167             case 154 /* ComputedPropertyName */:
19168                 return visitNode(cbNode, node.expression);
19169             case 279 /* HeritageClause */:
19170                 return visitNodes(cbNode, cbNodes, node.types);
19171             case 216 /* ExpressionWithTypeArguments */:
19172                 return visitNode(cbNode, node.expression) ||
19173                     visitNodes(cbNode, cbNodes, node.typeArguments);
19174             case 265 /* ExternalModuleReference */:
19175                 return visitNode(cbNode, node.expression);
19176             case 264 /* MissingDeclaration */:
19177                 return visitNodes(cbNode, cbNodes, node.decorators);
19178             case 327 /* CommaListExpression */:
19179                 return visitNodes(cbNode, cbNodes, node.elements);
19180             case 266 /* JsxElement */:
19181                 return visitNode(cbNode, node.openingElement) ||
19182                     visitNodes(cbNode, cbNodes, node.children) ||
19183                     visitNode(cbNode, node.closingElement);
19184             case 270 /* JsxFragment */:
19185                 return visitNode(cbNode, node.openingFragment) ||
19186                     visitNodes(cbNode, cbNodes, node.children) ||
19187                     visitNode(cbNode, node.closingFragment);
19188             case 267 /* JsxSelfClosingElement */:
19189             case 268 /* JsxOpeningElement */:
19190                 return visitNode(cbNode, node.tagName) ||
19191                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
19192                     visitNode(cbNode, node.attributes);
19193             case 274 /* JsxAttributes */:
19194                 return visitNodes(cbNode, cbNodes, node.properties);
19195             case 273 /* JsxAttribute */:
19196                 return visitNode(cbNode, node.name) ||
19197                     visitNode(cbNode, node.initializer);
19198             case 275 /* JsxSpreadAttribute */:
19199                 return visitNode(cbNode, node.expression);
19200             case 276 /* JsxExpression */:
19201                 return visitNode(cbNode, node.dotDotDotToken) ||
19202                     visitNode(cbNode, node.expression);
19203             case 269 /* JsxClosingElement */:
19204                 return visitNode(cbNode, node.tagName);
19205             case 176 /* OptionalType */:
19206             case 177 /* RestType */:
19207             case 294 /* JSDocTypeExpression */:
19208             case 298 /* JSDocNonNullableType */:
19209             case 297 /* JSDocNullableType */:
19210             case 299 /* JSDocOptionalType */:
19211             case 301 /* JSDocVariadicType */:
19212                 return visitNode(cbNode, node.type);
19213             case 300 /* JSDocFunctionType */:
19214                 return visitNodes(cbNode, cbNodes, node.parameters) ||
19215                     visitNode(cbNode, node.type);
19216             case 303 /* JSDocComment */:
19217                 return visitNodes(cbNode, cbNodes, node.tags);
19218             case 317 /* JSDocParameterTag */:
19219             case 323 /* JSDocPropertyTag */:
19220                 return visitNode(cbNode, node.tagName) ||
19221                     (node.isNameFirst
19222                         ? visitNode(cbNode, node.name) ||
19223                             visitNode(cbNode, node.typeExpression)
19224                         : visitNode(cbNode, node.typeExpression) ||
19225                             visitNode(cbNode, node.name));
19226             case 309 /* JSDocAuthorTag */:
19227                 return visitNode(cbNode, node.tagName);
19228             case 308 /* JSDocImplementsTag */:
19229                 return visitNode(cbNode, node.tagName) ||
19230                     visitNode(cbNode, node.class);
19231             case 307 /* JSDocAugmentsTag */:
19232                 return visitNode(cbNode, node.tagName) ||
19233                     visitNode(cbNode, node.class);
19234             case 321 /* JSDocTemplateTag */:
19235                 return visitNode(cbNode, node.tagName) ||
19236                     visitNode(cbNode, node.constraint) ||
19237                     visitNodes(cbNode, cbNodes, node.typeParameters);
19238             case 322 /* JSDocTypedefTag */:
19239                 return visitNode(cbNode, node.tagName) ||
19240                     (node.typeExpression &&
19241                         node.typeExpression.kind === 294 /* JSDocTypeExpression */
19242                         ? visitNode(cbNode, node.typeExpression) ||
19243                             visitNode(cbNode, node.fullName)
19244                         : visitNode(cbNode, node.fullName) ||
19245                             visitNode(cbNode, node.typeExpression));
19246             case 315 /* JSDocCallbackTag */:
19247                 return visitNode(cbNode, node.tagName) ||
19248                     visitNode(cbNode, node.fullName) ||
19249                     visitNode(cbNode, node.typeExpression);
19250             case 318 /* JSDocReturnTag */:
19251             case 320 /* JSDocTypeTag */:
19252             case 319 /* JSDocThisTag */:
19253             case 316 /* JSDocEnumTag */:
19254                 return visitNode(cbNode, node.tagName) ||
19255                     visitNode(cbNode, node.typeExpression);
19256             case 305 /* JSDocSignature */:
19257                 return ts.forEach(node.typeParameters, cbNode) ||
19258                     ts.forEach(node.parameters, cbNode) ||
19259                     visitNode(cbNode, node.type);
19260             case 304 /* JSDocTypeLiteral */:
19261                 return ts.forEach(node.jsDocPropertyTags, cbNode);
19262             case 306 /* JSDocTag */:
19263             case 310 /* JSDocClassTag */:
19264             case 311 /* JSDocPublicTag */:
19265             case 312 /* JSDocPrivateTag */:
19266             case 313 /* JSDocProtectedTag */:
19267             case 314 /* JSDocReadonlyTag */:
19268                 return visitNode(cbNode, node.tagName);
19269             case 326 /* PartiallyEmittedExpression */:
19270                 return visitNode(cbNode, node.expression);
19271         }
19272     }
19273     ts.forEachChild = forEachChild;
19274     /** @internal */
19275     /**
19276      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
19277      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
19278      * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
19279      *  If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
19280      *
19281      * @param node a given node to visit its children
19282      * @param cbNode a callback to be invoked for all child nodes
19283      * @param cbNodes a callback to be invoked for embedded array
19284      *
19285      * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
19286      * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
19287      */
19288     function forEachChildRecursively(rootNode, cbNode, cbNodes) {
19289         var stack = [rootNode];
19290         while (stack.length) {
19291             var parent = stack.pop();
19292             var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent));
19293             if (res) {
19294                 return res;
19295             }
19296         }
19297         return;
19298         function gatherPossibleChildren(node) {
19299             var children = [];
19300             forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
19301             return children;
19302             function addWorkItem(n) {
19303                 children.unshift(n);
19304             }
19305         }
19306         function visitAllPossibleChildren(parent, children) {
19307             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
19308                 var child = children_1[_i];
19309                 if (ts.isArray(child)) {
19310                     if (cbNodes) {
19311                         var res = cbNodes(child, parent);
19312                         if (res) {
19313                             if (res === "skip")
19314                                 continue;
19315                             return res;
19316                         }
19317                     }
19318                     for (var i = child.length - 1; i >= 0; i--) {
19319                         var realChild = child[i];
19320                         var res = cbNode(realChild, parent);
19321                         if (res) {
19322                             if (res === "skip")
19323                                 continue;
19324                             return res;
19325                         }
19326                         stack.push(realChild);
19327                     }
19328                 }
19329                 else {
19330                     stack.push(child);
19331                     var res = cbNode(child, parent);
19332                     if (res) {
19333                         if (res === "skip")
19334                             continue;
19335                         return res;
19336                     }
19337                 }
19338             }
19339         }
19340     }
19341     ts.forEachChildRecursively = forEachChildRecursively;
19342     function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
19343         if (setParentNodes === void 0) { setParentNodes = false; }
19344         ts.performance.mark("beforeParse");
19345         var result;
19346         ts.perfLogger.logStartParseSourceFile(fileName);
19347         if (languageVersion === 100 /* JSON */) {
19348             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
19349         }
19350         else {
19351             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
19352         }
19353         ts.perfLogger.logStopParseSourceFile();
19354         ts.performance.mark("afterParse");
19355         ts.performance.measure("Parse", "beforeParse", "afterParse");
19356         return result;
19357     }
19358     ts.createSourceFile = createSourceFile;
19359     function parseIsolatedEntityName(text, languageVersion) {
19360         return Parser.parseIsolatedEntityName(text, languageVersion);
19361     }
19362     ts.parseIsolatedEntityName = parseIsolatedEntityName;
19363     /**
19364      * Parse json text into SyntaxTree and return node and parse errors if any
19365      * @param fileName
19366      * @param sourceText
19367      */
19368     function parseJsonText(fileName, sourceText) {
19369         return Parser.parseJsonText(fileName, sourceText);
19370     }
19371     ts.parseJsonText = parseJsonText;
19372     // See also `isExternalOrCommonJsModule` in utilities.ts
19373     function isExternalModule(file) {
19374         return file.externalModuleIndicator !== undefined;
19375     }
19376     ts.isExternalModule = isExternalModule;
19377     // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
19378     // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
19379     // The SourceFile will be created with the compiler attempting to reuse as many nodes from
19380     // this file as possible.
19381     //
19382     // Note: this function mutates nodes from this SourceFile. That means any existing nodes
19383     // from this SourceFile that are being held onto may change as a result (including
19384     // becoming detached from any SourceFile).  It is recommended that this SourceFile not
19385     // be used once 'update' is called on it.
19386     function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
19387         if (aggressiveChecks === void 0) { aggressiveChecks = false; }
19388         var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
19389         // 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.
19390         // We will manually port the flag to the new source file.
19391         newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
19392         return newSourceFile;
19393     }
19394     ts.updateSourceFile = updateSourceFile;
19395     /* @internal */
19396     function parseIsolatedJSDocComment(content, start, length) {
19397         var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
19398         if (result && result.jsDoc) {
19399             // because the jsDocComment was parsed out of the source file, it might
19400             // not be covered by the fixupParentReferences.
19401             Parser.fixupParentReferences(result.jsDoc);
19402         }
19403         return result;
19404     }
19405     ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
19406     /* @internal */
19407     // Exposed only for testing.
19408     function parseJSDocTypeExpressionForTests(content, start, length) {
19409         return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
19410     }
19411     ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
19412     // Implement the parser as a singleton module.  We do this for perf reasons because creating
19413     // parser instances can actually be expensive enough to impact us on projects with many source
19414     // files.
19415     var Parser;
19416     (function (Parser) {
19417         // Share a single scanner across all calls to parse a source file.  This helps speed things
19418         // up by avoiding the cost of creating/compiling scanners over and over again.
19419         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
19420         var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
19421         // capture constructors in 'initializeState' to avoid null checks
19422         var NodeConstructor;
19423         var TokenConstructor;
19424         var IdentifierConstructor;
19425         var PrivateIdentifierConstructor;
19426         var SourceFileConstructor;
19427         var sourceFile;
19428         var parseDiagnostics;
19429         var syntaxCursor;
19430         var currentToken;
19431         var sourceText;
19432         var nodeCount;
19433         var identifiers;
19434         var privateIdentifiers;
19435         var identifierCount;
19436         var parsingContext;
19437         var notParenthesizedArrow;
19438         // Flags that dictate what parsing context we're in.  For example:
19439         // Whether or not we are in strict parsing mode.  All that changes in strict parsing mode is
19440         // that some tokens that would be considered identifiers may be considered keywords.
19441         //
19442         // When adding more parser context flags, consider which is the more common case that the
19443         // flag will be in.  This should be the 'false' state for that flag.  The reason for this is
19444         // that we don't store data in our nodes unless the value is in the *non-default* state.  So,
19445         // for example, more often than code 'allows-in' (or doesn't 'disallow-in').  We opt for
19446         // 'disallow-in' set to 'false'.  Otherwise, if we had 'allowsIn' set to 'true', then almost
19447         // all nodes would need extra state on them to store this info.
19448         //
19449         // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
19450         // grammar specification.
19451         //
19452         // An important thing about these context concepts.  By default they are effectively inherited
19453         // while parsing through every grammar production.  i.e. if you don't change them, then when
19454         // you parse a sub-production, it will have the same context values as the parent production.
19455         // This is great most of the time.  After all, consider all the 'expression' grammar productions
19456         // and how nearly all of them pass along the 'in' and 'yield' context values:
19457         //
19458         // EqualityExpression[In, Yield] :
19459         //      RelationalExpression[?In, ?Yield]
19460         //      EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
19461         //      EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
19462         //      EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
19463         //      EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
19464         //
19465         // Where you have to be careful is then understanding what the points are in the grammar
19466         // where the values are *not* passed along.  For example:
19467         //
19468         // SingleNameBinding[Yield,GeneratorParameter]
19469         //      [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
19470         //      [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
19471         //
19472         // Here this is saying that if the GeneratorParameter context flag is set, that we should
19473         // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
19474         // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
19475         // production.  Conversely, if the GeneratorParameter context flag is not set, then we
19476         // should leave the 'yield' context flag alone.
19477         //
19478         // Getting this all correct is tricky and requires careful reading of the grammar to
19479         // understand when these values should be changed versus when they should be inherited.
19480         //
19481         // Note: it should not be necessary to save/restore these flags during speculative/lookahead
19482         // parsing.  These context flags are naturally stored and restored through normal recursive
19483         // descent parsing and unwinding.
19484         var contextFlags;
19485         // Whether or not we've had a parse error since creating the last AST node.  If we have
19486         // encountered an error, it will be stored on the next AST node we create.  Parse errors
19487         // can be broken down into three categories:
19488         //
19489         // 1) An error that occurred during scanning.  For example, an unterminated literal, or a
19490         //    character that was completely not understood.
19491         //
19492         // 2) A token was expected, but was not present.  This type of error is commonly produced
19493         //    by the 'parseExpected' function.
19494         //
19495         // 3) A token was present that no parsing function was able to consume.  This type of error
19496         //    only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
19497         //    decides to skip the token.
19498         //
19499         // In all of these cases, we want to mark the next node as having had an error before it.
19500         // With this mark, we can know in incremental settings if this node can be reused, or if
19501         // we have to reparse it.  If we don't keep this information around, we may just reuse the
19502         // node.  in that event we would then not produce the same errors as we did before, causing
19503         // significant confusion problems.
19504         //
19505         // Note: it is necessary that this value be saved/restored during speculative/lookahead
19506         // parsing.  During lookahead parsing, we will often create a node.  That node will have
19507         // this value attached, and then this value will be set back to 'false'.  If we decide to
19508         // rewind, we must get back to the same value we had prior to the lookahead.
19509         //
19510         // Note: any errors at the end of the file that do not precede a regular node, should get
19511         // attached to the EOF token.
19512         var parseErrorBeforeNextFinishedNode = false;
19513         function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
19514             if (setParentNodes === void 0) { setParentNodes = false; }
19515             scriptKind = ts.ensureScriptKind(fileName, scriptKind);
19516             if (scriptKind === 6 /* JSON */) {
19517                 var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
19518                 ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
19519                 result_2.referencedFiles = ts.emptyArray;
19520                 result_2.typeReferenceDirectives = ts.emptyArray;
19521                 result_2.libReferenceDirectives = ts.emptyArray;
19522                 result_2.amdDependencies = ts.emptyArray;
19523                 result_2.hasNoDefaultLib = false;
19524                 result_2.pragmas = ts.emptyMap;
19525                 return result_2;
19526             }
19527             initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
19528             var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
19529             clearState();
19530             return result;
19531         }
19532         Parser.parseSourceFile = parseSourceFile;
19533         function parseIsolatedEntityName(content, languageVersion) {
19534             // Choice of `isDeclarationFile` should be arbitrary
19535             initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
19536             // Prime the scanner.
19537             nextToken();
19538             var entityName = parseEntityName(/*allowReservedWords*/ true);
19539             var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
19540             clearState();
19541             return isInvalid ? entityName : undefined;
19542         }
19543         Parser.parseIsolatedEntityName = parseIsolatedEntityName;
19544         function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
19545             if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
19546             initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
19547             // Set source file so that errors will be reported with this file name
19548             sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
19549             sourceFile.flags = contextFlags;
19550             // Prime the scanner.
19551             nextToken();
19552             var pos = getNodePos();
19553             if (token() === 1 /* EndOfFileToken */) {
19554                 sourceFile.statements = createNodeArray([], pos, pos);
19555                 sourceFile.endOfFileToken = parseTokenNode();
19556             }
19557             else {
19558                 var statement = createNode(226 /* ExpressionStatement */);
19559                 switch (token()) {
19560                     case 22 /* OpenBracketToken */:
19561                         statement.expression = parseArrayLiteralExpression();
19562                         break;
19563                     case 106 /* TrueKeyword */:
19564                     case 91 /* FalseKeyword */:
19565                     case 100 /* NullKeyword */:
19566                         statement.expression = parseTokenNode();
19567                         break;
19568                     case 40 /* MinusToken */:
19569                         if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
19570                             statement.expression = parsePrefixUnaryExpression();
19571                         }
19572                         else {
19573                             statement.expression = parseObjectLiteralExpression();
19574                         }
19575                         break;
19576                     case 8 /* NumericLiteral */:
19577                     case 10 /* StringLiteral */:
19578                         if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
19579                             statement.expression = parseLiteralNode();
19580                             break;
19581                         }
19582                     // falls through
19583                     default:
19584                         statement.expression = parseObjectLiteralExpression();
19585                         break;
19586                 }
19587                 finishNode(statement);
19588                 sourceFile.statements = createNodeArray([statement], pos);
19589                 sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
19590             }
19591             if (setParentNodes) {
19592                 fixupParentReferences(sourceFile);
19593             }
19594             sourceFile.nodeCount = nodeCount;
19595             sourceFile.identifierCount = identifierCount;
19596             sourceFile.identifiers = identifiers;
19597             sourceFile.parseDiagnostics = parseDiagnostics;
19598             var result = sourceFile;
19599             clearState();
19600             return result;
19601         }
19602         Parser.parseJsonText = parseJsonText;
19603         function getLanguageVariant(scriptKind) {
19604             // .tsx and .jsx files are treated as jsx language variant.
19605             return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
19606         }
19607         function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) {
19608             NodeConstructor = ts.objectAllocator.getNodeConstructor();
19609             TokenConstructor = ts.objectAllocator.getTokenConstructor();
19610             IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
19611             PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
19612             SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
19613             sourceText = _sourceText;
19614             syntaxCursor = _syntaxCursor;
19615             parseDiagnostics = [];
19616             parsingContext = 0;
19617             identifiers = ts.createMap();
19618             privateIdentifiers = ts.createMap();
19619             identifierCount = 0;
19620             nodeCount = 0;
19621             switch (scriptKind) {
19622                 case 1 /* JS */:
19623                 case 2 /* JSX */:
19624                     contextFlags = 131072 /* JavaScriptFile */;
19625                     break;
19626                 case 6 /* JSON */:
19627                     contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
19628                     break;
19629                 default:
19630                     contextFlags = 0 /* None */;
19631                     break;
19632             }
19633             parseErrorBeforeNextFinishedNode = false;
19634             // Initialize and prime the scanner before parsing the source elements.
19635             scanner.setText(sourceText);
19636             scanner.setOnError(scanError);
19637             scanner.setScriptTarget(languageVersion);
19638             scanner.setLanguageVariant(getLanguageVariant(scriptKind));
19639         }
19640         function clearState() {
19641             // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
19642             scanner.clearCommentDirectives();
19643             scanner.setText("");
19644             scanner.setOnError(undefined);
19645             // Clear any data.  We don't want to accidentally hold onto it for too long.
19646             parseDiagnostics = undefined;
19647             sourceFile = undefined;
19648             identifiers = undefined;
19649             syntaxCursor = undefined;
19650             sourceText = undefined;
19651             notParenthesizedArrow = undefined;
19652         }
19653         function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) {
19654             var isDeclarationFile = isDeclarationFileName(fileName);
19655             if (isDeclarationFile) {
19656                 contextFlags |= 8388608 /* Ambient */;
19657             }
19658             sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
19659             sourceFile.flags = contextFlags;
19660             // Prime the scanner.
19661             nextToken();
19662             // 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
19663             processCommentPragmas(sourceFile, sourceText);
19664             processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
19665             sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
19666             ts.Debug.assert(token() === 1 /* EndOfFileToken */);
19667             sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
19668             setExternalModuleIndicator(sourceFile);
19669             sourceFile.commentDirectives = scanner.getCommentDirectives();
19670             sourceFile.nodeCount = nodeCount;
19671             sourceFile.identifierCount = identifierCount;
19672             sourceFile.identifiers = identifiers;
19673             sourceFile.parseDiagnostics = parseDiagnostics;
19674             if (setParentNodes) {
19675                 fixupParentReferences(sourceFile);
19676             }
19677             return sourceFile;
19678             function reportPragmaDiagnostic(pos, end, diagnostic) {
19679                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
19680             }
19681         }
19682         function addJSDocComment(node) {
19683             ts.Debug.assert(!node.jsDoc); // Should only be called once per node
19684             var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
19685             if (jsDoc.length)
19686                 node.jsDoc = jsDoc;
19687             return node;
19688         }
19689         function fixupParentReferences(rootNode) {
19690             // normally parent references are set during binding. However, for clients that only need
19691             // a syntax tree, and no semantic features, then the binding process is an unnecessary
19692             // overhead.  This functions allows us to set all the parents, without all the expense of
19693             // binding.
19694             forEachChildRecursively(rootNode, bindParentToChild);
19695             function bindParentToChild(child, parent) {
19696                 child.parent = parent;
19697                 if (ts.hasJSDocNodes(child)) {
19698                     for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
19699                         var doc = _a[_i];
19700                         bindParentToChild(doc, child);
19701                         forEachChildRecursively(doc, bindParentToChild);
19702                     }
19703                 }
19704             }
19705         }
19706         Parser.fixupParentReferences = fixupParentReferences;
19707         function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
19708             // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
19709             // this is quite rare comparing to other nodes and createNode should be as fast as possible
19710             var sourceFile = new SourceFileConstructor(290 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
19711             nodeCount++;
19712             sourceFile.text = sourceText;
19713             sourceFile.bindDiagnostics = [];
19714             sourceFile.bindSuggestionDiagnostics = undefined;
19715             sourceFile.languageVersion = languageVersion;
19716             sourceFile.fileName = ts.normalizePath(fileName);
19717             sourceFile.languageVariant = getLanguageVariant(scriptKind);
19718             sourceFile.isDeclarationFile = isDeclarationFile;
19719             sourceFile.scriptKind = scriptKind;
19720             return sourceFile;
19721         }
19722         function setContextFlag(val, flag) {
19723             if (val) {
19724                 contextFlags |= flag;
19725             }
19726             else {
19727                 contextFlags &= ~flag;
19728             }
19729         }
19730         function setDisallowInContext(val) {
19731             setContextFlag(val, 4096 /* DisallowInContext */);
19732         }
19733         function setYieldContext(val) {
19734             setContextFlag(val, 8192 /* YieldContext */);
19735         }
19736         function setDecoratorContext(val) {
19737             setContextFlag(val, 16384 /* DecoratorContext */);
19738         }
19739         function setAwaitContext(val) {
19740             setContextFlag(val, 32768 /* AwaitContext */);
19741         }
19742         function doOutsideOfContext(context, func) {
19743             // contextFlagsToClear will contain only the context flags that are
19744             // currently set that we need to temporarily clear
19745             // We don't just blindly reset to the previous flags to ensure
19746             // that we do not mutate cached flags for the incremental
19747             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19748             // HasAggregatedChildData).
19749             var contextFlagsToClear = context & contextFlags;
19750             if (contextFlagsToClear) {
19751                 // clear the requested context flags
19752                 setContextFlag(/*val*/ false, contextFlagsToClear);
19753                 var result = func();
19754                 // restore the context flags we just cleared
19755                 setContextFlag(/*val*/ true, contextFlagsToClear);
19756                 return result;
19757             }
19758             // no need to do anything special as we are not in any of the requested contexts
19759             return func();
19760         }
19761         function doInsideOfContext(context, func) {
19762             // contextFlagsToSet will contain only the context flags that
19763             // are not currently set that we need to temporarily enable.
19764             // We don't just blindly reset to the previous flags to ensure
19765             // that we do not mutate cached flags for the incremental
19766             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19767             // HasAggregatedChildData).
19768             var contextFlagsToSet = context & ~contextFlags;
19769             if (contextFlagsToSet) {
19770                 // set the requested context flags
19771                 setContextFlag(/*val*/ true, contextFlagsToSet);
19772                 var result = func();
19773                 // reset the context flags we just set
19774                 setContextFlag(/*val*/ false, contextFlagsToSet);
19775                 return result;
19776             }
19777             // no need to do anything special as we are already in all of the requested contexts
19778             return func();
19779         }
19780         function allowInAnd(func) {
19781             return doOutsideOfContext(4096 /* DisallowInContext */, func);
19782         }
19783         function disallowInAnd(func) {
19784             return doInsideOfContext(4096 /* DisallowInContext */, func);
19785         }
19786         function doInYieldContext(func) {
19787             return doInsideOfContext(8192 /* YieldContext */, func);
19788         }
19789         function doInDecoratorContext(func) {
19790             return doInsideOfContext(16384 /* DecoratorContext */, func);
19791         }
19792         function doInAwaitContext(func) {
19793             return doInsideOfContext(32768 /* AwaitContext */, func);
19794         }
19795         function doOutsideOfAwaitContext(func) {
19796             return doOutsideOfContext(32768 /* AwaitContext */, func);
19797         }
19798         function doInYieldAndAwaitContext(func) {
19799             return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19800         }
19801         function doOutsideOfYieldAndAwaitContext(func) {
19802             return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19803         }
19804         function inContext(flags) {
19805             return (contextFlags & flags) !== 0;
19806         }
19807         function inYieldContext() {
19808             return inContext(8192 /* YieldContext */);
19809         }
19810         function inDisallowInContext() {
19811             return inContext(4096 /* DisallowInContext */);
19812         }
19813         function inDecoratorContext() {
19814             return inContext(16384 /* DecoratorContext */);
19815         }
19816         function inAwaitContext() {
19817             return inContext(32768 /* AwaitContext */);
19818         }
19819         function parseErrorAtCurrentToken(message, arg0) {
19820             parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
19821         }
19822         function parseErrorAtPosition(start, length, message, arg0) {
19823             // Don't report another error if it would just be at the same position as the last error.
19824             var lastError = ts.lastOrUndefined(parseDiagnostics);
19825             if (!lastError || start !== lastError.start) {
19826                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0));
19827             }
19828             // Mark that we've encountered an error.  We'll set an appropriate bit on the next
19829             // node we finish so that it can't be reused incrementally.
19830             parseErrorBeforeNextFinishedNode = true;
19831         }
19832         function parseErrorAt(start, end, message, arg0) {
19833             parseErrorAtPosition(start, end - start, message, arg0);
19834         }
19835         function parseErrorAtRange(range, message, arg0) {
19836             parseErrorAt(range.pos, range.end, message, arg0);
19837         }
19838         function scanError(message, length) {
19839             parseErrorAtPosition(scanner.getTextPos(), length, message);
19840         }
19841         function getNodePos() {
19842             return scanner.getStartPos();
19843         }
19844         // Use this function to access the current token instead of reading the currentToken
19845         // variable. Since function results aren't narrowed in control flow analysis, this ensures
19846         // that the type checker doesn't make wrong assumptions about the type of the current
19847         // token (e.g. a call to nextToken() changes the current token but the checker doesn't
19848         // reason about this side effect).  Mainstream VMs inline simple functions like this, so
19849         // there is no performance penalty.
19850         function token() {
19851             return currentToken;
19852         }
19853         function nextTokenWithoutCheck() {
19854             return currentToken = scanner.scan();
19855         }
19856         function nextToken() {
19857             // if the keyword had an escape
19858             if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
19859                 // issue a parse error for the escape
19860                 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
19861             }
19862             return nextTokenWithoutCheck();
19863         }
19864         function nextTokenJSDoc() {
19865             return currentToken = scanner.scanJsDocToken();
19866         }
19867         function reScanGreaterToken() {
19868             return currentToken = scanner.reScanGreaterToken();
19869         }
19870         function reScanSlashToken() {
19871             return currentToken = scanner.reScanSlashToken();
19872         }
19873         function reScanTemplateToken(isTaggedTemplate) {
19874             return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
19875         }
19876         function reScanTemplateHeadOrNoSubstitutionTemplate() {
19877             return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
19878         }
19879         function reScanLessThanToken() {
19880             return currentToken = scanner.reScanLessThanToken();
19881         }
19882         function scanJsxIdentifier() {
19883             return currentToken = scanner.scanJsxIdentifier();
19884         }
19885         function scanJsxText() {
19886             return currentToken = scanner.scanJsxToken();
19887         }
19888         function scanJsxAttributeValue() {
19889             return currentToken = scanner.scanJsxAttributeValue();
19890         }
19891         function speculationHelper(callback, isLookAhead) {
19892             // Keep track of the state we'll need to rollback to if lookahead fails (or if the
19893             // caller asked us to always reset our state).
19894             var saveToken = currentToken;
19895             var saveParseDiagnosticsLength = parseDiagnostics.length;
19896             var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
19897             // Note: it is not actually necessary to save/restore the context flags here.  That's
19898             // because the saving/restoring of these flags happens naturally through the recursive
19899             // descent nature of our parser.  However, we still store this here just so we can
19900             // assert that invariant holds.
19901             var saveContextFlags = contextFlags;
19902             // If we're only looking ahead, then tell the scanner to only lookahead as well.
19903             // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
19904             // same.
19905             var result = isLookAhead
19906                 ? scanner.lookAhead(callback)
19907                 : scanner.tryScan(callback);
19908             ts.Debug.assert(saveContextFlags === contextFlags);
19909             // If our callback returned something 'falsy' or we're just looking ahead,
19910             // then unconditionally restore us to where we were.
19911             if (!result || isLookAhead) {
19912                 currentToken = saveToken;
19913                 parseDiagnostics.length = saveParseDiagnosticsLength;
19914                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
19915             }
19916             return result;
19917         }
19918         /** Invokes the provided callback then unconditionally restores the parser to the state it
19919          * was in immediately prior to invoking the callback.  The result of invoking the callback
19920          * is returned from this function.
19921          */
19922         function lookAhead(callback) {
19923             return speculationHelper(callback, /*isLookAhead*/ true);
19924         }
19925         /** Invokes the provided callback.  If the callback returns something falsy, then it restores
19926          * the parser to the state it was in immediately prior to invoking the callback.  If the
19927          * callback returns something truthy, then the parser state is not rolled back.  The result
19928          * of invoking the callback is returned from this function.
19929          */
19930         function tryParse(callback) {
19931             return speculationHelper(callback, /*isLookAhead*/ false);
19932         }
19933         // Ignore strict mode flag because we will report an error in type checker instead.
19934         function isIdentifier() {
19935             if (token() === 75 /* Identifier */) {
19936                 return true;
19937             }
19938             // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
19939             // considered a keyword and is not an identifier.
19940             if (token() === 121 /* YieldKeyword */ && inYieldContext()) {
19941                 return false;
19942             }
19943             // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
19944             // considered a keyword and is not an identifier.
19945             if (token() === 127 /* AwaitKeyword */ && inAwaitContext()) {
19946                 return false;
19947             }
19948             return token() > 112 /* LastReservedWord */;
19949         }
19950         function parseExpected(kind, diagnosticMessage, shouldAdvance) {
19951             if (shouldAdvance === void 0) { shouldAdvance = true; }
19952             if (token() === kind) {
19953                 if (shouldAdvance) {
19954                     nextToken();
19955                 }
19956                 return true;
19957             }
19958             // Report specific message if provided with one.  Otherwise, report generic fallback message.
19959             if (diagnosticMessage) {
19960                 parseErrorAtCurrentToken(diagnosticMessage);
19961             }
19962             else {
19963                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
19964             }
19965             return false;
19966         }
19967         function parseExpectedJSDoc(kind) {
19968             if (token() === kind) {
19969                 nextTokenJSDoc();
19970                 return true;
19971             }
19972             parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
19973             return false;
19974         }
19975         function parseOptional(t) {
19976             if (token() === t) {
19977                 nextToken();
19978                 return true;
19979             }
19980             return false;
19981         }
19982         function parseOptionalToken(t) {
19983             if (token() === t) {
19984                 return parseTokenNode();
19985             }
19986             return undefined;
19987         }
19988         function parseOptionalTokenJSDoc(t) {
19989             if (token() === t) {
19990                 return parseTokenNodeJSDoc();
19991             }
19992             return undefined;
19993         }
19994         function parseExpectedToken(t, diagnosticMessage, arg0) {
19995             return parseOptionalToken(t) ||
19996                 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
19997         }
19998         function parseExpectedTokenJSDoc(t) {
19999             return parseOptionalTokenJSDoc(t) ||
20000                 createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
20001         }
20002         function parseTokenNode() {
20003             var node = createNode(token());
20004             nextToken();
20005             return finishNode(node);
20006         }
20007         function parseTokenNodeJSDoc() {
20008             var node = createNode(token());
20009             nextTokenJSDoc();
20010             return finishNode(node);
20011         }
20012         function canParseSemicolon() {
20013             // If there's a real semicolon, then we can always parse it out.
20014             if (token() === 26 /* SemicolonToken */) {
20015                 return true;
20016             }
20017             // We can parse out an optional semicolon in ASI cases in the following cases.
20018             return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
20019         }
20020         function parseSemicolon() {
20021             if (canParseSemicolon()) {
20022                 if (token() === 26 /* SemicolonToken */) {
20023                     // consume the semicolon if it was explicitly provided.
20024                     nextToken();
20025                 }
20026                 return true;
20027             }
20028             else {
20029                 return parseExpected(26 /* SemicolonToken */);
20030             }
20031         }
20032         function createNode(kind, pos) {
20033             nodeCount++;
20034             var p = pos >= 0 ? pos : scanner.getStartPos();
20035             return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) :
20036                 kind === 75 /* Identifier */ ? new IdentifierConstructor(kind, p, p) :
20037                     kind === 76 /* PrivateIdentifier */ ? new PrivateIdentifierConstructor(kind, p, p) :
20038                         new TokenConstructor(kind, p, p);
20039         }
20040         function createNodeWithJSDoc(kind, pos) {
20041             var node = createNode(kind, pos);
20042             if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */ && (kind !== 226 /* ExpressionStatement */ || token() !== 20 /* OpenParenToken */)) {
20043                 addJSDocComment(node);
20044             }
20045             return node;
20046         }
20047         function createNodeArray(elements, pos, end) {
20048             // Since the element list of a node array is typically created by starting with an empty array and
20049             // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
20050             // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
20051             var length = elements.length;
20052             var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
20053             array.pos = pos;
20054             array.end = end === undefined ? scanner.getStartPos() : end;
20055             return array;
20056         }
20057         function finishNode(node, end) {
20058             node.end = end === undefined ? scanner.getStartPos() : end;
20059             if (contextFlags) {
20060                 node.flags |= contextFlags;
20061             }
20062             // Keep track on the node if we encountered an error while parsing it.  If we did, then
20063             // we cannot reuse the node incrementally.  Once we've marked this node, clear out the
20064             // flag so that we don't mark any subsequent nodes.
20065             if (parseErrorBeforeNextFinishedNode) {
20066                 parseErrorBeforeNextFinishedNode = false;
20067                 node.flags |= 65536 /* ThisNodeHasError */;
20068             }
20069             return node;
20070         }
20071         function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
20072             if (reportAtCurrentPosition) {
20073                 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
20074             }
20075             else if (diagnosticMessage) {
20076                 parseErrorAtCurrentToken(diagnosticMessage, arg0);
20077             }
20078             var result = createNode(kind);
20079             if (kind === 75 /* Identifier */) {
20080                 result.escapedText = "";
20081             }
20082             else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) {
20083                 result.text = "";
20084             }
20085             return finishNode(result);
20086         }
20087         function internIdentifier(text) {
20088             var identifier = identifiers.get(text);
20089             if (identifier === undefined) {
20090                 identifiers.set(text, identifier = text);
20091             }
20092             return identifier;
20093         }
20094         // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
20095         // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
20096         // each identifier in order to reduce memory consumption.
20097         function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
20098             identifierCount++;
20099             if (isIdentifier) {
20100                 var node = createNode(75 /* Identifier */);
20101                 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
20102                 if (token() !== 75 /* Identifier */) {
20103                     node.originalKeywordKind = token();
20104                 }
20105                 node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
20106                 nextTokenWithoutCheck();
20107                 return finishNode(node);
20108             }
20109             if (token() === 76 /* PrivateIdentifier */) {
20110                 parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
20111                 return createIdentifier(/*isIdentifier*/ true);
20112             }
20113             // Only for end of file because the error gets reported incorrectly on embedded script tags.
20114             var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
20115             var isReservedWord = scanner.isReservedWord();
20116             var msgArg = scanner.getTokenText();
20117             var defaultMessage = isReservedWord ?
20118                 ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
20119                 ts.Diagnostics.Identifier_expected;
20120             return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
20121         }
20122         function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
20123             return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
20124         }
20125         function parseIdentifierName(diagnosticMessage) {
20126             return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
20127         }
20128         function isLiteralPropertyName() {
20129             return ts.tokenIsIdentifierOrKeyword(token()) ||
20130                 token() === 10 /* StringLiteral */ ||
20131                 token() === 8 /* NumericLiteral */;
20132         }
20133         function parsePropertyNameWorker(allowComputedPropertyNames) {
20134             if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
20135                 var node = parseLiteralNode();
20136                 node.text = internIdentifier(node.text);
20137                 return node;
20138             }
20139             if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
20140                 return parseComputedPropertyName();
20141             }
20142             if (token() === 76 /* PrivateIdentifier */) {
20143                 return parsePrivateIdentifier();
20144             }
20145             return parseIdentifierName();
20146         }
20147         function parsePropertyName() {
20148             return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
20149         }
20150         function parseComputedPropertyName() {
20151             // PropertyName [Yield]:
20152             //      LiteralPropertyName
20153             //      ComputedPropertyName[?Yield]
20154             var node = createNode(154 /* ComputedPropertyName */);
20155             parseExpected(22 /* OpenBracketToken */);
20156             // We parse any expression (including a comma expression). But the grammar
20157             // says that only an assignment expression is allowed, so the grammar checker
20158             // will error if it sees a comma expression.
20159             node.expression = allowInAnd(parseExpression);
20160             parseExpected(23 /* CloseBracketToken */);
20161             return finishNode(node);
20162         }
20163         function internPrivateIdentifier(text) {
20164             var privateIdentifier = privateIdentifiers.get(text);
20165             if (privateIdentifier === undefined) {
20166                 privateIdentifiers.set(text, privateIdentifier = text);
20167             }
20168             return privateIdentifier;
20169         }
20170         function parsePrivateIdentifier() {
20171             var node = createNode(76 /* PrivateIdentifier */);
20172             node.escapedText = ts.escapeLeadingUnderscores(internPrivateIdentifier(scanner.getTokenText()));
20173             nextToken();
20174             return finishNode(node);
20175         }
20176         function parseContextualModifier(t) {
20177             return token() === t && tryParse(nextTokenCanFollowModifier);
20178         }
20179         function nextTokenIsOnSameLineAndCanFollowModifier() {
20180             nextToken();
20181             if (scanner.hasPrecedingLineBreak()) {
20182                 return false;
20183             }
20184             return canFollowModifier();
20185         }
20186         function nextTokenCanFollowModifier() {
20187             switch (token()) {
20188                 case 81 /* ConstKeyword */:
20189                     // 'const' is only a modifier if followed by 'enum'.
20190                     return nextToken() === 88 /* EnumKeyword */;
20191                 case 89 /* ExportKeyword */:
20192                     nextToken();
20193                     if (token() === 84 /* DefaultKeyword */) {
20194                         return lookAhead(nextTokenCanFollowDefaultKeyword);
20195                     }
20196                     if (token() === 145 /* TypeKeyword */) {
20197                         return lookAhead(nextTokenCanFollowExportModifier);
20198                     }
20199                     return canFollowExportModifier();
20200                 case 84 /* DefaultKeyword */:
20201                     return nextTokenCanFollowDefaultKeyword();
20202                 case 120 /* StaticKeyword */:
20203                 case 131 /* GetKeyword */:
20204                 case 142 /* SetKeyword */:
20205                     nextToken();
20206                     return canFollowModifier();
20207                 default:
20208                     return nextTokenIsOnSameLineAndCanFollowModifier();
20209             }
20210         }
20211         function canFollowExportModifier() {
20212             return token() !== 41 /* AsteriskToken */
20213                 && token() !== 123 /* AsKeyword */
20214                 && token() !== 18 /* OpenBraceToken */
20215                 && canFollowModifier();
20216         }
20217         function nextTokenCanFollowExportModifier() {
20218             nextToken();
20219             return canFollowExportModifier();
20220         }
20221         function parseAnyContextualModifier() {
20222             return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
20223         }
20224         function canFollowModifier() {
20225             return token() === 22 /* OpenBracketToken */
20226                 || token() === 18 /* OpenBraceToken */
20227                 || token() === 41 /* AsteriskToken */
20228                 || token() === 25 /* DotDotDotToken */
20229                 || isLiteralPropertyName();
20230         }
20231         function nextTokenCanFollowDefaultKeyword() {
20232             nextToken();
20233             return token() === 80 /* ClassKeyword */ || token() === 94 /* FunctionKeyword */ ||
20234                 token() === 114 /* InterfaceKeyword */ ||
20235                 (token() === 122 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
20236                 (token() === 126 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
20237         }
20238         // True if positioned at the start of a list element
20239         function isListElement(parsingContext, inErrorRecovery) {
20240             var node = currentNode(parsingContext);
20241             if (node) {
20242                 return true;
20243             }
20244             switch (parsingContext) {
20245                 case 0 /* SourceElements */:
20246                 case 1 /* BlockStatements */:
20247                 case 3 /* SwitchClauseStatements */:
20248                     // If we're in error recovery, then we don't want to treat ';' as an empty statement.
20249                     // The problem is that ';' can show up in far too many contexts, and if we see one
20250                     // and assume it's a statement, then we may bail out inappropriately from whatever
20251                     // we're parsing.  For example, if we have a semicolon in the middle of a class, then
20252                     // we really don't want to assume the class is over and we're on a statement in the
20253                     // outer module.  We just want to consume and move on.
20254                     return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
20255                 case 2 /* SwitchClauses */:
20256                     return token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20257                 case 4 /* TypeMembers */:
20258                     return lookAhead(isTypeMemberStart);
20259                 case 5 /* ClassMembers */:
20260                     // We allow semicolons as class elements (as specified by ES6) as long as we're
20261                     // not in error recovery.  If we're in error recovery, we don't want an errant
20262                     // semicolon to be treated as a class member (since they're almost always used
20263                     // for statements.
20264                     return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
20265                 case 6 /* EnumMembers */:
20266                     // Include open bracket computed properties. This technically also lets in indexers,
20267                     // which would be a candidate for improved error reporting.
20268                     return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
20269                 case 12 /* ObjectLiteralMembers */:
20270                     switch (token()) {
20271                         case 22 /* OpenBracketToken */:
20272                         case 41 /* AsteriskToken */:
20273                         case 25 /* DotDotDotToken */:
20274                         case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
20275                             return true;
20276                         default:
20277                             return isLiteralPropertyName();
20278                     }
20279                 case 18 /* RestProperties */:
20280                     return isLiteralPropertyName();
20281                 case 9 /* ObjectBindingElements */:
20282                     return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
20283                 case 7 /* HeritageClauseElement */:
20284                     // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
20285                     // That way we won't consume the body of a class in its heritage clause.
20286                     if (token() === 18 /* OpenBraceToken */) {
20287                         return lookAhead(isValidHeritageClauseObjectLiteral);
20288                     }
20289                     if (!inErrorRecovery) {
20290                         return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
20291                     }
20292                     else {
20293                         // If we're in error recovery we tighten up what we're willing to match.
20294                         // That way we don't treat something like "this" as a valid heritage clause
20295                         // element during recovery.
20296                         return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
20297                     }
20298                 case 8 /* VariableDeclarations */:
20299                     return isIdentifierOrPrivateIdentifierOrPattern();
20300                 case 10 /* ArrayBindingElements */:
20301                     return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPrivateIdentifierOrPattern();
20302                 case 19 /* TypeParameters */:
20303                     return isIdentifier();
20304                 case 15 /* ArrayLiteralMembers */:
20305                     switch (token()) {
20306                         case 27 /* CommaToken */:
20307                         case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
20308                             return true;
20309                     }
20310                 // falls through
20311                 case 11 /* ArgumentExpressions */:
20312                     return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
20313                 case 16 /* Parameters */:
20314                     return isStartOfParameter(/*isJSDocParameter*/ false);
20315                 case 17 /* JSDocParameters */:
20316                     return isStartOfParameter(/*isJSDocParameter*/ true);
20317                 case 20 /* TypeArguments */:
20318                 case 21 /* TupleElementTypes */:
20319                     return token() === 27 /* CommaToken */ || isStartOfType();
20320                 case 22 /* HeritageClauses */:
20321                     return isHeritageClause();
20322                 case 23 /* ImportOrExportSpecifiers */:
20323                     return ts.tokenIsIdentifierOrKeyword(token());
20324                 case 13 /* JsxAttributes */:
20325                     return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
20326                 case 14 /* JsxChildren */:
20327                     return true;
20328             }
20329             return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
20330         }
20331         function isValidHeritageClauseObjectLiteral() {
20332             ts.Debug.assert(token() === 18 /* OpenBraceToken */);
20333             if (nextToken() === 19 /* CloseBraceToken */) {
20334                 // if we see "extends {}" then only treat the {} as what we're extending (and not
20335                 // the class body) if we have:
20336                 //
20337                 //      extends {} {
20338                 //      extends {},
20339                 //      extends {} extends
20340                 //      extends {} implements
20341                 var next = nextToken();
20342                 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 90 /* ExtendsKeyword */ || next === 113 /* ImplementsKeyword */;
20343             }
20344             return true;
20345         }
20346         function nextTokenIsIdentifier() {
20347             nextToken();
20348             return isIdentifier();
20349         }
20350         function nextTokenIsIdentifierOrKeyword() {
20351             nextToken();
20352             return ts.tokenIsIdentifierOrKeyword(token());
20353         }
20354         function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
20355             nextToken();
20356             return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
20357         }
20358         function isHeritageClauseExtendsOrImplementsKeyword() {
20359             if (token() === 113 /* ImplementsKeyword */ ||
20360                 token() === 90 /* ExtendsKeyword */) {
20361                 return lookAhead(nextTokenIsStartOfExpression);
20362             }
20363             return false;
20364         }
20365         function nextTokenIsStartOfExpression() {
20366             nextToken();
20367             return isStartOfExpression();
20368         }
20369         function nextTokenIsStartOfType() {
20370             nextToken();
20371             return isStartOfType();
20372         }
20373         // True if positioned at a list terminator
20374         function isListTerminator(kind) {
20375             if (token() === 1 /* EndOfFileToken */) {
20376                 // Being at the end of the file ends all lists.
20377                 return true;
20378             }
20379             switch (kind) {
20380                 case 1 /* BlockStatements */:
20381                 case 2 /* SwitchClauses */:
20382                 case 4 /* TypeMembers */:
20383                 case 5 /* ClassMembers */:
20384                 case 6 /* EnumMembers */:
20385                 case 12 /* ObjectLiteralMembers */:
20386                 case 9 /* ObjectBindingElements */:
20387                 case 23 /* ImportOrExportSpecifiers */:
20388                     return token() === 19 /* CloseBraceToken */;
20389                 case 3 /* SwitchClauseStatements */:
20390                     return token() === 19 /* CloseBraceToken */ || token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20391                 case 7 /* HeritageClauseElement */:
20392                     return token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20393                 case 8 /* VariableDeclarations */:
20394                     return isVariableDeclaratorListTerminator();
20395                 case 19 /* TypeParameters */:
20396                     // Tokens other than '>' are here for better error recovery
20397                     return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20398                 case 11 /* ArgumentExpressions */:
20399                     // Tokens other than ')' are here for better error recovery
20400                     return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
20401                 case 15 /* ArrayLiteralMembers */:
20402                 case 21 /* TupleElementTypes */:
20403                 case 10 /* ArrayBindingElements */:
20404                     return token() === 23 /* CloseBracketToken */;
20405                 case 17 /* JSDocParameters */:
20406                 case 16 /* Parameters */:
20407                 case 18 /* RestProperties */:
20408                     // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
20409                     return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
20410                 case 20 /* TypeArguments */:
20411                     // All other tokens should cause the type-argument to terminate except comma token
20412                     return token() !== 27 /* CommaToken */;
20413                 case 22 /* HeritageClauses */:
20414                     return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
20415                 case 13 /* JsxAttributes */:
20416                     return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
20417                 case 14 /* JsxChildren */:
20418                     return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
20419                 default:
20420                     return false;
20421             }
20422         }
20423         function isVariableDeclaratorListTerminator() {
20424             // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
20425             // with parsing the list of variable declarators.
20426             if (canParseSemicolon()) {
20427                 return true;
20428             }
20429             // in the case where we're parsing the variable declarator of a 'for-in' statement, we
20430             // are done if we see an 'in' keyword in front of us. Same with for-of
20431             if (isInOrOfKeyword(token())) {
20432                 return true;
20433             }
20434             // ERROR RECOVERY TWEAK:
20435             // For better error recovery, if we see an '=>' then we just stop immediately.  We've got an
20436             // arrow function here and it's going to be very unlikely that we'll resynchronize and get
20437             // another variable declaration.
20438             if (token() === 38 /* EqualsGreaterThanToken */) {
20439                 return true;
20440             }
20441             // Keep trying to parse out variable declarators.
20442             return false;
20443         }
20444         // True if positioned at element or terminator of the current list or any enclosing list
20445         function isInSomeParsingContext() {
20446             for (var kind = 0; kind < 24 /* Count */; kind++) {
20447                 if (parsingContext & (1 << kind)) {
20448                     if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
20449                         return true;
20450                     }
20451                 }
20452             }
20453             return false;
20454         }
20455         // Parses a list of elements
20456         function parseList(kind, parseElement) {
20457             var saveParsingContext = parsingContext;
20458             parsingContext |= 1 << kind;
20459             var list = [];
20460             var listPos = getNodePos();
20461             while (!isListTerminator(kind)) {
20462                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20463                     var element = parseListElement(kind, parseElement);
20464                     list.push(element);
20465                     continue;
20466                 }
20467                 if (abortParsingListOrMoveToNextToken(kind)) {
20468                     break;
20469                 }
20470             }
20471             parsingContext = saveParsingContext;
20472             return createNodeArray(list, listPos);
20473         }
20474         function parseListElement(parsingContext, parseElement) {
20475             var node = currentNode(parsingContext);
20476             if (node) {
20477                 return consumeNode(node);
20478             }
20479             return parseElement();
20480         }
20481         function currentNode(parsingContext) {
20482             // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
20483             //
20484             // If there is an outstanding parse error that we've encountered, but not attached to
20485             // some node, then we cannot get a node from the old source tree.  This is because we
20486             // want to mark the next node we encounter as being unusable.
20487             //
20488             // Note: This may be too conservative.  Perhaps we could reuse the node and set the bit
20489             // on it (or its leftmost child) as having the error.  For now though, being conservative
20490             // is nice and likely won't ever affect perf.
20491             if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
20492                 return undefined;
20493             }
20494             var node = syntaxCursor.currentNode(scanner.getStartPos());
20495             // Can't reuse a missing node.
20496             // Can't reuse a node that intersected the change range.
20497             // Can't reuse a node that contains a parse error.  This is necessary so that we
20498             // produce the same set of errors again.
20499             if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
20500                 return undefined;
20501             }
20502             // We can only reuse a node if it was parsed under the same strict mode that we're
20503             // currently in.  i.e. if we originally parsed a node in non-strict mode, but then
20504             // the user added 'using strict' at the top of the file, then we can't use that node
20505             // again as the presence of strict mode may cause us to parse the tokens in the file
20506             // differently.
20507             //
20508             // Note: we *can* reuse tokens when the strict mode changes.  That's because tokens
20509             // are unaffected by strict mode.  It's just the parser will decide what to do with it
20510             // differently depending on what mode it is in.
20511             //
20512             // This also applies to all our other context flags as well.
20513             var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
20514             if (nodeContextFlags !== contextFlags) {
20515                 return undefined;
20516             }
20517             // Ok, we have a node that looks like it could be reused.  Now verify that it is valid
20518             // in the current list parsing context that we're currently at.
20519             if (!canReuseNode(node, parsingContext)) {
20520                 return undefined;
20521             }
20522             if (node.jsDocCache) {
20523                 // jsDocCache may include tags from parent nodes, which might have been modified.
20524                 node.jsDocCache = undefined;
20525             }
20526             return node;
20527         }
20528         function consumeNode(node) {
20529             // Move the scanner so it is after the node we just consumed.
20530             scanner.setTextPos(node.end);
20531             nextToken();
20532             return node;
20533         }
20534         function isReusableParsingContext(parsingContext) {
20535             switch (parsingContext) {
20536                 case 5 /* ClassMembers */:
20537                 case 2 /* SwitchClauses */:
20538                 case 0 /* SourceElements */:
20539                 case 1 /* BlockStatements */:
20540                 case 3 /* SwitchClauseStatements */:
20541                 case 6 /* EnumMembers */:
20542                 case 4 /* TypeMembers */:
20543                 case 8 /* VariableDeclarations */:
20544                 case 17 /* JSDocParameters */:
20545                 case 16 /* Parameters */:
20546                     return true;
20547             }
20548             return false;
20549         }
20550         function canReuseNode(node, parsingContext) {
20551             switch (parsingContext) {
20552                 case 5 /* ClassMembers */:
20553                     return isReusableClassMember(node);
20554                 case 2 /* SwitchClauses */:
20555                     return isReusableSwitchClause(node);
20556                 case 0 /* SourceElements */:
20557                 case 1 /* BlockStatements */:
20558                 case 3 /* SwitchClauseStatements */:
20559                     return isReusableStatement(node);
20560                 case 6 /* EnumMembers */:
20561                     return isReusableEnumMember(node);
20562                 case 4 /* TypeMembers */:
20563                     return isReusableTypeMember(node);
20564                 case 8 /* VariableDeclarations */:
20565                     return isReusableVariableDeclaration(node);
20566                 case 17 /* JSDocParameters */:
20567                 case 16 /* Parameters */:
20568                     return isReusableParameter(node);
20569                 // Any other lists we do not care about reusing nodes in.  But feel free to add if
20570                 // you can do so safely.  Danger areas involve nodes that may involve speculative
20571                 // parsing.  If speculative parsing is involved with the node, then the range the
20572                 // parser reached while looking ahead might be in the edited range (see the example
20573                 // in canReuseVariableDeclaratorNode for a good case of this).
20574                 // case ParsingContext.HeritageClauses:
20575                 // This would probably be safe to reuse.  There is no speculative parsing with
20576                 // heritage clauses.
20577                 // case ParsingContext.TypeParameters:
20578                 // This would probably be safe to reuse.  There is no speculative parsing with
20579                 // type parameters.  Note that that's because type *parameters* only occur in
20580                 // unambiguous *type* contexts.  While type *arguments* occur in very ambiguous
20581                 // *expression* contexts.
20582                 // case ParsingContext.TupleElementTypes:
20583                 // This would probably be safe to reuse.  There is no speculative parsing with
20584                 // tuple types.
20585                 // Technically, type argument list types are probably safe to reuse.  While
20586                 // speculative parsing is involved with them (since type argument lists are only
20587                 // produced from speculative parsing a < as a type argument list), we only have
20588                 // the types because speculative parsing succeeded.  Thus, the lookahead never
20589                 // went past the end of the list and rewound.
20590                 // case ParsingContext.TypeArguments:
20591                 // Note: these are almost certainly not safe to ever reuse.  Expressions commonly
20592                 // need a large amount of lookahead, and we should not reuse them as they may
20593                 // have actually intersected the edit.
20594                 // case ParsingContext.ArgumentExpressions:
20595                 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
20596                 // cases.  i.e. a property assignment may end with an expression, and thus might
20597                 // have lookahead far beyond it's old node.
20598                 // case ParsingContext.ObjectLiteralMembers:
20599                 // This is probably not safe to reuse.  There can be speculative parsing with
20600                 // type names in a heritage clause.  There can be generic names in the type
20601                 // name list, and there can be left hand side expressions (which can have type
20602                 // arguments.)
20603                 // case ParsingContext.HeritageClauseElement:
20604                 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
20605                 // on any given element. Same for children.
20606                 // case ParsingContext.JsxAttributes:
20607                 // case ParsingContext.JsxChildren:
20608             }
20609             return false;
20610         }
20611         function isReusableClassMember(node) {
20612             if (node) {
20613                 switch (node.kind) {
20614                     case 162 /* Constructor */:
20615                     case 167 /* IndexSignature */:
20616                     case 163 /* GetAccessor */:
20617                     case 164 /* SetAccessor */:
20618                     case 159 /* PropertyDeclaration */:
20619                     case 222 /* SemicolonClassElement */:
20620                         return true;
20621                     case 161 /* MethodDeclaration */:
20622                         // Method declarations are not necessarily reusable.  An object-literal
20623                         // may have a method calls "constructor(...)" and we must reparse that
20624                         // into an actual .ConstructorDeclaration.
20625                         var methodDeclaration = node;
20626                         var nameIsConstructor = methodDeclaration.name.kind === 75 /* Identifier */ &&
20627                             methodDeclaration.name.originalKeywordKind === 129 /* ConstructorKeyword */;
20628                         return !nameIsConstructor;
20629                 }
20630             }
20631             return false;
20632         }
20633         function isReusableSwitchClause(node) {
20634             if (node) {
20635                 switch (node.kind) {
20636                     case 277 /* CaseClause */:
20637                     case 278 /* DefaultClause */:
20638                         return true;
20639                 }
20640             }
20641             return false;
20642         }
20643         function isReusableStatement(node) {
20644             if (node) {
20645                 switch (node.kind) {
20646                     case 244 /* FunctionDeclaration */:
20647                     case 225 /* VariableStatement */:
20648                     case 223 /* Block */:
20649                     case 227 /* IfStatement */:
20650                     case 226 /* ExpressionStatement */:
20651                     case 239 /* ThrowStatement */:
20652                     case 235 /* ReturnStatement */:
20653                     case 237 /* SwitchStatement */:
20654                     case 234 /* BreakStatement */:
20655                     case 233 /* ContinueStatement */:
20656                     case 231 /* ForInStatement */:
20657                     case 232 /* ForOfStatement */:
20658                     case 230 /* ForStatement */:
20659                     case 229 /* WhileStatement */:
20660                     case 236 /* WithStatement */:
20661                     case 224 /* EmptyStatement */:
20662                     case 240 /* TryStatement */:
20663                     case 238 /* LabeledStatement */:
20664                     case 228 /* DoStatement */:
20665                     case 241 /* DebuggerStatement */:
20666                     case 254 /* ImportDeclaration */:
20667                     case 253 /* ImportEqualsDeclaration */:
20668                     case 260 /* ExportDeclaration */:
20669                     case 259 /* ExportAssignment */:
20670                     case 249 /* ModuleDeclaration */:
20671                     case 245 /* ClassDeclaration */:
20672                     case 246 /* InterfaceDeclaration */:
20673                     case 248 /* EnumDeclaration */:
20674                     case 247 /* TypeAliasDeclaration */:
20675                         return true;
20676                 }
20677             }
20678             return false;
20679         }
20680         function isReusableEnumMember(node) {
20681             return node.kind === 284 /* EnumMember */;
20682         }
20683         function isReusableTypeMember(node) {
20684             if (node) {
20685                 switch (node.kind) {
20686                     case 166 /* ConstructSignature */:
20687                     case 160 /* MethodSignature */:
20688                     case 167 /* IndexSignature */:
20689                     case 158 /* PropertySignature */:
20690                     case 165 /* CallSignature */:
20691                         return true;
20692                 }
20693             }
20694             return false;
20695         }
20696         function isReusableVariableDeclaration(node) {
20697             if (node.kind !== 242 /* VariableDeclaration */) {
20698                 return false;
20699             }
20700             // Very subtle incremental parsing bug.  Consider the following code:
20701             //
20702             //      let v = new List < A, B
20703             //
20704             // This is actually legal code.  It's a list of variable declarators "v = new List<A"
20705             // on one side and "B" on the other. If you then change that to:
20706             //
20707             //      let v = new List < A, B >()
20708             //
20709             // then we have a problem.  "v = new List<A" doesn't intersect the change range, so we
20710             // start reparsing at "B" and we completely fail to handle this properly.
20711             //
20712             // In order to prevent this, we do not allow a variable declarator to be reused if it
20713             // has an initializer.
20714             var variableDeclarator = node;
20715             return variableDeclarator.initializer === undefined;
20716         }
20717         function isReusableParameter(node) {
20718             if (node.kind !== 156 /* Parameter */) {
20719                 return false;
20720             }
20721             // See the comment in isReusableVariableDeclaration for why we do this.
20722             var parameter = node;
20723             return parameter.initializer === undefined;
20724         }
20725         // Returns true if we should abort parsing.
20726         function abortParsingListOrMoveToNextToken(kind) {
20727             parseErrorAtCurrentToken(parsingContextErrors(kind));
20728             if (isInSomeParsingContext()) {
20729                 return true;
20730             }
20731             nextToken();
20732             return false;
20733         }
20734         function parsingContextErrors(context) {
20735             switch (context) {
20736                 case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected;
20737                 case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected;
20738                 case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected;
20739                 case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected;
20740                 case 18 /* RestProperties */: // fallthrough
20741                 case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected;
20742                 case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
20743                 case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected;
20744                 case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected;
20745                 case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected;
20746                 case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected;
20747                 case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected;
20748                 case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected;
20749                 case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected;
20750                 case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected;
20751                 case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected;
20752                 case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected;
20753                 case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected;
20754                 case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected;
20755                 case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected;
20756                 case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected;
20757                 case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected;
20758                 case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected;
20759                 case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected;
20760                 default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);`
20761             }
20762         }
20763         // Parses a comma-delimited list of elements
20764         function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
20765             var saveParsingContext = parsingContext;
20766             parsingContext |= 1 << kind;
20767             var list = [];
20768             var listPos = getNodePos();
20769             var commaStart = -1; // Meaning the previous token was not a comma
20770             while (true) {
20771                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20772                     var startPos = scanner.getStartPos();
20773                     list.push(parseListElement(kind, parseElement));
20774                     commaStart = scanner.getTokenPos();
20775                     if (parseOptional(27 /* CommaToken */)) {
20776                         // No need to check for a zero length node since we know we parsed a comma
20777                         continue;
20778                     }
20779                     commaStart = -1; // Back to the state where the last token was not a comma
20780                     if (isListTerminator(kind)) {
20781                         break;
20782                     }
20783                     // We didn't get a comma, and the list wasn't terminated, explicitly parse
20784                     // out a comma so we give a good error message.
20785                     parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
20786                     // If the token was a semicolon, and the caller allows that, then skip it and
20787                     // continue.  This ensures we get back on track and don't result in tons of
20788                     // parse errors.  For example, this can happen when people do things like use
20789                     // a semicolon to delimit object literal members.   Note: we'll have already
20790                     // reported an error when we called parseExpected above.
20791                     if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
20792                         nextToken();
20793                     }
20794                     if (startPos === scanner.getStartPos()) {
20795                         // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
20796                         // Consume a token to advance the parser in some way and avoid an infinite loop
20797                         // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
20798                         // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
20799                         nextToken();
20800                     }
20801                     continue;
20802                 }
20803                 if (isListTerminator(kind)) {
20804                     break;
20805                 }
20806                 if (abortParsingListOrMoveToNextToken(kind)) {
20807                     break;
20808                 }
20809             }
20810             parsingContext = saveParsingContext;
20811             var result = createNodeArray(list, listPos);
20812             // Recording the trailing comma is deliberately done after the previous
20813             // loop, and not just if we see a list terminator. This is because the list
20814             // may have ended incorrectly, but it is still important to know if there
20815             // was a trailing comma.
20816             // Check if the last token was a comma.
20817             if (commaStart >= 0) {
20818                 // Always preserve a trailing comma by marking it on the NodeArray
20819                 result.hasTrailingComma = true;
20820             }
20821             return result;
20822         }
20823         function getExpectedCommaDiagnostic(kind) {
20824             return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
20825         }
20826         function createMissingList() {
20827             var list = createNodeArray([], getNodePos());
20828             list.isMissingList = true;
20829             return list;
20830         }
20831         function isMissingList(arr) {
20832             return !!arr.isMissingList;
20833         }
20834         function parseBracketedList(kind, parseElement, open, close) {
20835             if (parseExpected(open)) {
20836                 var result = parseDelimitedList(kind, parseElement);
20837                 parseExpected(close);
20838                 return result;
20839             }
20840             return createMissingList();
20841         }
20842         function parseEntityName(allowReservedWords, diagnosticMessage) {
20843             var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
20844             var dotPos = scanner.getStartPos();
20845             while (parseOptional(24 /* DotToken */)) {
20846                 if (token() === 29 /* LessThanToken */) {
20847                     // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
20848                     entity.jsdocDotPos = dotPos;
20849                     break;
20850                 }
20851                 dotPos = scanner.getStartPos();
20852                 entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false));
20853             }
20854             return entity;
20855         }
20856         function createQualifiedName(entity, name) {
20857             var node = createNode(153 /* QualifiedName */, entity.pos);
20858             node.left = entity;
20859             node.right = name;
20860             return finishNode(node);
20861         }
20862         function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
20863             // Technically a keyword is valid here as all identifiers and keywords are identifier names.
20864             // However, often we'll encounter this in error situations when the identifier or keyword
20865             // is actually starting another valid construct.
20866             //
20867             // So, we check for the following specific case:
20868             //
20869             //      name.
20870             //      identifierOrKeyword identifierNameOrKeyword
20871             //
20872             // Note: the newlines are important here.  For example, if that above code
20873             // were rewritten into:
20874             //
20875             //      name.identifierOrKeyword
20876             //      identifierNameOrKeyword
20877             //
20878             // Then we would consider it valid.  That's because ASI would take effect and
20879             // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
20880             // In the first case though, ASI will not take effect because there is not a
20881             // line terminator after the identifier or keyword.
20882             if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
20883                 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
20884                 if (matchesPattern) {
20885                     // Report that we need an identifier.  However, report it right after the dot,
20886                     // and not on the next token.  This is because the next token might actually
20887                     // be an identifier and the error would be quite confusing.
20888                     return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
20889                 }
20890             }
20891             if (token() === 76 /* PrivateIdentifier */) {
20892                 var node = parsePrivateIdentifier();
20893                 return allowPrivateIdentifiers ? node : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
20894             }
20895             return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
20896         }
20897         function parseTemplateExpression(isTaggedTemplate) {
20898             var template = createNode(211 /* TemplateExpression */);
20899             template.head = parseTemplateHead(isTaggedTemplate);
20900             ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
20901             var list = [];
20902             var listPos = getNodePos();
20903             do {
20904                 list.push(parseTemplateSpan(isTaggedTemplate));
20905             } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */);
20906             template.templateSpans = createNodeArray(list, listPos);
20907             return finishNode(template);
20908         }
20909         function parseTemplateSpan(isTaggedTemplate) {
20910             var span = createNode(221 /* TemplateSpan */);
20911             span.expression = allowInAnd(parseExpression);
20912             var literal;
20913             if (token() === 19 /* CloseBraceToken */) {
20914                 reScanTemplateToken(isTaggedTemplate);
20915                 literal = parseTemplateMiddleOrTemplateTail();
20916             }
20917             else {
20918                 literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
20919             }
20920             span.literal = literal;
20921             return finishNode(span);
20922         }
20923         function parseLiteralNode() {
20924             return parseLiteralLikeNode(token());
20925         }
20926         function parseTemplateHead(isTaggedTemplate) {
20927             if (isTaggedTemplate) {
20928                 reScanTemplateHeadOrNoSubstitutionTemplate();
20929             }
20930             var fragment = parseLiteralLikeNode(token());
20931             ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
20932             return fragment;
20933         }
20934         function parseTemplateMiddleOrTemplateTail() {
20935             var fragment = parseLiteralLikeNode(token());
20936             ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
20937             return fragment;
20938         }
20939         function parseLiteralLikeNode(kind) {
20940             var node = createNode(kind);
20941             node.text = scanner.getTokenValue();
20942             switch (kind) {
20943                 case 14 /* NoSubstitutionTemplateLiteral */:
20944                 case 15 /* TemplateHead */:
20945                 case 16 /* TemplateMiddle */:
20946                 case 17 /* TemplateTail */:
20947                     var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
20948                     var tokenText = scanner.getTokenText();
20949                     node.rawText = tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
20950                     break;
20951             }
20952             if (scanner.hasExtendedUnicodeEscape()) {
20953                 node.hasExtendedUnicodeEscape = true;
20954             }
20955             if (scanner.isUnterminated()) {
20956                 node.isUnterminated = true;
20957             }
20958             // Octal literals are not allowed in strict mode or ES5
20959             // Note that theoretically the following condition would hold true literals like 009,
20960             // which is not octal.But because of how the scanner separates the tokens, we would
20961             // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
20962             // We also do not need to check for negatives because any prefix operator would be part of a
20963             // parent unary expression.
20964             if (node.kind === 8 /* NumericLiteral */) {
20965                 node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */;
20966             }
20967             if (ts.isTemplateLiteralKind(node.kind)) {
20968                 node.templateFlags = scanner.getTokenFlags() & 2048 /* ContainsInvalidEscape */;
20969             }
20970             nextToken();
20971             finishNode(node);
20972             return node;
20973         }
20974         // TYPES
20975         function parseTypeReference() {
20976             var node = createNode(169 /* TypeReference */);
20977             node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
20978             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
20979                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
20980             }
20981             return finishNode(node);
20982         }
20983         // If true, we should abort parsing an error function.
20984         function typeHasArrowFunctionBlockingParseError(node) {
20985             switch (node.kind) {
20986                 case 169 /* TypeReference */:
20987                     return ts.nodeIsMissing(node.typeName);
20988                 case 170 /* FunctionType */:
20989                 case 171 /* ConstructorType */: {
20990                     var _a = node, parameters = _a.parameters, type = _a.type;
20991                     return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
20992                 }
20993                 case 182 /* ParenthesizedType */:
20994                     return typeHasArrowFunctionBlockingParseError(node.type);
20995                 default:
20996                     return false;
20997             }
20998         }
20999         function parseThisTypePredicate(lhs) {
21000             nextToken();
21001             var node = createNode(168 /* TypePredicate */, lhs.pos);
21002             node.parameterName = lhs;
21003             node.type = parseType();
21004             return finishNode(node);
21005         }
21006         function parseThisTypeNode() {
21007             var node = createNode(183 /* ThisType */);
21008             nextToken();
21009             return finishNode(node);
21010         }
21011         function parseJSDocAllType(postFixEquals) {
21012             var result = createNode(295 /* JSDocAllType */);
21013             if (postFixEquals) {
21014                 return createPostfixType(299 /* JSDocOptionalType */, result);
21015             }
21016             else {
21017                 nextToken();
21018             }
21019             return finishNode(result);
21020         }
21021         function parseJSDocNonNullableType() {
21022             var result = createNode(298 /* JSDocNonNullableType */);
21023             nextToken();
21024             result.type = parseNonArrayType();
21025             return finishNode(result);
21026         }
21027         function parseJSDocUnknownOrNullableType() {
21028             var pos = scanner.getStartPos();
21029             // skip the ?
21030             nextToken();
21031             // Need to lookahead to decide if this is a nullable or unknown type.
21032             // Here are cases where we'll pick the unknown type:
21033             //
21034             //      Foo(?,
21035             //      { a: ? }
21036             //      Foo(?)
21037             //      Foo<?>
21038             //      Foo(?=
21039             //      (?|
21040             if (token() === 27 /* CommaToken */ ||
21041                 token() === 19 /* CloseBraceToken */ ||
21042                 token() === 21 /* CloseParenToken */ ||
21043                 token() === 31 /* GreaterThanToken */ ||
21044                 token() === 62 /* EqualsToken */ ||
21045                 token() === 51 /* BarToken */) {
21046                 var result = createNode(296 /* JSDocUnknownType */, pos);
21047                 return finishNode(result);
21048             }
21049             else {
21050                 var result = createNode(297 /* JSDocNullableType */, pos);
21051                 result.type = parseType();
21052                 return finishNode(result);
21053             }
21054         }
21055         function parseJSDocFunctionType() {
21056             if (lookAhead(nextTokenIsOpenParen)) {
21057                 var result = createNodeWithJSDoc(300 /* JSDocFunctionType */);
21058                 nextToken();
21059                 fillSignature(58 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
21060                 return finishNode(result);
21061             }
21062             var node = createNode(169 /* TypeReference */);
21063             node.typeName = parseIdentifierName();
21064             return finishNode(node);
21065         }
21066         function parseJSDocParameter() {
21067             var parameter = createNode(156 /* Parameter */);
21068             if (token() === 104 /* ThisKeyword */ || token() === 99 /* NewKeyword */) {
21069                 parameter.name = parseIdentifierName();
21070                 parseExpected(58 /* ColonToken */);
21071             }
21072             parameter.type = parseJSDocType();
21073             return finishNode(parameter);
21074         }
21075         function parseJSDocType() {
21076             scanner.setInJSDocType(true);
21077             var moduleSpecifier = parseOptionalToken(135 /* ModuleKeyword */);
21078             if (moduleSpecifier) {
21079                 var moduleTag = createNode(302 /* JSDocNamepathType */, moduleSpecifier.pos);
21080                 terminate: while (true) {
21081                     switch (token()) {
21082                         case 19 /* CloseBraceToken */:
21083                         case 1 /* EndOfFileToken */:
21084                         case 27 /* CommaToken */:
21085                         case 5 /* WhitespaceTrivia */:
21086                             break terminate;
21087                         default:
21088                             nextTokenJSDoc();
21089                     }
21090                 }
21091                 scanner.setInJSDocType(false);
21092                 return finishNode(moduleTag);
21093             }
21094             var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */);
21095             var type = parseTypeOrTypePredicate();
21096             scanner.setInJSDocType(false);
21097             if (dotdotdot) {
21098                 var variadic = createNode(301 /* JSDocVariadicType */, dotdotdot.pos);
21099                 variadic.type = type;
21100                 type = finishNode(variadic);
21101             }
21102             if (token() === 62 /* EqualsToken */) {
21103                 return createPostfixType(299 /* JSDocOptionalType */, type);
21104             }
21105             return type;
21106         }
21107         function parseTypeQuery() {
21108             var node = createNode(172 /* TypeQuery */);
21109             parseExpected(108 /* TypeOfKeyword */);
21110             node.exprName = parseEntityName(/*allowReservedWords*/ true);
21111             return finishNode(node);
21112         }
21113         function parseTypeParameter() {
21114             var node = createNode(155 /* TypeParameter */);
21115             node.name = parseIdentifier();
21116             if (parseOptional(90 /* ExtendsKeyword */)) {
21117                 // It's not uncommon for people to write improper constraints to a generic.  If the
21118                 // user writes a constraint that is an expression and not an actual type, then parse
21119                 // it out as an expression (so we can recover well), but report that a type is needed
21120                 // instead.
21121                 if (isStartOfType() || !isStartOfExpression()) {
21122                     node.constraint = parseType();
21123                 }
21124                 else {
21125                     // It was not a type, and it looked like an expression.  Parse out an expression
21126                     // here so we recover well.  Note: it is important that we call parseUnaryExpression
21127                     // and not parseExpression here.  If the user has:
21128                     //
21129                     //      <T extends "">
21130                     //
21131                     // We do *not* want to consume the `>` as we're consuming the expression for "".
21132                     node.expression = parseUnaryExpressionOrHigher();
21133                 }
21134             }
21135             if (parseOptional(62 /* EqualsToken */)) {
21136                 node.default = parseType();
21137             }
21138             return finishNode(node);
21139         }
21140         function parseTypeParameters() {
21141             if (token() === 29 /* LessThanToken */) {
21142                 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21143             }
21144         }
21145         function parseParameterType() {
21146             if (parseOptional(58 /* ColonToken */)) {
21147                 return parseType();
21148             }
21149             return undefined;
21150         }
21151         function isStartOfParameter(isJSDocParameter) {
21152             return token() === 25 /* DotDotDotToken */ ||
21153                 isIdentifierOrPrivateIdentifierOrPattern() ||
21154                 ts.isModifierKind(token()) ||
21155                 token() === 59 /* AtToken */ ||
21156                 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
21157         }
21158         function parseParameter() {
21159             var node = createNodeWithJSDoc(156 /* Parameter */);
21160             if (token() === 104 /* ThisKeyword */) {
21161                 node.name = createIdentifier(/*isIdentifier*/ true);
21162                 node.type = parseParameterType();
21163                 return finishNode(node);
21164             }
21165             node.decorators = parseDecorators();
21166             node.modifiers = parseModifiers();
21167             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
21168             // FormalParameter [Yield,Await]:
21169             //      BindingElement[?Yield,?Await]
21170             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
21171             if (ts.getFullWidth(node.name) === 0 && !node.modifiers && ts.isModifierKind(token())) {
21172                 // in cases like
21173                 // 'use strict'
21174                 // function foo(static)
21175                 // isParameter('static') === true, because of isModifier('static')
21176                 // however 'static' is not a legal identifier in a strict mode.
21177                 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
21178                 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
21179                 // to avoid this we'll advance cursor to the next token.
21180                 nextToken();
21181             }
21182             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21183             node.type = parseParameterType();
21184             node.initializer = parseInitializer();
21185             return finishNode(node);
21186         }
21187         /**
21188          * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined.
21189          * @returns If return type parsing succeeds
21190          */
21191         function fillSignature(returnToken, flags, signature) {
21192             if (!(flags & 32 /* JSDoc */)) {
21193                 signature.typeParameters = parseTypeParameters();
21194             }
21195             var parametersParsedSuccessfully = parseParameterList(signature, flags);
21196             if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
21197                 signature.type = parseTypeOrTypePredicate();
21198                 if (typeHasArrowFunctionBlockingParseError(signature.type))
21199                     return false;
21200             }
21201             return parametersParsedSuccessfully;
21202         }
21203         function shouldParseReturnType(returnToken, isType) {
21204             if (returnToken === 38 /* EqualsGreaterThanToken */) {
21205                 parseExpected(returnToken);
21206                 return true;
21207             }
21208             else if (parseOptional(58 /* ColonToken */)) {
21209                 return true;
21210             }
21211             else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
21212                 // This is easy to get backward, especially in type contexts, so parse the type anyway
21213                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
21214                 nextToken();
21215                 return true;
21216             }
21217             return false;
21218         }
21219         // Returns true on success.
21220         function parseParameterList(signature, flags) {
21221             // FormalParameters [Yield,Await]: (modified)
21222             //      [empty]
21223             //      FormalParameterList[?Yield,Await]
21224             //
21225             // FormalParameter[Yield,Await]: (modified)
21226             //      BindingElement[?Yield,Await]
21227             //
21228             // BindingElement [Yield,Await]: (modified)
21229             //      SingleNameBinding[?Yield,?Await]
21230             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21231             //
21232             // SingleNameBinding [Yield,Await]:
21233             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21234             if (!parseExpected(20 /* OpenParenToken */)) {
21235                 signature.parameters = createMissingList();
21236                 return false;
21237             }
21238             var savedYieldContext = inYieldContext();
21239             var savedAwaitContext = inAwaitContext();
21240             setYieldContext(!!(flags & 1 /* Yield */));
21241             setAwaitContext(!!(flags & 2 /* Await */));
21242             signature.parameters = flags & 32 /* JSDoc */ ?
21243                 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
21244                 parseDelimitedList(16 /* Parameters */, parseParameter);
21245             setYieldContext(savedYieldContext);
21246             setAwaitContext(savedAwaitContext);
21247             return parseExpected(21 /* CloseParenToken */);
21248         }
21249         function parseTypeMemberSemicolon() {
21250             // We allow type members to be separated by commas or (possibly ASI) semicolons.
21251             // First check if it was a comma.  If so, we're done with the member.
21252             if (parseOptional(27 /* CommaToken */)) {
21253                 return;
21254             }
21255             // Didn't have a comma.  We must have a (possible ASI) semicolon.
21256             parseSemicolon();
21257         }
21258         function parseSignatureMember(kind) {
21259             var node = createNodeWithJSDoc(kind);
21260             if (kind === 166 /* ConstructSignature */) {
21261                 parseExpected(99 /* NewKeyword */);
21262             }
21263             fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21264             parseTypeMemberSemicolon();
21265             return finishNode(node);
21266         }
21267         function isIndexSignature() {
21268             return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
21269         }
21270         function isUnambiguouslyIndexSignature() {
21271             // The only allowed sequence is:
21272             //
21273             //   [id:
21274             //
21275             // However, for error recovery, we also check the following cases:
21276             //
21277             //   [...
21278             //   [id,
21279             //   [id?,
21280             //   [id?:
21281             //   [id?]
21282             //   [public id
21283             //   [private id
21284             //   [protected id
21285             //   []
21286             //
21287             nextToken();
21288             if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
21289                 return true;
21290             }
21291             if (ts.isModifierKind(token())) {
21292                 nextToken();
21293                 if (isIdentifier()) {
21294                     return true;
21295                 }
21296             }
21297             else if (!isIdentifier()) {
21298                 return false;
21299             }
21300             else {
21301                 // Skip the identifier
21302                 nextToken();
21303             }
21304             // A colon signifies a well formed indexer
21305             // A comma should be a badly formed indexer because comma expressions are not allowed
21306             // in computed properties.
21307             if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
21308                 return true;
21309             }
21310             // Question mark could be an indexer with an optional property,
21311             // or it could be a conditional expression in a computed property.
21312             if (token() !== 57 /* QuestionToken */) {
21313                 return false;
21314             }
21315             // If any of the following tokens are after the question mark, it cannot
21316             // be a conditional expression, so treat it as an indexer.
21317             nextToken();
21318             return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
21319         }
21320         function parseIndexSignatureDeclaration(node) {
21321             node.kind = 167 /* IndexSignature */;
21322             node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21323             node.type = parseTypeAnnotation();
21324             parseTypeMemberSemicolon();
21325             return finishNode(node);
21326         }
21327         function parsePropertyOrMethodSignature(node) {
21328             node.name = parsePropertyName();
21329             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21330             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21331                 node.kind = 160 /* MethodSignature */;
21332                 // Method signatures don't exist in expression contexts.  So they have neither
21333                 // [Yield] nor [Await]
21334                 fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21335             }
21336             else {
21337                 node.kind = 158 /* PropertySignature */;
21338                 node.type = parseTypeAnnotation();
21339                 if (token() === 62 /* EqualsToken */) {
21340                     // Although type literal properties cannot not have initializers, we attempt
21341                     // to parse an initializer so we can report in the checker that an interface
21342                     // property or type literal property cannot have an initializer.
21343                     node.initializer = parseInitializer();
21344                 }
21345             }
21346             parseTypeMemberSemicolon();
21347             return finishNode(node);
21348         }
21349         function isTypeMemberStart() {
21350             // Return true if we have the start of a signature member
21351             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21352                 return true;
21353             }
21354             var idToken = false;
21355             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
21356             while (ts.isModifierKind(token())) {
21357                 idToken = true;
21358                 nextToken();
21359             }
21360             // Index signatures and computed property names are type members
21361             if (token() === 22 /* OpenBracketToken */) {
21362                 return true;
21363             }
21364             // Try to get the first property-like token following all modifiers
21365             if (isLiteralPropertyName()) {
21366                 idToken = true;
21367                 nextToken();
21368             }
21369             // If we were able to get any potential identifier, check that it is
21370             // the start of a member declaration
21371             if (idToken) {
21372                 return token() === 20 /* OpenParenToken */ ||
21373                     token() === 29 /* LessThanToken */ ||
21374                     token() === 57 /* QuestionToken */ ||
21375                     token() === 58 /* ColonToken */ ||
21376                     token() === 27 /* CommaToken */ ||
21377                     canParseSemicolon();
21378             }
21379             return false;
21380         }
21381         function parseTypeMember() {
21382             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21383                 return parseSignatureMember(165 /* CallSignature */);
21384             }
21385             if (token() === 99 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
21386                 return parseSignatureMember(166 /* ConstructSignature */);
21387             }
21388             var node = createNodeWithJSDoc(0 /* Unknown */);
21389             node.modifiers = parseModifiers();
21390             if (isIndexSignature()) {
21391                 return parseIndexSignatureDeclaration(node);
21392             }
21393             return parsePropertyOrMethodSignature(node);
21394         }
21395         function nextTokenIsOpenParenOrLessThan() {
21396             nextToken();
21397             return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
21398         }
21399         function nextTokenIsDot() {
21400             return nextToken() === 24 /* DotToken */;
21401         }
21402         function nextTokenIsOpenParenOrLessThanOrDot() {
21403             switch (nextToken()) {
21404                 case 20 /* OpenParenToken */:
21405                 case 29 /* LessThanToken */:
21406                 case 24 /* DotToken */:
21407                     return true;
21408             }
21409             return false;
21410         }
21411         function parseTypeLiteral() {
21412             var node = createNode(173 /* TypeLiteral */);
21413             node.members = parseObjectTypeMembers();
21414             return finishNode(node);
21415         }
21416         function parseObjectTypeMembers() {
21417             var members;
21418             if (parseExpected(18 /* OpenBraceToken */)) {
21419                 members = parseList(4 /* TypeMembers */, parseTypeMember);
21420                 parseExpected(19 /* CloseBraceToken */);
21421             }
21422             else {
21423                 members = createMissingList();
21424             }
21425             return members;
21426         }
21427         function isStartOfMappedType() {
21428             nextToken();
21429             if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21430                 return nextToken() === 138 /* ReadonlyKeyword */;
21431             }
21432             if (token() === 138 /* ReadonlyKeyword */) {
21433                 nextToken();
21434             }
21435             return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 97 /* InKeyword */;
21436         }
21437         function parseMappedTypeParameter() {
21438             var node = createNode(155 /* TypeParameter */);
21439             node.name = parseIdentifier();
21440             parseExpected(97 /* InKeyword */);
21441             node.constraint = parseType();
21442             return finishNode(node);
21443         }
21444         function parseMappedType() {
21445             var node = createNode(186 /* MappedType */);
21446             parseExpected(18 /* OpenBraceToken */);
21447             if (token() === 138 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21448                 node.readonlyToken = parseTokenNode();
21449                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
21450                     parseExpectedToken(138 /* ReadonlyKeyword */);
21451                 }
21452             }
21453             parseExpected(22 /* OpenBracketToken */);
21454             node.typeParameter = parseMappedTypeParameter();
21455             parseExpected(23 /* CloseBracketToken */);
21456             if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21457                 node.questionToken = parseTokenNode();
21458                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
21459                     parseExpectedToken(57 /* QuestionToken */);
21460                 }
21461             }
21462             node.type = parseTypeAnnotation();
21463             parseSemicolon();
21464             parseExpected(19 /* CloseBraceToken */);
21465             return finishNode(node);
21466         }
21467         function parseTupleElementType() {
21468             var pos = getNodePos();
21469             if (parseOptional(25 /* DotDotDotToken */)) {
21470                 var node = createNode(177 /* RestType */, pos);
21471                 node.type = parseType();
21472                 return finishNode(node);
21473             }
21474             var type = parseType();
21475             if (!(contextFlags & 4194304 /* JSDoc */) && type.kind === 297 /* JSDocNullableType */ && type.pos === type.type.pos) {
21476                 type.kind = 176 /* OptionalType */;
21477             }
21478             return type;
21479         }
21480         function parseTupleType() {
21481             var node = createNode(175 /* TupleType */);
21482             node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21483             return finishNode(node);
21484         }
21485         function parseParenthesizedType() {
21486             var node = createNode(182 /* ParenthesizedType */);
21487             parseExpected(20 /* OpenParenToken */);
21488             node.type = parseType();
21489             parseExpected(21 /* CloseParenToken */);
21490             return finishNode(node);
21491         }
21492         function parseFunctionOrConstructorType() {
21493             var pos = getNodePos();
21494             var kind = parseOptional(99 /* NewKeyword */) ? 171 /* ConstructorType */ : 170 /* FunctionType */;
21495             var node = createNodeWithJSDoc(kind, pos);
21496             fillSignature(38 /* EqualsGreaterThanToken */, 4 /* Type */, node);
21497             return finishNode(node);
21498         }
21499         function parseKeywordAndNoDot() {
21500             var node = parseTokenNode();
21501             return token() === 24 /* DotToken */ ? undefined : node;
21502         }
21503         function parseLiteralTypeNode(negative) {
21504             var node = createNode(187 /* LiteralType */);
21505             var unaryMinusExpression;
21506             if (negative) {
21507                 unaryMinusExpression = createNode(207 /* PrefixUnaryExpression */);
21508                 unaryMinusExpression.operator = 40 /* MinusToken */;
21509                 nextToken();
21510             }
21511             var expression = token() === 106 /* TrueKeyword */ || token() === 91 /* FalseKeyword */
21512                 ? parseTokenNode()
21513                 : parseLiteralLikeNode(token());
21514             if (negative) {
21515                 unaryMinusExpression.operand = expression;
21516                 finishNode(unaryMinusExpression);
21517                 expression = unaryMinusExpression;
21518             }
21519             node.literal = expression;
21520             return finishNode(node);
21521         }
21522         function isStartOfTypeOfImportType() {
21523             nextToken();
21524             return token() === 96 /* ImportKeyword */;
21525         }
21526         function parseImportType() {
21527             sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
21528             var node = createNode(188 /* ImportType */);
21529             if (parseOptional(108 /* TypeOfKeyword */)) {
21530                 node.isTypeOf = true;
21531             }
21532             parseExpected(96 /* ImportKeyword */);
21533             parseExpected(20 /* OpenParenToken */);
21534             node.argument = parseType();
21535             parseExpected(21 /* CloseParenToken */);
21536             if (parseOptional(24 /* DotToken */)) {
21537                 node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
21538             }
21539             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
21540                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21541             }
21542             return finishNode(node);
21543         }
21544         function nextTokenIsNumericOrBigIntLiteral() {
21545             nextToken();
21546             return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
21547         }
21548         function parseNonArrayType() {
21549             switch (token()) {
21550                 case 125 /* AnyKeyword */:
21551                 case 148 /* UnknownKeyword */:
21552                 case 143 /* StringKeyword */:
21553                 case 140 /* NumberKeyword */:
21554                 case 151 /* BigIntKeyword */:
21555                 case 144 /* SymbolKeyword */:
21556                 case 128 /* BooleanKeyword */:
21557                 case 146 /* UndefinedKeyword */:
21558                 case 137 /* NeverKeyword */:
21559                 case 141 /* ObjectKeyword */:
21560                     // If these are followed by a dot, then parse these out as a dotted type reference instead.
21561                     return tryParse(parseKeywordAndNoDot) || parseTypeReference();
21562                 case 41 /* AsteriskToken */:
21563                     return parseJSDocAllType(/*postfixEquals*/ false);
21564                 case 65 /* AsteriskEqualsToken */:
21565                     return parseJSDocAllType(/*postfixEquals*/ true);
21566                 case 60 /* QuestionQuestionToken */:
21567                     // If there is '??', consider that is prefix '?' in JSDoc type.
21568                     scanner.reScanQuestionToken();
21569                 // falls through
21570                 case 57 /* QuestionToken */:
21571                     return parseJSDocUnknownOrNullableType();
21572                 case 94 /* FunctionKeyword */:
21573                     return parseJSDocFunctionType();
21574                 case 53 /* ExclamationToken */:
21575                     return parseJSDocNonNullableType();
21576                 case 14 /* NoSubstitutionTemplateLiteral */:
21577                 case 10 /* StringLiteral */:
21578                 case 8 /* NumericLiteral */:
21579                 case 9 /* BigIntLiteral */:
21580                 case 106 /* TrueKeyword */:
21581                 case 91 /* FalseKeyword */:
21582                     return parseLiteralTypeNode();
21583                 case 40 /* MinusToken */:
21584                     return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
21585                 case 110 /* VoidKeyword */:
21586                 case 100 /* NullKeyword */:
21587                     return parseTokenNode();
21588                 case 104 /* ThisKeyword */: {
21589                     var thisKeyword = parseThisTypeNode();
21590                     if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21591                         return parseThisTypePredicate(thisKeyword);
21592                     }
21593                     else {
21594                         return thisKeyword;
21595                     }
21596                 }
21597                 case 108 /* TypeOfKeyword */:
21598                     return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
21599                 case 18 /* OpenBraceToken */:
21600                     return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
21601                 case 22 /* OpenBracketToken */:
21602                     return parseTupleType();
21603                 case 20 /* OpenParenToken */:
21604                     return parseParenthesizedType();
21605                 case 96 /* ImportKeyword */:
21606                     return parseImportType();
21607                 case 124 /* AssertsKeyword */:
21608                     return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
21609                 default:
21610                     return parseTypeReference();
21611             }
21612         }
21613         function isStartOfType(inStartOfParameter) {
21614             switch (token()) {
21615                 case 125 /* AnyKeyword */:
21616                 case 148 /* UnknownKeyword */:
21617                 case 143 /* StringKeyword */:
21618                 case 140 /* NumberKeyword */:
21619                 case 151 /* BigIntKeyword */:
21620                 case 128 /* BooleanKeyword */:
21621                 case 138 /* ReadonlyKeyword */:
21622                 case 144 /* SymbolKeyword */:
21623                 case 147 /* UniqueKeyword */:
21624                 case 110 /* VoidKeyword */:
21625                 case 146 /* UndefinedKeyword */:
21626                 case 100 /* NullKeyword */:
21627                 case 104 /* ThisKeyword */:
21628                 case 108 /* TypeOfKeyword */:
21629                 case 137 /* NeverKeyword */:
21630                 case 18 /* OpenBraceToken */:
21631                 case 22 /* OpenBracketToken */:
21632                 case 29 /* LessThanToken */:
21633                 case 51 /* BarToken */:
21634                 case 50 /* AmpersandToken */:
21635                 case 99 /* NewKeyword */:
21636                 case 10 /* StringLiteral */:
21637                 case 8 /* NumericLiteral */:
21638                 case 9 /* BigIntLiteral */:
21639                 case 106 /* TrueKeyword */:
21640                 case 91 /* FalseKeyword */:
21641                 case 141 /* ObjectKeyword */:
21642                 case 41 /* AsteriskToken */:
21643                 case 57 /* QuestionToken */:
21644                 case 53 /* ExclamationToken */:
21645                 case 25 /* DotDotDotToken */:
21646                 case 132 /* InferKeyword */:
21647                 case 96 /* ImportKeyword */:
21648                 case 124 /* AssertsKeyword */:
21649                     return true;
21650                 case 94 /* FunctionKeyword */:
21651                     return !inStartOfParameter;
21652                 case 40 /* MinusToken */:
21653                     return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
21654                 case 20 /* OpenParenToken */:
21655                     // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
21656                     // or something that starts a type. We don't want to consider things like '(1)' a type.
21657                     return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
21658                 default:
21659                     return isIdentifier();
21660             }
21661         }
21662         function isStartOfParenthesizedOrFunctionType() {
21663             nextToken();
21664             return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
21665         }
21666         function parsePostfixTypeOrHigher() {
21667             var type = parseNonArrayType();
21668             while (!scanner.hasPrecedingLineBreak()) {
21669                 switch (token()) {
21670                     case 53 /* ExclamationToken */:
21671                         type = createPostfixType(298 /* JSDocNonNullableType */, type);
21672                         break;
21673                     case 57 /* QuestionToken */:
21674                         // If not in JSDoc and next token is start of a type we have a conditional type
21675                         if (!(contextFlags & 4194304 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
21676                             return type;
21677                         }
21678                         type = createPostfixType(297 /* JSDocNullableType */, type);
21679                         break;
21680                     case 22 /* OpenBracketToken */:
21681                         parseExpected(22 /* OpenBracketToken */);
21682                         if (isStartOfType()) {
21683                             var node = createNode(185 /* IndexedAccessType */, type.pos);
21684                             node.objectType = type;
21685                             node.indexType = parseType();
21686                             parseExpected(23 /* CloseBracketToken */);
21687                             type = finishNode(node);
21688                         }
21689                         else {
21690                             var node = createNode(174 /* ArrayType */, type.pos);
21691                             node.elementType = type;
21692                             parseExpected(23 /* CloseBracketToken */);
21693                             type = finishNode(node);
21694                         }
21695                         break;
21696                     default:
21697                         return type;
21698                 }
21699             }
21700             return type;
21701         }
21702         function createPostfixType(kind, type) {
21703             nextToken();
21704             var postfix = createNode(kind, type.pos);
21705             postfix.type = type;
21706             return finishNode(postfix);
21707         }
21708         function parseTypeOperator(operator) {
21709             var node = createNode(184 /* TypeOperator */);
21710             parseExpected(operator);
21711             node.operator = operator;
21712             node.type = parseTypeOperatorOrHigher();
21713             return finishNode(node);
21714         }
21715         function parseInferType() {
21716             var node = createNode(181 /* InferType */);
21717             parseExpected(132 /* InferKeyword */);
21718             var typeParameter = createNode(155 /* TypeParameter */);
21719             typeParameter.name = parseIdentifier();
21720             node.typeParameter = finishNode(typeParameter);
21721             return finishNode(node);
21722         }
21723         function parseTypeOperatorOrHigher() {
21724             var operator = token();
21725             switch (operator) {
21726                 case 134 /* KeyOfKeyword */:
21727                 case 147 /* UniqueKeyword */:
21728                 case 138 /* ReadonlyKeyword */:
21729                     return parseTypeOperator(operator);
21730                 case 132 /* InferKeyword */:
21731                     return parseInferType();
21732             }
21733             return parsePostfixTypeOrHigher();
21734         }
21735         function parseUnionOrIntersectionType(kind, parseConstituentType, operator) {
21736             var start = scanner.getStartPos();
21737             var hasLeadingOperator = parseOptional(operator);
21738             var type = parseConstituentType();
21739             if (token() === operator || hasLeadingOperator) {
21740                 var types = [type];
21741                 while (parseOptional(operator)) {
21742                     types.push(parseConstituentType());
21743                 }
21744                 var node = createNode(kind, start);
21745                 node.types = createNodeArray(types, start);
21746                 type = finishNode(node);
21747             }
21748             return type;
21749         }
21750         function parseIntersectionTypeOrHigher() {
21751             return parseUnionOrIntersectionType(179 /* IntersectionType */, parseTypeOperatorOrHigher, 50 /* AmpersandToken */);
21752         }
21753         function parseUnionTypeOrHigher() {
21754             return parseUnionOrIntersectionType(178 /* UnionType */, parseIntersectionTypeOrHigher, 51 /* BarToken */);
21755         }
21756         function isStartOfFunctionType() {
21757             if (token() === 29 /* LessThanToken */) {
21758                 return true;
21759             }
21760             return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType);
21761         }
21762         function skipParameterStart() {
21763             if (ts.isModifierKind(token())) {
21764                 // Skip modifiers
21765                 parseModifiers();
21766             }
21767             if (isIdentifier() || token() === 104 /* ThisKeyword */) {
21768                 nextToken();
21769                 return true;
21770             }
21771             if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
21772                 // Return true if we can parse an array or object binding pattern with no errors
21773                 var previousErrorCount = parseDiagnostics.length;
21774                 parseIdentifierOrPattern();
21775                 return previousErrorCount === parseDiagnostics.length;
21776             }
21777             return false;
21778         }
21779         function isUnambiguouslyStartOfFunctionType() {
21780             nextToken();
21781             if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
21782                 // ( )
21783                 // ( ...
21784                 return true;
21785             }
21786             if (skipParameterStart()) {
21787                 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
21788                 // now see if we have something that indicates a parameter declaration
21789                 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
21790                     token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
21791                     // ( xxx :
21792                     // ( xxx ,
21793                     // ( xxx ?
21794                     // ( xxx =
21795                     return true;
21796                 }
21797                 if (token() === 21 /* CloseParenToken */) {
21798                     nextToken();
21799                     if (token() === 38 /* EqualsGreaterThanToken */) {
21800                         // ( xxx ) =>
21801                         return true;
21802                     }
21803                 }
21804             }
21805             return false;
21806         }
21807         function parseTypeOrTypePredicate() {
21808             var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
21809             var type = parseType();
21810             if (typePredicateVariable) {
21811                 var node = createNode(168 /* TypePredicate */, typePredicateVariable.pos);
21812                 node.assertsModifier = undefined;
21813                 node.parameterName = typePredicateVariable;
21814                 node.type = type;
21815                 return finishNode(node);
21816             }
21817             else {
21818                 return type;
21819             }
21820         }
21821         function parseTypePredicatePrefix() {
21822             var id = parseIdentifier();
21823             if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21824                 nextToken();
21825                 return id;
21826             }
21827         }
21828         function parseAssertsTypePredicate() {
21829             var node = createNode(168 /* TypePredicate */);
21830             node.assertsModifier = parseExpectedToken(124 /* AssertsKeyword */);
21831             node.parameterName = token() === 104 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
21832             node.type = parseOptional(133 /* IsKeyword */) ? parseType() : undefined;
21833             return finishNode(node);
21834         }
21835         function parseType() {
21836             // The rules about 'yield' only apply to actual code/expression contexts.  They don't
21837             // apply to 'type' contexts.  So we disable these parameters here before moving on.
21838             return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
21839         }
21840         function parseTypeWorker(noConditionalTypes) {
21841             if (isStartOfFunctionType() || token() === 99 /* NewKeyword */) {
21842                 return parseFunctionOrConstructorType();
21843             }
21844             var type = parseUnionTypeOrHigher();
21845             if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(90 /* ExtendsKeyword */)) {
21846                 var node = createNode(180 /* ConditionalType */, type.pos);
21847                 node.checkType = type;
21848                 // The type following 'extends' is not permitted to be another conditional type
21849                 node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
21850                 parseExpected(57 /* QuestionToken */);
21851                 node.trueType = parseTypeWorker();
21852                 parseExpected(58 /* ColonToken */);
21853                 node.falseType = parseTypeWorker();
21854                 return finishNode(node);
21855             }
21856             return type;
21857         }
21858         function parseTypeAnnotation() {
21859             return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
21860         }
21861         // EXPRESSIONS
21862         function isStartOfLeftHandSideExpression() {
21863             switch (token()) {
21864                 case 104 /* ThisKeyword */:
21865                 case 102 /* SuperKeyword */:
21866                 case 100 /* NullKeyword */:
21867                 case 106 /* TrueKeyword */:
21868                 case 91 /* FalseKeyword */:
21869                 case 8 /* NumericLiteral */:
21870                 case 9 /* BigIntLiteral */:
21871                 case 10 /* StringLiteral */:
21872                 case 14 /* NoSubstitutionTemplateLiteral */:
21873                 case 15 /* TemplateHead */:
21874                 case 20 /* OpenParenToken */:
21875                 case 22 /* OpenBracketToken */:
21876                 case 18 /* OpenBraceToken */:
21877                 case 94 /* FunctionKeyword */:
21878                 case 80 /* ClassKeyword */:
21879                 case 99 /* NewKeyword */:
21880                 case 43 /* SlashToken */:
21881                 case 67 /* SlashEqualsToken */:
21882                 case 75 /* Identifier */:
21883                     return true;
21884                 case 96 /* ImportKeyword */:
21885                     return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
21886                 default:
21887                     return isIdentifier();
21888             }
21889         }
21890         function isStartOfExpression() {
21891             if (isStartOfLeftHandSideExpression()) {
21892                 return true;
21893             }
21894             switch (token()) {
21895                 case 39 /* PlusToken */:
21896                 case 40 /* MinusToken */:
21897                 case 54 /* TildeToken */:
21898                 case 53 /* ExclamationToken */:
21899                 case 85 /* DeleteKeyword */:
21900                 case 108 /* TypeOfKeyword */:
21901                 case 110 /* VoidKeyword */:
21902                 case 45 /* PlusPlusToken */:
21903                 case 46 /* MinusMinusToken */:
21904                 case 29 /* LessThanToken */:
21905                 case 127 /* AwaitKeyword */:
21906                 case 121 /* YieldKeyword */:
21907                 case 76 /* PrivateIdentifier */:
21908                     // Yield/await always starts an expression.  Either it is an identifier (in which case
21909                     // it is definitely an expression).  Or it's a keyword (either because we're in
21910                     // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
21911                     return true;
21912                 default:
21913                     // Error tolerance.  If we see the start of some binary operator, we consider
21914                     // that the start of an expression.  That way we'll parse out a missing identifier,
21915                     // give a good message about an identifier being missing, and then consume the
21916                     // rest of the binary expression.
21917                     if (isBinaryOperator()) {
21918                         return true;
21919                     }
21920                     return isIdentifier();
21921             }
21922         }
21923         function isStartOfExpressionStatement() {
21924             // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
21925             return token() !== 18 /* OpenBraceToken */ &&
21926                 token() !== 94 /* FunctionKeyword */ &&
21927                 token() !== 80 /* ClassKeyword */ &&
21928                 token() !== 59 /* AtToken */ &&
21929                 isStartOfExpression();
21930         }
21931         function parseExpression() {
21932             // Expression[in]:
21933             //      AssignmentExpression[in]
21934             //      Expression[in] , AssignmentExpression[in]
21935             // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
21936             var saveDecoratorContext = inDecoratorContext();
21937             if (saveDecoratorContext) {
21938                 setDecoratorContext(/*val*/ false);
21939             }
21940             var expr = parseAssignmentExpressionOrHigher();
21941             var operatorToken;
21942             while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
21943                 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
21944             }
21945             if (saveDecoratorContext) {
21946                 setDecoratorContext(/*val*/ true);
21947             }
21948             return expr;
21949         }
21950         function parseInitializer() {
21951             return parseOptional(62 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
21952         }
21953         function parseAssignmentExpressionOrHigher() {
21954             //  AssignmentExpression[in,yield]:
21955             //      1) ConditionalExpression[?in,?yield]
21956             //      2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
21957             //      3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
21958             //      4) ArrowFunctionExpression[?in,?yield]
21959             //      5) AsyncArrowFunctionExpression[in,yield,await]
21960             //      6) [+Yield] YieldExpression[?In]
21961             //
21962             // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
21963             // (i.e. they're both BinaryExpressions with an assignment operator in it).
21964             // First, do the simple check if we have a YieldExpression (production '6').
21965             if (isYieldExpression()) {
21966                 return parseYieldExpression();
21967             }
21968             // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
21969             // parameter list or is an async arrow function.
21970             // AsyncArrowFunctionExpression:
21971             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
21972             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
21973             // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
21974             // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
21975             //
21976             // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
21977             // not a LeftHandSideExpression, nor does it start a ConditionalExpression.  So we are done
21978             // with AssignmentExpression if we see one.
21979             var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
21980             if (arrowExpression) {
21981                 return arrowExpression;
21982             }
21983             // Now try to see if we're in production '1', '2' or '3'.  A conditional expression can
21984             // start with a LogicalOrExpression, while the assignment productions can only start with
21985             // LeftHandSideExpressions.
21986             //
21987             // So, first, we try to just parse out a BinaryExpression.  If we get something that is a
21988             // LeftHandSide or higher, then we can try to parse out the assignment expression part.
21989             // Otherwise, we try to parse out the conditional expression bit.  We want to allow any
21990             // binary expression here, so we pass in the 'lowest' precedence here so that it matches
21991             // and consumes anything.
21992             var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
21993             // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
21994             // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
21995             // identifier and the current token is an arrow.
21996             if (expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
21997                 return parseSimpleArrowFunctionExpression(expr);
21998             }
21999             // Now see if we might be in cases '2' or '3'.
22000             // If the expression was a LHS expression, and we have an assignment operator, then
22001             // we're in '2' or '3'. Consume the assignment and return.
22002             //
22003             // Note: we call reScanGreaterToken so that we get an appropriately merged token
22004             // for cases like `> > =` becoming `>>=`
22005             if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
22006                 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher());
22007             }
22008             // It wasn't an assignment or a lambda.  This is a conditional expression:
22009             return parseConditionalExpressionRest(expr);
22010         }
22011         function isYieldExpression() {
22012             if (token() === 121 /* YieldKeyword */) {
22013                 // If we have a 'yield' keyword, and this is a context where yield expressions are
22014                 // allowed, then definitely parse out a yield expression.
22015                 if (inYieldContext()) {
22016                     return true;
22017                 }
22018                 // We're in a context where 'yield expr' is not allowed.  However, if we can
22019                 // definitely tell that the user was trying to parse a 'yield expr' and not
22020                 // just a normal expr that start with a 'yield' identifier, then parse out
22021                 // a 'yield expr'.  We can then report an error later that they are only
22022                 // allowed in generator expressions.
22023                 //
22024                 // for example, if we see 'yield(foo)', then we'll have to treat that as an
22025                 // invocation expression of something called 'yield'.  However, if we have
22026                 // 'yield foo' then that is not legal as a normal expression, so we can
22027                 // definitely recognize this as a yield expression.
22028                 //
22029                 // for now we just check if the next token is an identifier.  More heuristics
22030                 // can be added here later as necessary.  We just need to make sure that we
22031                 // don't accidentally consume something legal.
22032                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22033             }
22034             return false;
22035         }
22036         function nextTokenIsIdentifierOnSameLine() {
22037             nextToken();
22038             return !scanner.hasPrecedingLineBreak() && isIdentifier();
22039         }
22040         function parseYieldExpression() {
22041             var node = createNode(212 /* YieldExpression */);
22042             // YieldExpression[In] :
22043             //      yield
22044             //      yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22045             //      yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22046             nextToken();
22047             if (!scanner.hasPrecedingLineBreak() &&
22048                 (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
22049                 node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
22050                 node.expression = parseAssignmentExpressionOrHigher();
22051                 return finishNode(node);
22052             }
22053             else {
22054                 // if the next token is not on the same line as yield.  or we don't have an '*' or
22055                 // the start of an expression, then this is just a simple "yield" expression.
22056                 return finishNode(node);
22057             }
22058         }
22059         function parseSimpleArrowFunctionExpression(identifier, asyncModifier) {
22060             ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
22061             var node;
22062             if (asyncModifier) {
22063                 node = createNode(202 /* ArrowFunction */, asyncModifier.pos);
22064                 node.modifiers = asyncModifier;
22065             }
22066             else {
22067                 node = createNode(202 /* ArrowFunction */, identifier.pos);
22068             }
22069             var parameter = createNode(156 /* Parameter */, identifier.pos);
22070             parameter.name = identifier;
22071             finishNode(parameter);
22072             node.parameters = createNodeArray([parameter], parameter.pos, parameter.end);
22073             node.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22074             node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
22075             return addJSDocComment(finishNode(node));
22076         }
22077         function tryParseParenthesizedArrowFunctionExpression() {
22078             var triState = isParenthesizedArrowFunctionExpression();
22079             if (triState === 0 /* False */) {
22080                 // It's definitely not a parenthesized arrow function expression.
22081                 return undefined;
22082             }
22083             // If we definitely have an arrow function, then we can just parse one, not requiring a
22084             // following => or { token. Otherwise, we *might* have an arrow function.  Try to parse
22085             // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
22086             // expression instead.
22087             var arrowFunction = triState === 1 /* True */
22088                 ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true)
22089                 : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead);
22090             if (!arrowFunction) {
22091                 // Didn't appear to actually be a parenthesized arrow function.  Just bail out.
22092                 return undefined;
22093             }
22094             var isAsync = hasModifierOfKind(arrowFunction, 126 /* AsyncKeyword */);
22095             // If we have an arrow, then try to parse the body. Even if not, try to parse if we
22096             // have an opening brace, just in case we're in an error state.
22097             var lastToken = token();
22098             arrowFunction.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22099             arrowFunction.body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
22100                 ? parseArrowFunctionExpressionBody(isAsync)
22101                 : parseIdentifier();
22102             return finishNode(arrowFunction);
22103         }
22104         //  True        -> We definitely expect a parenthesized arrow function here.
22105         //  False       -> There *cannot* be a parenthesized arrow function here.
22106         //  Unknown     -> There *might* be a parenthesized arrow function here.
22107         //                 Speculatively look ahead to be sure, and rollback if not.
22108         function isParenthesizedArrowFunctionExpression() {
22109             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 126 /* AsyncKeyword */) {
22110                 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
22111             }
22112             if (token() === 38 /* EqualsGreaterThanToken */) {
22113                 // ERROR RECOVERY TWEAK:
22114                 // If we see a standalone => try to parse it as an arrow function expression as that's
22115                 // likely what the user intended to write.
22116                 return 1 /* True */;
22117             }
22118             // Definitely not a parenthesized arrow function.
22119             return 0 /* False */;
22120         }
22121         function isParenthesizedArrowFunctionExpressionWorker() {
22122             if (token() === 126 /* AsyncKeyword */) {
22123                 nextToken();
22124                 if (scanner.hasPrecedingLineBreak()) {
22125                     return 0 /* False */;
22126                 }
22127                 if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
22128                     return 0 /* False */;
22129                 }
22130             }
22131             var first = token();
22132             var second = nextToken();
22133             if (first === 20 /* OpenParenToken */) {
22134                 if (second === 21 /* CloseParenToken */) {
22135                     // Simple cases: "() =>", "(): ", and "() {".
22136                     // This is an arrow function with no parameters.
22137                     // The last one is not actually an arrow function,
22138                     // but this is probably what the user intended.
22139                     var third = nextToken();
22140                     switch (third) {
22141                         case 38 /* EqualsGreaterThanToken */:
22142                         case 58 /* ColonToken */:
22143                         case 18 /* OpenBraceToken */:
22144                             return 1 /* True */;
22145                         default:
22146                             return 0 /* False */;
22147                     }
22148                 }
22149                 // If encounter "([" or "({", this could be the start of a binding pattern.
22150                 // Examples:
22151                 //      ([ x ]) => { }
22152                 //      ({ x }) => { }
22153                 //      ([ x ])
22154                 //      ({ x })
22155                 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
22156                     return 2 /* Unknown */;
22157                 }
22158                 // Simple case: "(..."
22159                 // This is an arrow function with a rest parameter.
22160                 if (second === 25 /* DotDotDotToken */) {
22161                     return 1 /* True */;
22162                 }
22163                 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
22164                 // isn't actually allowed, but we want to treat it as a lambda so we can provide
22165                 // a good error message.
22166                 if (ts.isModifierKind(second) && second !== 126 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
22167                     return 1 /* True */;
22168                 }
22169                 // If we had "(" followed by something that's not an identifier,
22170                 // then this definitely doesn't look like a lambda.  "this" is not
22171                 // valid, but we want to parse it and then give a semantic error.
22172                 if (!isIdentifier() && second !== 104 /* ThisKeyword */) {
22173                     return 0 /* False */;
22174                 }
22175                 switch (nextToken()) {
22176                     case 58 /* ColonToken */:
22177                         // If we have something like "(a:", then we must have a
22178                         // type-annotated parameter in an arrow function expression.
22179                         return 1 /* True */;
22180                     case 57 /* QuestionToken */:
22181                         nextToken();
22182                         // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
22183                         if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
22184                             return 1 /* True */;
22185                         }
22186                         // Otherwise it is definitely not a lambda.
22187                         return 0 /* False */;
22188                     case 27 /* CommaToken */:
22189                     case 62 /* EqualsToken */:
22190                     case 21 /* CloseParenToken */:
22191                         // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
22192                         return 2 /* Unknown */;
22193                 }
22194                 // It is definitely not an arrow function
22195                 return 0 /* False */;
22196             }
22197             else {
22198                 ts.Debug.assert(first === 29 /* LessThanToken */);
22199                 // If we have "<" not followed by an identifier,
22200                 // then this definitely is not an arrow function.
22201                 if (!isIdentifier()) {
22202                     return 0 /* False */;
22203                 }
22204                 // JSX overrides
22205                 if (sourceFile.languageVariant === 1 /* JSX */) {
22206                     var isArrowFunctionInJsx = lookAhead(function () {
22207                         var third = nextToken();
22208                         if (third === 90 /* ExtendsKeyword */) {
22209                             var fourth = nextToken();
22210                             switch (fourth) {
22211                                 case 62 /* EqualsToken */:
22212                                 case 31 /* GreaterThanToken */:
22213                                     return false;
22214                                 default:
22215                                     return true;
22216                             }
22217                         }
22218                         else if (third === 27 /* CommaToken */) {
22219                             return true;
22220                         }
22221                         return false;
22222                     });
22223                     if (isArrowFunctionInJsx) {
22224                         return 1 /* True */;
22225                     }
22226                     return 0 /* False */;
22227                 }
22228                 // This *could* be a parenthesized arrow function.
22229                 return 2 /* Unknown */;
22230             }
22231         }
22232         function parsePossibleParenthesizedArrowFunctionExpressionHead() {
22233             var tokenPos = scanner.getTokenPos();
22234             if (notParenthesizedArrow && notParenthesizedArrow.has(tokenPos.toString())) {
22235                 return undefined;
22236             }
22237             var result = parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
22238             if (!result) {
22239                 (notParenthesizedArrow || (notParenthesizedArrow = ts.createMap())).set(tokenPos.toString(), true);
22240             }
22241             return result;
22242         }
22243         function tryParseAsyncSimpleArrowFunctionExpression() {
22244             // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
22245             if (token() === 126 /* AsyncKeyword */) {
22246                 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
22247                     var asyncModifier = parseModifiersForArrowFunction();
22248                     var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22249                     return parseSimpleArrowFunctionExpression(expr, asyncModifier);
22250                 }
22251             }
22252             return undefined;
22253         }
22254         function isUnParenthesizedAsyncArrowFunctionWorker() {
22255             // AsyncArrowFunctionExpression:
22256             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
22257             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
22258             if (token() === 126 /* AsyncKeyword */) {
22259                 nextToken();
22260                 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
22261                 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
22262                 if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
22263                     return 0 /* False */;
22264                 }
22265                 // Check for un-parenthesized AsyncArrowFunction
22266                 var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22267                 if (!scanner.hasPrecedingLineBreak() && expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
22268                     return 1 /* True */;
22269                 }
22270             }
22271             return 0 /* False */;
22272         }
22273         function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
22274             var node = createNodeWithJSDoc(202 /* ArrowFunction */);
22275             node.modifiers = parseModifiersForArrowFunction();
22276             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
22277             // Arrow functions are never generators.
22278             //
22279             // If we're speculatively parsing a signature for a parenthesized arrow function, then
22280             // we have to have a complete parameter list.  Otherwise we might see something like
22281             // a => (b => c)
22282             // And think that "(b =>" was actually a parenthesized arrow function with a missing
22283             // close paren.
22284             if (!fillSignature(58 /* ColonToken */, isAsync, node) && !allowAmbiguity) {
22285                 return undefined;
22286             }
22287             // Parsing a signature isn't enough.
22288             // Parenthesized arrow signatures often look like other valid expressions.
22289             // For instance:
22290             //  - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
22291             //  - "(x,y)" is a comma expression parsed as a signature with two parameters.
22292             //  - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
22293             //  - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
22294             //
22295             // So we need just a bit of lookahead to ensure that it can only be a signature.
22296             var hasJSDocFunctionType = node.type && ts.isJSDocFunctionType(node.type);
22297             if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
22298                 // Returning undefined here will cause our caller to rewind to where we started from.
22299                 return undefined;
22300             }
22301             return node;
22302         }
22303         function parseArrowFunctionExpressionBody(isAsync) {
22304             if (token() === 18 /* OpenBraceToken */) {
22305                 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
22306             }
22307             if (token() !== 26 /* SemicolonToken */ &&
22308                 token() !== 94 /* FunctionKeyword */ &&
22309                 token() !== 80 /* ClassKeyword */ &&
22310                 isStartOfStatement() &&
22311                 !isStartOfExpressionStatement()) {
22312                 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
22313                 //
22314                 // Here we try to recover from a potential error situation in the case where the
22315                 // user meant to supply a block. For example, if the user wrote:
22316                 //
22317                 //  a =>
22318                 //      let v = 0;
22319                 //  }
22320                 //
22321                 // they may be missing an open brace.  Check to see if that's the case so we can
22322                 // try to recover better.  If we don't do this, then the next close curly we see may end
22323                 // up preemptively closing the containing construct.
22324                 //
22325                 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
22326                 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
22327             }
22328             return isAsync
22329                 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
22330                 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
22331         }
22332         function parseConditionalExpressionRest(leftOperand) {
22333             // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
22334             var questionToken = parseOptionalToken(57 /* QuestionToken */);
22335             if (!questionToken) {
22336                 return leftOperand;
22337             }
22338             // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
22339             // we do not that for the 'whenFalse' part.
22340             var node = createNode(210 /* ConditionalExpression */, leftOperand.pos);
22341             node.condition = leftOperand;
22342             node.questionToken = questionToken;
22343             node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
22344             node.colonToken = parseExpectedToken(58 /* ColonToken */);
22345             node.whenFalse = ts.nodeIsPresent(node.colonToken)
22346                 ? parseAssignmentExpressionOrHigher()
22347                 : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
22348             return finishNode(node);
22349         }
22350         function parseBinaryExpressionOrHigher(precedence) {
22351             var leftOperand = parseUnaryExpressionOrHigher();
22352             return parseBinaryExpressionRest(precedence, leftOperand);
22353         }
22354         function isInOrOfKeyword(t) {
22355             return t === 97 /* InKeyword */ || t === 152 /* OfKeyword */;
22356         }
22357         function parseBinaryExpressionRest(precedence, leftOperand) {
22358             while (true) {
22359                 // We either have a binary operator here, or we're finished.  We call
22360                 // reScanGreaterToken so that we merge token sequences like > and = into >=
22361                 reScanGreaterToken();
22362                 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
22363                 // Check the precedence to see if we should "take" this operator
22364                 // - For left associative operator (all operator but **), consume the operator,
22365                 //   recursively call the function below, and parse binaryExpression as a rightOperand
22366                 //   of the caller if the new precedence of the operator is greater then or equal to the current precedence.
22367                 //   For example:
22368                 //      a - b - c;
22369                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22370                 //      a * b - c
22371                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22372                 //      a - b * c;
22373                 //            ^token; leftOperand = b. Return b * c to the caller as a rightOperand
22374                 // - For right associative operator (**), consume the operator, recursively call the function
22375                 //   and parse binaryExpression as a rightOperand of the caller if the new precedence of
22376                 //   the operator is strictly grater than the current precedence
22377                 //   For example:
22378                 //      a ** b ** c;
22379                 //             ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22380                 //      a - b ** c;
22381                 //            ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22382                 //      a ** b - c
22383                 //             ^token; leftOperand = b. Return b to the caller as a rightOperand
22384                 var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
22385                     newPrecedence >= precedence :
22386                     newPrecedence > precedence;
22387                 if (!consumeCurrentOperator) {
22388                     break;
22389                 }
22390                 if (token() === 97 /* InKeyword */ && inDisallowInContext()) {
22391                     break;
22392                 }
22393                 if (token() === 123 /* AsKeyword */) {
22394                     // Make sure we *do* perform ASI for constructs like this:
22395                     //    var x = foo
22396                     //    as (Bar)
22397                     // This should be parsed as an initialized variable, followed
22398                     // by a function call to 'as' with the argument 'Bar'
22399                     if (scanner.hasPrecedingLineBreak()) {
22400                         break;
22401                     }
22402                     else {
22403                         nextToken();
22404                         leftOperand = makeAsExpression(leftOperand, parseType());
22405                     }
22406                 }
22407                 else {
22408                     leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
22409                 }
22410             }
22411             return leftOperand;
22412         }
22413         function isBinaryOperator() {
22414             if (inDisallowInContext() && token() === 97 /* InKeyword */) {
22415                 return false;
22416             }
22417             return ts.getBinaryOperatorPrecedence(token()) > 0;
22418         }
22419         function makeBinaryExpression(left, operatorToken, right) {
22420             var node = createNode(209 /* BinaryExpression */, left.pos);
22421             node.left = left;
22422             node.operatorToken = operatorToken;
22423             node.right = right;
22424             return finishNode(node);
22425         }
22426         function makeAsExpression(left, right) {
22427             var node = createNode(217 /* AsExpression */, left.pos);
22428             node.expression = left;
22429             node.type = right;
22430             return finishNode(node);
22431         }
22432         function parsePrefixUnaryExpression() {
22433             var node = createNode(207 /* PrefixUnaryExpression */);
22434             node.operator = token();
22435             nextToken();
22436             node.operand = parseSimpleUnaryExpression();
22437             return finishNode(node);
22438         }
22439         function parseDeleteExpression() {
22440             var node = createNode(203 /* DeleteExpression */);
22441             nextToken();
22442             node.expression = parseSimpleUnaryExpression();
22443             return finishNode(node);
22444         }
22445         function parseTypeOfExpression() {
22446             var node = createNode(204 /* TypeOfExpression */);
22447             nextToken();
22448             node.expression = parseSimpleUnaryExpression();
22449             return finishNode(node);
22450         }
22451         function parseVoidExpression() {
22452             var node = createNode(205 /* VoidExpression */);
22453             nextToken();
22454             node.expression = parseSimpleUnaryExpression();
22455             return finishNode(node);
22456         }
22457         function isAwaitExpression() {
22458             if (token() === 127 /* AwaitKeyword */) {
22459                 if (inAwaitContext()) {
22460                     return true;
22461                 }
22462                 // here we are using similar heuristics as 'isYieldExpression'
22463                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22464             }
22465             return false;
22466         }
22467         function parseAwaitExpression() {
22468             var node = createNode(206 /* AwaitExpression */);
22469             nextToken();
22470             node.expression = parseSimpleUnaryExpression();
22471             return finishNode(node);
22472         }
22473         /**
22474          * Parse ES7 exponential expression and await expression
22475          *
22476          * ES7 ExponentiationExpression:
22477          *      1) UnaryExpression[?Yield]
22478          *      2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
22479          *
22480          */
22481         function parseUnaryExpressionOrHigher() {
22482             /**
22483              * ES7 UpdateExpression:
22484              *      1) LeftHandSideExpression[?Yield]
22485              *      2) LeftHandSideExpression[?Yield][no LineTerminator here]++
22486              *      3) LeftHandSideExpression[?Yield][no LineTerminator here]--
22487              *      4) ++UnaryExpression[?Yield]
22488              *      5) --UnaryExpression[?Yield]
22489              */
22490             if (isUpdateExpression()) {
22491                 var updateExpression = parseUpdateExpression();
22492                 return token() === 42 /* AsteriskAsteriskToken */ ?
22493                     parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) :
22494                     updateExpression;
22495             }
22496             /**
22497              * ES7 UnaryExpression:
22498              *      1) UpdateExpression[?yield]
22499              *      2) delete UpdateExpression[?yield]
22500              *      3) void UpdateExpression[?yield]
22501              *      4) typeof UpdateExpression[?yield]
22502              *      5) + UpdateExpression[?yield]
22503              *      6) - UpdateExpression[?yield]
22504              *      7) ~ UpdateExpression[?yield]
22505              *      8) ! UpdateExpression[?yield]
22506              */
22507             var unaryOperator = token();
22508             var simpleUnaryExpression = parseSimpleUnaryExpression();
22509             if (token() === 42 /* AsteriskAsteriskToken */) {
22510                 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
22511                 var end = simpleUnaryExpression.end;
22512                 if (simpleUnaryExpression.kind === 199 /* TypeAssertionExpression */) {
22513                     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);
22514                 }
22515                 else {
22516                     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));
22517                 }
22518             }
22519             return simpleUnaryExpression;
22520         }
22521         /**
22522          * Parse ES7 simple-unary expression or higher:
22523          *
22524          * ES7 UnaryExpression:
22525          *      1) UpdateExpression[?yield]
22526          *      2) delete UnaryExpression[?yield]
22527          *      3) void UnaryExpression[?yield]
22528          *      4) typeof UnaryExpression[?yield]
22529          *      5) + UnaryExpression[?yield]
22530          *      6) - UnaryExpression[?yield]
22531          *      7) ~ UnaryExpression[?yield]
22532          *      8) ! UnaryExpression[?yield]
22533          *      9) [+Await] await UnaryExpression[?yield]
22534          */
22535         function parseSimpleUnaryExpression() {
22536             switch (token()) {
22537                 case 39 /* PlusToken */:
22538                 case 40 /* MinusToken */:
22539                 case 54 /* TildeToken */:
22540                 case 53 /* ExclamationToken */:
22541                     return parsePrefixUnaryExpression();
22542                 case 85 /* DeleteKeyword */:
22543                     return parseDeleteExpression();
22544                 case 108 /* TypeOfKeyword */:
22545                     return parseTypeOfExpression();
22546                 case 110 /* VoidKeyword */:
22547                     return parseVoidExpression();
22548                 case 29 /* LessThanToken */:
22549                     // This is modified UnaryExpression grammar in TypeScript
22550                     //  UnaryExpression (modified):
22551                     //      < type > UnaryExpression
22552                     return parseTypeAssertion();
22553                 case 127 /* AwaitKeyword */:
22554                     if (isAwaitExpression()) {
22555                         return parseAwaitExpression();
22556                     }
22557                 // falls through
22558                 default:
22559                     return parseUpdateExpression();
22560             }
22561         }
22562         /**
22563          * Check if the current token can possibly be an ES7 increment expression.
22564          *
22565          * ES7 UpdateExpression:
22566          *      LeftHandSideExpression[?Yield]
22567          *      LeftHandSideExpression[?Yield][no LineTerminator here]++
22568          *      LeftHandSideExpression[?Yield][no LineTerminator here]--
22569          *      ++LeftHandSideExpression[?Yield]
22570          *      --LeftHandSideExpression[?Yield]
22571          */
22572         function isUpdateExpression() {
22573             // This function is called inside parseUnaryExpression to decide
22574             // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
22575             switch (token()) {
22576                 case 39 /* PlusToken */:
22577                 case 40 /* MinusToken */:
22578                 case 54 /* TildeToken */:
22579                 case 53 /* ExclamationToken */:
22580                 case 85 /* DeleteKeyword */:
22581                 case 108 /* TypeOfKeyword */:
22582                 case 110 /* VoidKeyword */:
22583                 case 127 /* AwaitKeyword */:
22584                     return false;
22585                 case 29 /* LessThanToken */:
22586                     // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
22587                     if (sourceFile.languageVariant !== 1 /* JSX */) {
22588                         return false;
22589                     }
22590                 // We are in JSX context and the token is part of JSXElement.
22591                 // falls through
22592                 default:
22593                     return true;
22594             }
22595         }
22596         /**
22597          * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
22598          *
22599          * ES7 UpdateExpression[yield]:
22600          *      1) LeftHandSideExpression[?yield]
22601          *      2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
22602          *      3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
22603          *      4) ++LeftHandSideExpression[?yield]
22604          *      5) --LeftHandSideExpression[?yield]
22605          * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
22606          */
22607         function parseUpdateExpression() {
22608             if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
22609                 var node = createNode(207 /* PrefixUnaryExpression */);
22610                 node.operator = token();
22611                 nextToken();
22612                 node.operand = parseLeftHandSideExpressionOrHigher();
22613                 return finishNode(node);
22614             }
22615             else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
22616                 // JSXElement is part of primaryExpression
22617                 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
22618             }
22619             var expression = parseLeftHandSideExpressionOrHigher();
22620             ts.Debug.assert(ts.isLeftHandSideExpression(expression));
22621             if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
22622                 var node = createNode(208 /* PostfixUnaryExpression */, expression.pos);
22623                 node.operand = expression;
22624                 node.operator = token();
22625                 nextToken();
22626                 return finishNode(node);
22627             }
22628             return expression;
22629         }
22630         function parseLeftHandSideExpressionOrHigher() {
22631             // Original Ecma:
22632             // LeftHandSideExpression: See 11.2
22633             //      NewExpression
22634             //      CallExpression
22635             //
22636             // Our simplification:
22637             //
22638             // LeftHandSideExpression: See 11.2
22639             //      MemberExpression
22640             //      CallExpression
22641             //
22642             // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
22643             // MemberExpression to make our lives easier.
22644             //
22645             // to best understand the below code, it's important to see how CallExpression expands
22646             // out into its own productions:
22647             //
22648             // CallExpression:
22649             //      MemberExpression Arguments
22650             //      CallExpression Arguments
22651             //      CallExpression[Expression]
22652             //      CallExpression.IdentifierName
22653             //      import (AssignmentExpression)
22654             //      super Arguments
22655             //      super.IdentifierName
22656             //
22657             // Because of the recursion in these calls, we need to bottom out first. There are three
22658             // bottom out states we can run into: 1) We see 'super' which must start either of
22659             // the last two CallExpression productions. 2) We see 'import' which must start import call.
22660             // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
22661             // or starts the beginning of the first four CallExpression productions.
22662             var expression;
22663             if (token() === 96 /* ImportKeyword */) {
22664                 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
22665                     // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
22666                     // For example:
22667                     //      var foo3 = require("subfolder
22668                     //      import * as foo1 from "module-from-node
22669                     // We want this import to be a statement rather than import call expression
22670                     sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
22671                     expression = parseTokenNode();
22672                 }
22673                 else if (lookAhead(nextTokenIsDot)) {
22674                     // This is an 'import.*' metaproperty (i.e. 'import.meta')
22675                     var fullStart = scanner.getStartPos();
22676                     nextToken(); // advance past the 'import'
22677                     nextToken(); // advance past the dot
22678                     var node = createNode(219 /* MetaProperty */, fullStart);
22679                     node.keywordToken = 96 /* ImportKeyword */;
22680                     node.name = parseIdentifierName();
22681                     expression = finishNode(node);
22682                     sourceFile.flags |= 2097152 /* PossiblyContainsImportMeta */;
22683                 }
22684                 else {
22685                     expression = parseMemberExpressionOrHigher();
22686                 }
22687             }
22688             else {
22689                 expression = token() === 102 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
22690             }
22691             // Now, we *may* be complete.  However, we might have consumed the start of a
22692             // CallExpression or OptionalExpression.  As such, we need to consume the rest
22693             // of it here to be complete.
22694             return parseCallExpressionRest(expression);
22695         }
22696         function parseMemberExpressionOrHigher() {
22697             // Note: to make our lives simpler, we decompose the NewExpression productions and
22698             // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
22699             // like so:
22700             //
22701             //   PrimaryExpression : See 11.1
22702             //      this
22703             //      Identifier
22704             //      Literal
22705             //      ArrayLiteral
22706             //      ObjectLiteral
22707             //      (Expression)
22708             //      FunctionExpression
22709             //      new MemberExpression Arguments?
22710             //
22711             //   MemberExpression : See 11.2
22712             //      PrimaryExpression
22713             //      MemberExpression[Expression]
22714             //      MemberExpression.IdentifierName
22715             //
22716             //   CallExpression : See 11.2
22717             //      MemberExpression
22718             //      CallExpression Arguments
22719             //      CallExpression[Expression]
22720             //      CallExpression.IdentifierName
22721             //
22722             // Technically this is ambiguous.  i.e. CallExpression defines:
22723             //
22724             //   CallExpression:
22725             //      CallExpression Arguments
22726             //
22727             // If you see: "new Foo()"
22728             //
22729             // Then that could be treated as a single ObjectCreationExpression, or it could be
22730             // treated as the invocation of "new Foo".  We disambiguate that in code (to match
22731             // the original grammar) by making sure that if we see an ObjectCreationExpression
22732             // we always consume arguments if they are there. So we treat "new Foo()" as an
22733             // object creation only, and not at all as an invocation.  Another way to think
22734             // about this is that for every "new" that we see, we will consume an argument list if
22735             // it is there as part of the *associated* object creation node.  Any additional
22736             // argument lists we see, will become invocation expressions.
22737             //
22738             // Because there are no other places in the grammar now that refer to FunctionExpression
22739             // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
22740             // production.
22741             //
22742             // Because CallExpression and MemberExpression are left recursive, we need to bottom out
22743             // of the recursion immediately.  So we parse out a primary expression to start with.
22744             var expression = parsePrimaryExpression();
22745             return parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
22746         }
22747         function parseSuperExpression() {
22748             var expression = parseTokenNode();
22749             if (token() === 29 /* LessThanToken */) {
22750                 var startPos = getNodePos();
22751                 var typeArguments = tryParse(parseTypeArgumentsInExpression);
22752                 if (typeArguments !== undefined) {
22753                     parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
22754                 }
22755             }
22756             if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
22757                 return expression;
22758             }
22759             // If we have seen "super" it must be followed by '(' or '.'.
22760             // If it wasn't then just try to parse out a '.' and report an error.
22761             var node = createNode(194 /* PropertyAccessExpression */, expression.pos);
22762             node.expression = expression;
22763             parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
22764             // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
22765             node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
22766             return finishNode(node);
22767         }
22768         function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) {
22769             var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
22770             var result;
22771             if (opening.kind === 268 /* JsxOpeningElement */) {
22772                 var node = createNode(266 /* JsxElement */, opening.pos);
22773                 node.openingElement = opening;
22774                 node.children = parseJsxChildren(node.openingElement);
22775                 node.closingElement = parseJsxClosingElement(inExpressionContext);
22776                 if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
22777                     parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName));
22778                 }
22779                 result = finishNode(node);
22780             }
22781             else if (opening.kind === 271 /* JsxOpeningFragment */) {
22782                 var node = createNode(270 /* JsxFragment */, opening.pos);
22783                 node.openingFragment = opening;
22784                 node.children = parseJsxChildren(node.openingFragment);
22785                 node.closingFragment = parseJsxClosingFragment(inExpressionContext);
22786                 result = finishNode(node);
22787             }
22788             else {
22789                 ts.Debug.assert(opening.kind === 267 /* JsxSelfClosingElement */);
22790                 // Nothing else to do for self-closing elements
22791                 result = opening;
22792             }
22793             // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
22794             // an enclosing tag), we'll naively try to parse   ^ this as a 'less than' operator and the remainder of the tag
22795             // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
22796             // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
22797             // does less damage and we can report a better error.
22798             // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
22799             // of one sort or another.
22800             if (inExpressionContext && token() === 29 /* LessThanToken */) {
22801                 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); });
22802                 if (invalidElement) {
22803                     parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
22804                     var badNode = createNode(209 /* BinaryExpression */, result.pos);
22805                     badNode.end = invalidElement.end;
22806                     badNode.left = result;
22807                     badNode.right = invalidElement;
22808                     badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
22809                     badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
22810                     return badNode;
22811                 }
22812             }
22813             return result;
22814         }
22815         function parseJsxText() {
22816             var node = createNode(11 /* JsxText */);
22817             node.text = scanner.getTokenValue();
22818             node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
22819             currentToken = scanner.scanJsxToken();
22820             return finishNode(node);
22821         }
22822         function parseJsxChild(openingTag, token) {
22823             switch (token) {
22824                 case 1 /* EndOfFileToken */:
22825                     // If we hit EOF, issue the error at the tag that lacks the closing element
22826                     // rather than at the end of the file (which is useless)
22827                     if (ts.isJsxOpeningFragment(openingTag)) {
22828                         parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
22829                     }
22830                     else {
22831                         // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
22832                         // or to cover only 'Foo' in < Foo >
22833                         var tag = openingTag.tagName;
22834                         var start = ts.skipTrivia(sourceText, tag.pos);
22835                         parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
22836                     }
22837                     return undefined;
22838                 case 30 /* LessThanSlashToken */:
22839                 case 7 /* ConflictMarkerTrivia */:
22840                     return undefined;
22841                 case 11 /* JsxText */:
22842                 case 12 /* JsxTextAllWhiteSpaces */:
22843                     return parseJsxText();
22844                 case 18 /* OpenBraceToken */:
22845                     return parseJsxExpression(/*inExpressionContext*/ false);
22846                 case 29 /* LessThanToken */:
22847                     return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
22848                 default:
22849                     return ts.Debug.assertNever(token);
22850             }
22851         }
22852         function parseJsxChildren(openingTag) {
22853             var list = [];
22854             var listPos = getNodePos();
22855             var saveParsingContext = parsingContext;
22856             parsingContext |= 1 << 14 /* JsxChildren */;
22857             while (true) {
22858                 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
22859                 if (!child)
22860                     break;
22861                 list.push(child);
22862             }
22863             parsingContext = saveParsingContext;
22864             return createNodeArray(list, listPos);
22865         }
22866         function parseJsxAttributes() {
22867             var jsxAttributes = createNode(274 /* JsxAttributes */);
22868             jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
22869             return finishNode(jsxAttributes);
22870         }
22871         function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
22872             var fullStart = scanner.getStartPos();
22873             parseExpected(29 /* LessThanToken */);
22874             if (token() === 31 /* GreaterThanToken */) {
22875                 // See below for explanation of scanJsxText
22876                 var node_1 = createNode(271 /* JsxOpeningFragment */, fullStart);
22877                 scanJsxText();
22878                 return finishNode(node_1);
22879             }
22880             var tagName = parseJsxElementName();
22881             var typeArguments = tryParseTypeArguments();
22882             var attributes = parseJsxAttributes();
22883             var node;
22884             if (token() === 31 /* GreaterThanToken */) {
22885                 // Closing tag, so scan the immediately-following text with the JSX scanning instead
22886                 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
22887                 // scanning errors
22888                 node = createNode(268 /* JsxOpeningElement */, fullStart);
22889                 scanJsxText();
22890             }
22891             else {
22892                 parseExpected(43 /* SlashToken */);
22893                 if (inExpressionContext) {
22894                     parseExpected(31 /* GreaterThanToken */);
22895                 }
22896                 else {
22897                     parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22898                     scanJsxText();
22899                 }
22900                 node = createNode(267 /* JsxSelfClosingElement */, fullStart);
22901             }
22902             node.tagName = tagName;
22903             node.typeArguments = typeArguments;
22904             node.attributes = attributes;
22905             return finishNode(node);
22906         }
22907         function parseJsxElementName() {
22908             scanJsxIdentifier();
22909             // JsxElement can have name in the form of
22910             //      propertyAccessExpression
22911             //      primaryExpression in the form of an identifier and "this" keyword
22912             // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
22913             // We only want to consider "this" as a primaryExpression
22914             var expression = token() === 104 /* ThisKeyword */ ?
22915                 parseTokenNode() : parseIdentifierName();
22916             while (parseOptional(24 /* DotToken */)) {
22917                 var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
22918                 propertyAccess.expression = expression;
22919                 propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false);
22920                 expression = finishNode(propertyAccess);
22921             }
22922             return expression;
22923         }
22924         function parseJsxExpression(inExpressionContext) {
22925             var node = createNode(276 /* JsxExpression */);
22926             if (!parseExpected(18 /* OpenBraceToken */)) {
22927                 return undefined;
22928             }
22929             if (token() !== 19 /* CloseBraceToken */) {
22930                 node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
22931                 // Only an AssignmentExpression is valid here per the JSX spec,
22932                 // but we can unambiguously parse a comma sequence and provide
22933                 // a better error message in grammar checking.
22934                 node.expression = parseExpression();
22935             }
22936             if (inExpressionContext) {
22937                 parseExpected(19 /* CloseBraceToken */);
22938             }
22939             else {
22940                 if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
22941                     scanJsxText();
22942                 }
22943             }
22944             return finishNode(node);
22945         }
22946         function parseJsxAttribute() {
22947             if (token() === 18 /* OpenBraceToken */) {
22948                 return parseJsxSpreadAttribute();
22949             }
22950             scanJsxIdentifier();
22951             var node = createNode(273 /* JsxAttribute */);
22952             node.name = parseIdentifierName();
22953             if (token() === 62 /* EqualsToken */) {
22954                 switch (scanJsxAttributeValue()) {
22955                     case 10 /* StringLiteral */:
22956                         node.initializer = parseLiteralNode();
22957                         break;
22958                     default:
22959                         node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
22960                         break;
22961                 }
22962             }
22963             return finishNode(node);
22964         }
22965         function parseJsxSpreadAttribute() {
22966             var node = createNode(275 /* JsxSpreadAttribute */);
22967             parseExpected(18 /* OpenBraceToken */);
22968             parseExpected(25 /* DotDotDotToken */);
22969             node.expression = parseExpression();
22970             parseExpected(19 /* CloseBraceToken */);
22971             return finishNode(node);
22972         }
22973         function parseJsxClosingElement(inExpressionContext) {
22974             var node = createNode(269 /* JsxClosingElement */);
22975             parseExpected(30 /* LessThanSlashToken */);
22976             node.tagName = parseJsxElementName();
22977             if (inExpressionContext) {
22978                 parseExpected(31 /* GreaterThanToken */);
22979             }
22980             else {
22981                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22982                 scanJsxText();
22983             }
22984             return finishNode(node);
22985         }
22986         function parseJsxClosingFragment(inExpressionContext) {
22987             var node = createNode(272 /* JsxClosingFragment */);
22988             parseExpected(30 /* LessThanSlashToken */);
22989             if (ts.tokenIsIdentifierOrKeyword(token())) {
22990                 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
22991             }
22992             if (inExpressionContext) {
22993                 parseExpected(31 /* GreaterThanToken */);
22994             }
22995             else {
22996                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22997                 scanJsxText();
22998             }
22999             return finishNode(node);
23000         }
23001         function parseTypeAssertion() {
23002             var node = createNode(199 /* TypeAssertionExpression */);
23003             parseExpected(29 /* LessThanToken */);
23004             node.type = parseType();
23005             parseExpected(31 /* GreaterThanToken */);
23006             node.expression = parseSimpleUnaryExpression();
23007             return finishNode(node);
23008         }
23009         function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
23010             nextToken();
23011             return ts.tokenIsIdentifierOrKeyword(token())
23012                 || token() === 22 /* OpenBracketToken */
23013                 || isTemplateStartOfTaggedTemplate();
23014         }
23015         function isStartOfOptionalPropertyOrElementAccessChain() {
23016             return token() === 28 /* QuestionDotToken */
23017                 && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
23018         }
23019         function tryReparseOptionalChain(node) {
23020             if (node.flags & 32 /* OptionalChain */) {
23021                 return true;
23022             }
23023             // check for an optional chain in a non-null expression
23024             if (ts.isNonNullExpression(node)) {
23025                 var expr = node.expression;
23026                 while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
23027                     expr = expr.expression;
23028                 }
23029                 if (expr.flags & 32 /* OptionalChain */) {
23030                     // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
23031                     while (ts.isNonNullExpression(node)) {
23032                         node.flags |= 32 /* OptionalChain */;
23033                         node = node.expression;
23034                     }
23035                     return true;
23036                 }
23037             }
23038             return false;
23039         }
23040         function parsePropertyAccessExpressionRest(expression, questionDotToken) {
23041             var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23042             propertyAccess.expression = expression;
23043             propertyAccess.questionDotToken = questionDotToken;
23044             propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
23045             if (questionDotToken || tryReparseOptionalChain(expression)) {
23046                 propertyAccess.flags |= 32 /* OptionalChain */;
23047                 if (ts.isPrivateIdentifier(propertyAccess.name)) {
23048                     parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
23049                 }
23050             }
23051             return finishNode(propertyAccess);
23052         }
23053         function parseElementAccessExpressionRest(expression, questionDotToken) {
23054             var indexedAccess = createNode(195 /* ElementAccessExpression */, expression.pos);
23055             indexedAccess.expression = expression;
23056             indexedAccess.questionDotToken = questionDotToken;
23057             if (token() === 23 /* CloseBracketToken */) {
23058                 indexedAccess.argumentExpression = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
23059             }
23060             else {
23061                 var argument = allowInAnd(parseExpression);
23062                 if (ts.isStringOrNumericLiteralLike(argument)) {
23063                     argument.text = internIdentifier(argument.text);
23064                 }
23065                 indexedAccess.argumentExpression = argument;
23066             }
23067             parseExpected(23 /* CloseBracketToken */);
23068             if (questionDotToken || tryReparseOptionalChain(expression)) {
23069                 indexedAccess.flags |= 32 /* OptionalChain */;
23070             }
23071             return finishNode(indexedAccess);
23072         }
23073         function parseMemberExpressionRest(expression, allowOptionalChain) {
23074             while (true) {
23075                 var questionDotToken = void 0;
23076                 var isPropertyAccess = false;
23077                 if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
23078                     questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
23079                     isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
23080                 }
23081                 else {
23082                     isPropertyAccess = parseOptional(24 /* DotToken */);
23083                 }
23084                 if (isPropertyAccess) {
23085                     expression = parsePropertyAccessExpressionRest(expression, questionDotToken);
23086                     continue;
23087                 }
23088                 if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
23089                     nextToken();
23090                     var nonNullExpression = createNode(218 /* NonNullExpression */, expression.pos);
23091                     nonNullExpression.expression = expression;
23092                     expression = finishNode(nonNullExpression);
23093                     continue;
23094                 }
23095                 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
23096                 if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
23097                     expression = parseElementAccessExpressionRest(expression, questionDotToken);
23098                     continue;
23099                 }
23100                 if (isTemplateStartOfTaggedTemplate()) {
23101                     expression = parseTaggedTemplateRest(expression, questionDotToken, /*typeArguments*/ undefined);
23102                     continue;
23103                 }
23104                 return expression;
23105             }
23106         }
23107         function isTemplateStartOfTaggedTemplate() {
23108             return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
23109         }
23110         function parseTaggedTemplateRest(tag, questionDotToken, typeArguments) {
23111             var tagExpression = createNode(198 /* TaggedTemplateExpression */, tag.pos);
23112             tagExpression.tag = tag;
23113             tagExpression.questionDotToken = questionDotToken;
23114             tagExpression.typeArguments = typeArguments;
23115             tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */
23116                 ? (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode())
23117                 : parseTemplateExpression(/*isTaggedTemplate*/ true);
23118             if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
23119                 tagExpression.flags |= 32 /* OptionalChain */;
23120             }
23121             return finishNode(tagExpression);
23122         }
23123         function parseCallExpressionRest(expression) {
23124             while (true) {
23125                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
23126                 var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
23127                 // handle 'foo<<T>()'
23128                 if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
23129                     // See if this is the start of a generic invocation.  If so, consume it and
23130                     // keep checking for postfix expressions.  Otherwise, it's just a '<' that's
23131                     // part of an arithmetic expression.  Break out so we consume it higher in the
23132                     // stack.
23133                     var typeArguments = tryParse(parseTypeArgumentsInExpression);
23134                     if (typeArguments) {
23135                         if (isTemplateStartOfTaggedTemplate()) {
23136                             expression = parseTaggedTemplateRest(expression, questionDotToken, typeArguments);
23137                             continue;
23138                         }
23139                         var callExpr = createNode(196 /* CallExpression */, expression.pos);
23140                         callExpr.expression = expression;
23141                         callExpr.questionDotToken = questionDotToken;
23142                         callExpr.typeArguments = typeArguments;
23143                         callExpr.arguments = parseArgumentList();
23144                         if (questionDotToken || tryReparseOptionalChain(expression)) {
23145                             callExpr.flags |= 32 /* OptionalChain */;
23146                         }
23147                         expression = finishNode(callExpr);
23148                         continue;
23149                     }
23150                 }
23151                 else if (token() === 20 /* OpenParenToken */) {
23152                     var callExpr = createNode(196 /* CallExpression */, expression.pos);
23153                     callExpr.expression = expression;
23154                     callExpr.questionDotToken = questionDotToken;
23155                     callExpr.arguments = parseArgumentList();
23156                     if (questionDotToken || tryReparseOptionalChain(expression)) {
23157                         callExpr.flags |= 32 /* OptionalChain */;
23158                     }
23159                     expression = finishNode(callExpr);
23160                     continue;
23161                 }
23162                 if (questionDotToken) {
23163                     // We failed to parse anything, so report a missing identifier here.
23164                     var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23165                     propertyAccess.expression = expression;
23166                     propertyAccess.questionDotToken = questionDotToken;
23167                     propertyAccess.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
23168                     propertyAccess.flags |= 32 /* OptionalChain */;
23169                     expression = finishNode(propertyAccess);
23170                 }
23171                 break;
23172             }
23173             return expression;
23174         }
23175         function parseArgumentList() {
23176             parseExpected(20 /* OpenParenToken */);
23177             var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
23178             parseExpected(21 /* CloseParenToken */);
23179             return result;
23180         }
23181         function parseTypeArgumentsInExpression() {
23182             if (reScanLessThanToken() !== 29 /* LessThanToken */) {
23183                 return undefined;
23184             }
23185             nextToken();
23186             var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
23187             if (!parseExpected(31 /* GreaterThanToken */)) {
23188                 // If it doesn't have the closing `>` then it's definitely not an type argument list.
23189                 return undefined;
23190             }
23191             // If we have a '<', then only parse this as a argument list if the type arguments
23192             // are complete and we have an open paren.  if we don't, rewind and return nothing.
23193             return typeArguments && canFollowTypeArgumentsInExpression()
23194                 ? typeArguments
23195                 : undefined;
23196         }
23197         function canFollowTypeArgumentsInExpression() {
23198             switch (token()) {
23199                 case 20 /* OpenParenToken */: // foo<x>(
23200                 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
23201                 case 15 /* TemplateHead */: // foo<T> `...${100}...`
23202                 // these are the only tokens can legally follow a type argument
23203                 // list. So we definitely want to treat them as type arg lists.
23204                 // falls through
23205                 case 24 /* DotToken */: // foo<x>.
23206                 case 21 /* CloseParenToken */: // foo<x>)
23207                 case 23 /* CloseBracketToken */: // foo<x>]
23208                 case 58 /* ColonToken */: // foo<x>:
23209                 case 26 /* SemicolonToken */: // foo<x>;
23210                 case 57 /* QuestionToken */: // foo<x>?
23211                 case 34 /* EqualsEqualsToken */: // foo<x> ==
23212                 case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
23213                 case 35 /* ExclamationEqualsToken */: // foo<x> !=
23214                 case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
23215                 case 55 /* AmpersandAmpersandToken */: // foo<x> &&
23216                 case 56 /* BarBarToken */: // foo<x> ||
23217                 case 60 /* QuestionQuestionToken */: // foo<x> ??
23218                 case 52 /* CaretToken */: // foo<x> ^
23219                 case 50 /* AmpersandToken */: // foo<x> &
23220                 case 51 /* BarToken */: // foo<x> |
23221                 case 19 /* CloseBraceToken */: // foo<x> }
23222                 case 1 /* EndOfFileToken */: // foo<x>
23223                     // these cases can't legally follow a type arg list.  However, they're not legal
23224                     // expressions either.  The user is probably in the middle of a generic type. So
23225                     // treat it as such.
23226                     return true;
23227                 case 27 /* CommaToken */: // foo<x>,
23228                 case 18 /* OpenBraceToken */: // foo<x> {
23229                 // We don't want to treat these as type arguments.  Otherwise we'll parse this
23230                 // as an invocation expression.  Instead, we want to parse out the expression
23231                 // in isolation from the type arguments.
23232                 // falls through
23233                 default:
23234                     // Anything else treat as an expression.
23235                     return false;
23236             }
23237         }
23238         function parsePrimaryExpression() {
23239             switch (token()) {
23240                 case 8 /* NumericLiteral */:
23241                 case 9 /* BigIntLiteral */:
23242                 case 10 /* StringLiteral */:
23243                 case 14 /* NoSubstitutionTemplateLiteral */:
23244                     return parseLiteralNode();
23245                 case 104 /* ThisKeyword */:
23246                 case 102 /* SuperKeyword */:
23247                 case 100 /* NullKeyword */:
23248                 case 106 /* TrueKeyword */:
23249                 case 91 /* FalseKeyword */:
23250                     return parseTokenNode();
23251                 case 20 /* OpenParenToken */:
23252                     return parseParenthesizedExpression();
23253                 case 22 /* OpenBracketToken */:
23254                     return parseArrayLiteralExpression();
23255                 case 18 /* OpenBraceToken */:
23256                     return parseObjectLiteralExpression();
23257                 case 126 /* AsyncKeyword */:
23258                     // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
23259                     // If we encounter `async [no LineTerminator here] function` then this is an async
23260                     // function; otherwise, its an identifier.
23261                     if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
23262                         break;
23263                     }
23264                     return parseFunctionExpression();
23265                 case 80 /* ClassKeyword */:
23266                     return parseClassExpression();
23267                 case 94 /* FunctionKeyword */:
23268                     return parseFunctionExpression();
23269                 case 99 /* NewKeyword */:
23270                     return parseNewExpressionOrNewDotTarget();
23271                 case 43 /* SlashToken */:
23272                 case 67 /* SlashEqualsToken */:
23273                     if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
23274                         return parseLiteralNode();
23275                     }
23276                     break;
23277                 case 15 /* TemplateHead */:
23278                     return parseTemplateExpression(/* isTaggedTemplate */ false);
23279             }
23280             return parseIdentifier(ts.Diagnostics.Expression_expected);
23281         }
23282         function parseParenthesizedExpression() {
23283             var node = createNodeWithJSDoc(200 /* ParenthesizedExpression */);
23284             parseExpected(20 /* OpenParenToken */);
23285             node.expression = allowInAnd(parseExpression);
23286             parseExpected(21 /* CloseParenToken */);
23287             return finishNode(node);
23288         }
23289         function parseSpreadElement() {
23290             var node = createNode(213 /* SpreadElement */);
23291             parseExpected(25 /* DotDotDotToken */);
23292             node.expression = parseAssignmentExpressionOrHigher();
23293             return finishNode(node);
23294         }
23295         function parseArgumentOrArrayLiteralElement() {
23296             return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
23297                 token() === 27 /* CommaToken */ ? createNode(215 /* OmittedExpression */) :
23298                     parseAssignmentExpressionOrHigher();
23299         }
23300         function parseArgumentExpression() {
23301             return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
23302         }
23303         function parseArrayLiteralExpression() {
23304             var node = createNode(192 /* ArrayLiteralExpression */);
23305             parseExpected(22 /* OpenBracketToken */);
23306             if (scanner.hasPrecedingLineBreak()) {
23307                 node.multiLine = true;
23308             }
23309             node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
23310             parseExpected(23 /* CloseBracketToken */);
23311             return finishNode(node);
23312         }
23313         function parseObjectLiteralElement() {
23314             var node = createNodeWithJSDoc(0 /* Unknown */);
23315             if (parseOptionalToken(25 /* DotDotDotToken */)) {
23316                 node.kind = 283 /* SpreadAssignment */;
23317                 node.expression = parseAssignmentExpressionOrHigher();
23318                 return finishNode(node);
23319             }
23320             node.decorators = parseDecorators();
23321             node.modifiers = parseModifiers();
23322             if (parseContextualModifier(131 /* GetKeyword */)) {
23323                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
23324             }
23325             if (parseContextualModifier(142 /* SetKeyword */)) {
23326                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
23327             }
23328             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23329             var tokenIsIdentifier = isIdentifier();
23330             node.name = parsePropertyName();
23331             // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
23332             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
23333             node.exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
23334             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
23335                 return parseMethodDeclaration(node, asteriskToken);
23336             }
23337             // check if it is short-hand property assignment or normal property assignment
23338             // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
23339             // CoverInitializedName[Yield] :
23340             //     IdentifierReference[?Yield] Initializer[In, ?Yield]
23341             // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
23342             var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
23343             if (isShorthandPropertyAssignment) {
23344                 node.kind = 282 /* ShorthandPropertyAssignment */;
23345                 var equalsToken = parseOptionalToken(62 /* EqualsToken */);
23346                 if (equalsToken) {
23347                     node.equalsToken = equalsToken;
23348                     node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
23349                 }
23350             }
23351             else {
23352                 node.kind = 281 /* PropertyAssignment */;
23353                 parseExpected(58 /* ColonToken */);
23354                 node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
23355             }
23356             return finishNode(node);
23357         }
23358         function parseObjectLiteralExpression() {
23359             var node = createNode(193 /* ObjectLiteralExpression */);
23360             var openBracePosition = scanner.getTokenPos();
23361             parseExpected(18 /* OpenBraceToken */);
23362             if (scanner.hasPrecedingLineBreak()) {
23363                 node.multiLine = true;
23364             }
23365             node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
23366             if (!parseExpected(19 /* CloseBraceToken */)) {
23367                 var lastError = ts.lastOrUndefined(parseDiagnostics);
23368                 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23369                     ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23370                 }
23371             }
23372             return finishNode(node);
23373         }
23374         function parseFunctionExpression() {
23375             // GeneratorExpression:
23376             //      function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
23377             //
23378             // FunctionExpression:
23379             //      function BindingIdentifier[opt](FormalParameters){ FunctionBody }
23380             var saveDecoratorContext = inDecoratorContext();
23381             if (saveDecoratorContext) {
23382                 setDecoratorContext(/*val*/ false);
23383             }
23384             var node = createNodeWithJSDoc(201 /* FunctionExpression */);
23385             node.modifiers = parseModifiers();
23386             parseExpected(94 /* FunctionKeyword */);
23387             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23388             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
23389             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
23390             node.name =
23391                 isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
23392                     isGenerator ? doInYieldContext(parseOptionalIdentifier) :
23393                         isAsync ? doInAwaitContext(parseOptionalIdentifier) :
23394                             parseOptionalIdentifier();
23395             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
23396             node.body = parseFunctionBlock(isGenerator | isAsync);
23397             if (saveDecoratorContext) {
23398                 setDecoratorContext(/*val*/ true);
23399             }
23400             return finishNode(node);
23401         }
23402         function parseOptionalIdentifier() {
23403             return isIdentifier() ? parseIdentifier() : undefined;
23404         }
23405         function parseNewExpressionOrNewDotTarget() {
23406             var fullStart = scanner.getStartPos();
23407             parseExpected(99 /* NewKeyword */);
23408             if (parseOptional(24 /* DotToken */)) {
23409                 var node_2 = createNode(219 /* MetaProperty */, fullStart);
23410                 node_2.keywordToken = 99 /* NewKeyword */;
23411                 node_2.name = parseIdentifierName();
23412                 return finishNode(node_2);
23413             }
23414             var expression = parsePrimaryExpression();
23415             var typeArguments;
23416             while (true) {
23417                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ false);
23418                 typeArguments = tryParse(parseTypeArgumentsInExpression);
23419                 if (isTemplateStartOfTaggedTemplate()) {
23420                     ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
23421                     expression = parseTaggedTemplateRest(expression, /*optionalChain*/ undefined, typeArguments);
23422                     typeArguments = undefined;
23423                 }
23424                 break;
23425             }
23426             var node = createNode(197 /* NewExpression */, fullStart);
23427             node.expression = expression;
23428             node.typeArguments = typeArguments;
23429             if (token() === 20 /* OpenParenToken */) {
23430                 node.arguments = parseArgumentList();
23431             }
23432             else if (node.typeArguments) {
23433                 parseErrorAt(fullStart, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
23434             }
23435             return finishNode(node);
23436         }
23437         // STATEMENTS
23438         function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
23439             var node = createNode(223 /* Block */);
23440             var openBracePosition = scanner.getTokenPos();
23441             if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
23442                 if (scanner.hasPrecedingLineBreak()) {
23443                     node.multiLine = true;
23444                 }
23445                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
23446                 if (!parseExpected(19 /* CloseBraceToken */)) {
23447                     var lastError = ts.lastOrUndefined(parseDiagnostics);
23448                     if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23449                         ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23450                     }
23451                 }
23452             }
23453             else {
23454                 node.statements = createMissingList();
23455             }
23456             return finishNode(node);
23457         }
23458         function parseFunctionBlock(flags, diagnosticMessage) {
23459             var savedYieldContext = inYieldContext();
23460             setYieldContext(!!(flags & 1 /* Yield */));
23461             var savedAwaitContext = inAwaitContext();
23462             setAwaitContext(!!(flags & 2 /* Await */));
23463             // We may be in a [Decorator] context when parsing a function expression or
23464             // arrow function. The body of the function is not in [Decorator] context.
23465             var saveDecoratorContext = inDecoratorContext();
23466             if (saveDecoratorContext) {
23467                 setDecoratorContext(/*val*/ false);
23468             }
23469             var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
23470             if (saveDecoratorContext) {
23471                 setDecoratorContext(/*val*/ true);
23472             }
23473             setYieldContext(savedYieldContext);
23474             setAwaitContext(savedAwaitContext);
23475             return block;
23476         }
23477         function parseEmptyStatement() {
23478             var node = createNode(224 /* EmptyStatement */);
23479             parseExpected(26 /* SemicolonToken */);
23480             return finishNode(node);
23481         }
23482         function parseIfStatement() {
23483             var node = createNode(227 /* IfStatement */);
23484             parseExpected(95 /* IfKeyword */);
23485             parseExpected(20 /* OpenParenToken */);
23486             node.expression = allowInAnd(parseExpression);
23487             parseExpected(21 /* CloseParenToken */);
23488             node.thenStatement = parseStatement();
23489             node.elseStatement = parseOptional(87 /* ElseKeyword */) ? parseStatement() : undefined;
23490             return finishNode(node);
23491         }
23492         function parseDoStatement() {
23493             var node = createNode(228 /* DoStatement */);
23494             parseExpected(86 /* DoKeyword */);
23495             node.statement = parseStatement();
23496             parseExpected(111 /* WhileKeyword */);
23497             parseExpected(20 /* OpenParenToken */);
23498             node.expression = allowInAnd(parseExpression);
23499             parseExpected(21 /* CloseParenToken */);
23500             // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
23501             // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
23502             // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
23503             //  do;while(0)x will have a semicolon inserted before x.
23504             parseOptional(26 /* SemicolonToken */);
23505             return finishNode(node);
23506         }
23507         function parseWhileStatement() {
23508             var node = createNode(229 /* WhileStatement */);
23509             parseExpected(111 /* WhileKeyword */);
23510             parseExpected(20 /* OpenParenToken */);
23511             node.expression = allowInAnd(parseExpression);
23512             parseExpected(21 /* CloseParenToken */);
23513             node.statement = parseStatement();
23514             return finishNode(node);
23515         }
23516         function parseForOrForInOrForOfStatement() {
23517             var pos = getNodePos();
23518             parseExpected(93 /* ForKeyword */);
23519             var awaitToken = parseOptionalToken(127 /* AwaitKeyword */);
23520             parseExpected(20 /* OpenParenToken */);
23521             var initializer;
23522             if (token() !== 26 /* SemicolonToken */) {
23523                 if (token() === 109 /* VarKeyword */ || token() === 115 /* LetKeyword */ || token() === 81 /* ConstKeyword */) {
23524                     initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
23525                 }
23526                 else {
23527                     initializer = disallowInAnd(parseExpression);
23528                 }
23529             }
23530             var forOrForInOrForOfStatement;
23531             if (awaitToken ? parseExpected(152 /* OfKeyword */) : parseOptional(152 /* OfKeyword */)) {
23532                 var forOfStatement = createNode(232 /* ForOfStatement */, pos);
23533                 forOfStatement.awaitModifier = awaitToken;
23534                 forOfStatement.initializer = initializer;
23535                 forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
23536                 parseExpected(21 /* CloseParenToken */);
23537                 forOrForInOrForOfStatement = forOfStatement;
23538             }
23539             else if (parseOptional(97 /* InKeyword */)) {
23540                 var forInStatement = createNode(231 /* ForInStatement */, pos);
23541                 forInStatement.initializer = initializer;
23542                 forInStatement.expression = allowInAnd(parseExpression);
23543                 parseExpected(21 /* CloseParenToken */);
23544                 forOrForInOrForOfStatement = forInStatement;
23545             }
23546             else {
23547                 var forStatement = createNode(230 /* ForStatement */, pos);
23548                 forStatement.initializer = initializer;
23549                 parseExpected(26 /* SemicolonToken */);
23550                 if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) {
23551                     forStatement.condition = allowInAnd(parseExpression);
23552                 }
23553                 parseExpected(26 /* SemicolonToken */);
23554                 if (token() !== 21 /* CloseParenToken */) {
23555                     forStatement.incrementor = allowInAnd(parseExpression);
23556                 }
23557                 parseExpected(21 /* CloseParenToken */);
23558                 forOrForInOrForOfStatement = forStatement;
23559             }
23560             forOrForInOrForOfStatement.statement = parseStatement();
23561             return finishNode(forOrForInOrForOfStatement);
23562         }
23563         function parseBreakOrContinueStatement(kind) {
23564             var node = createNode(kind);
23565             parseExpected(kind === 234 /* BreakStatement */ ? 77 /* BreakKeyword */ : 82 /* ContinueKeyword */);
23566             if (!canParseSemicolon()) {
23567                 node.label = parseIdentifier();
23568             }
23569             parseSemicolon();
23570             return finishNode(node);
23571         }
23572         function parseReturnStatement() {
23573             var node = createNode(235 /* ReturnStatement */);
23574             parseExpected(101 /* ReturnKeyword */);
23575             if (!canParseSemicolon()) {
23576                 node.expression = allowInAnd(parseExpression);
23577             }
23578             parseSemicolon();
23579             return finishNode(node);
23580         }
23581         function parseWithStatement() {
23582             var node = createNode(236 /* WithStatement */);
23583             parseExpected(112 /* WithKeyword */);
23584             parseExpected(20 /* OpenParenToken */);
23585             node.expression = allowInAnd(parseExpression);
23586             parseExpected(21 /* CloseParenToken */);
23587             node.statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
23588             return finishNode(node);
23589         }
23590         function parseCaseClause() {
23591             var node = createNode(277 /* CaseClause */);
23592             parseExpected(78 /* CaseKeyword */);
23593             node.expression = allowInAnd(parseExpression);
23594             parseExpected(58 /* ColonToken */);
23595             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23596             return finishNode(node);
23597         }
23598         function parseDefaultClause() {
23599             var node = createNode(278 /* DefaultClause */);
23600             parseExpected(84 /* DefaultKeyword */);
23601             parseExpected(58 /* ColonToken */);
23602             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23603             return finishNode(node);
23604         }
23605         function parseCaseOrDefaultClause() {
23606             return token() === 78 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
23607         }
23608         function parseSwitchStatement() {
23609             var node = createNode(237 /* SwitchStatement */);
23610             parseExpected(103 /* SwitchKeyword */);
23611             parseExpected(20 /* OpenParenToken */);
23612             node.expression = allowInAnd(parseExpression);
23613             parseExpected(21 /* CloseParenToken */);
23614             var caseBlock = createNode(251 /* CaseBlock */);
23615             parseExpected(18 /* OpenBraceToken */);
23616             caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
23617             parseExpected(19 /* CloseBraceToken */);
23618             node.caseBlock = finishNode(caseBlock);
23619             return finishNode(node);
23620         }
23621         function parseThrowStatement() {
23622             // ThrowStatement[Yield] :
23623             //      throw [no LineTerminator here]Expression[In, ?Yield];
23624             // Because of automatic semicolon insertion, we need to report error if this
23625             // throw could be terminated with a semicolon.  Note: we can't call 'parseExpression'
23626             // directly as that might consume an expression on the following line.
23627             // We just return 'undefined' in that case.  The actual error will be reported in the
23628             // grammar walker.
23629             var node = createNode(239 /* ThrowStatement */);
23630             parseExpected(105 /* ThrowKeyword */);
23631             node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
23632             parseSemicolon();
23633             return finishNode(node);
23634         }
23635         // TODO: Review for error recovery
23636         function parseTryStatement() {
23637             var node = createNode(240 /* TryStatement */);
23638             parseExpected(107 /* TryKeyword */);
23639             node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23640             node.catchClause = token() === 79 /* CatchKeyword */ ? parseCatchClause() : undefined;
23641             // If we don't have a catch clause, then we must have a finally clause.  Try to parse
23642             // one out no matter what.
23643             if (!node.catchClause || token() === 92 /* FinallyKeyword */) {
23644                 parseExpected(92 /* FinallyKeyword */);
23645                 node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23646             }
23647             return finishNode(node);
23648         }
23649         function parseCatchClause() {
23650             var result = createNode(280 /* CatchClause */);
23651             parseExpected(79 /* CatchKeyword */);
23652             if (parseOptional(20 /* OpenParenToken */)) {
23653                 result.variableDeclaration = parseVariableDeclaration();
23654                 parseExpected(21 /* CloseParenToken */);
23655             }
23656             else {
23657                 // Keep shape of node to avoid degrading performance.
23658                 result.variableDeclaration = undefined;
23659             }
23660             result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
23661             return finishNode(result);
23662         }
23663         function parseDebuggerStatement() {
23664             var node = createNode(241 /* DebuggerStatement */);
23665             parseExpected(83 /* DebuggerKeyword */);
23666             parseSemicolon();
23667             return finishNode(node);
23668         }
23669         function parseExpressionOrLabeledStatement() {
23670             // Avoiding having to do the lookahead for a labeled statement by just trying to parse
23671             // out an expression, seeing if it is identifier and then seeing if it is followed by
23672             // a colon.
23673             var node = createNodeWithJSDoc(token() === 75 /* Identifier */ ? 0 /* Unknown */ : 226 /* ExpressionStatement */);
23674             var expression = allowInAnd(parseExpression);
23675             if (expression.kind === 75 /* Identifier */ && parseOptional(58 /* ColonToken */)) {
23676                 node.kind = 238 /* LabeledStatement */;
23677                 node.label = expression;
23678                 node.statement = parseStatement();
23679             }
23680             else {
23681                 node.kind = 226 /* ExpressionStatement */;
23682                 node.expression = expression;
23683                 parseSemicolon();
23684             }
23685             return finishNode(node);
23686         }
23687         function nextTokenIsIdentifierOrKeywordOnSameLine() {
23688             nextToken();
23689             return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
23690         }
23691         function nextTokenIsClassKeywordOnSameLine() {
23692             nextToken();
23693             return token() === 80 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
23694         }
23695         function nextTokenIsFunctionKeywordOnSameLine() {
23696             nextToken();
23697             return token() === 94 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
23698         }
23699         function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
23700             nextToken();
23701             return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
23702         }
23703         function isDeclaration() {
23704             while (true) {
23705                 switch (token()) {
23706                     case 109 /* VarKeyword */:
23707                     case 115 /* LetKeyword */:
23708                     case 81 /* ConstKeyword */:
23709                     case 94 /* FunctionKeyword */:
23710                     case 80 /* ClassKeyword */:
23711                     case 88 /* EnumKeyword */:
23712                         return true;
23713                     // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
23714                     // however, an identifier cannot be followed by another identifier on the same line. This is what we
23715                     // count on to parse out the respective declarations. For instance, we exploit this to say that
23716                     //
23717                     //    namespace n
23718                     //
23719                     // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
23720                     //
23721                     //    namespace
23722                     //    n
23723                     //
23724                     // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
23725                     // We need to look one token ahead to see if it permissible to try parsing a declaration.
23726                     //
23727                     // *Note*: 'interface' is actually a strict mode reserved word. So while
23728                     //
23729                     //   "use strict"
23730                     //   interface
23731                     //   I {}
23732                     //
23733                     // could be legal, it would add complexity for very little gain.
23734                     case 114 /* InterfaceKeyword */:
23735                     case 145 /* TypeKeyword */:
23736                         return nextTokenIsIdentifierOnSameLine();
23737                     case 135 /* ModuleKeyword */:
23738                     case 136 /* NamespaceKeyword */:
23739                         return nextTokenIsIdentifierOrStringLiteralOnSameLine();
23740                     case 122 /* AbstractKeyword */:
23741                     case 126 /* AsyncKeyword */:
23742                     case 130 /* DeclareKeyword */:
23743                     case 117 /* PrivateKeyword */:
23744                     case 118 /* ProtectedKeyword */:
23745                     case 119 /* PublicKeyword */:
23746                     case 138 /* ReadonlyKeyword */:
23747                         nextToken();
23748                         // ASI takes effect for this modifier.
23749                         if (scanner.hasPrecedingLineBreak()) {
23750                             return false;
23751                         }
23752                         continue;
23753                     case 150 /* GlobalKeyword */:
23754                         nextToken();
23755                         return token() === 18 /* OpenBraceToken */ || token() === 75 /* Identifier */ || token() === 89 /* ExportKeyword */;
23756                     case 96 /* ImportKeyword */:
23757                         nextToken();
23758                         return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
23759                             token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
23760                     case 89 /* ExportKeyword */:
23761                         var currentToken_1 = nextToken();
23762                         if (currentToken_1 === 145 /* TypeKeyword */) {
23763                             currentToken_1 = lookAhead(nextToken);
23764                         }
23765                         if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
23766                             currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 84 /* DefaultKeyword */ ||
23767                             currentToken_1 === 123 /* AsKeyword */) {
23768                             return true;
23769                         }
23770                         continue;
23771                     case 120 /* StaticKeyword */:
23772                         nextToken();
23773                         continue;
23774                     default:
23775                         return false;
23776                 }
23777             }
23778         }
23779         function isStartOfDeclaration() {
23780             return lookAhead(isDeclaration);
23781         }
23782         function isStartOfStatement() {
23783             switch (token()) {
23784                 case 59 /* AtToken */:
23785                 case 26 /* SemicolonToken */:
23786                 case 18 /* OpenBraceToken */:
23787                 case 109 /* VarKeyword */:
23788                 case 115 /* LetKeyword */:
23789                 case 94 /* FunctionKeyword */:
23790                 case 80 /* ClassKeyword */:
23791                 case 88 /* EnumKeyword */:
23792                 case 95 /* IfKeyword */:
23793                 case 86 /* DoKeyword */:
23794                 case 111 /* WhileKeyword */:
23795                 case 93 /* ForKeyword */:
23796                 case 82 /* ContinueKeyword */:
23797                 case 77 /* BreakKeyword */:
23798                 case 101 /* ReturnKeyword */:
23799                 case 112 /* WithKeyword */:
23800                 case 103 /* SwitchKeyword */:
23801                 case 105 /* ThrowKeyword */:
23802                 case 107 /* TryKeyword */:
23803                 case 83 /* DebuggerKeyword */:
23804                 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
23805                 // however, we say they are here so that we may gracefully parse them and error later.
23806                 // falls through
23807                 case 79 /* CatchKeyword */:
23808                 case 92 /* FinallyKeyword */:
23809                     return true;
23810                 case 96 /* ImportKeyword */:
23811                     return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
23812                 case 81 /* ConstKeyword */:
23813                 case 89 /* ExportKeyword */:
23814                     return isStartOfDeclaration();
23815                 case 126 /* AsyncKeyword */:
23816                 case 130 /* DeclareKeyword */:
23817                 case 114 /* InterfaceKeyword */:
23818                 case 135 /* ModuleKeyword */:
23819                 case 136 /* NamespaceKeyword */:
23820                 case 145 /* TypeKeyword */:
23821                 case 150 /* GlobalKeyword */:
23822                     // When these don't start a declaration, they're an identifier in an expression statement
23823                     return true;
23824                 case 119 /* PublicKeyword */:
23825                 case 117 /* PrivateKeyword */:
23826                 case 118 /* ProtectedKeyword */:
23827                 case 120 /* StaticKeyword */:
23828                 case 138 /* ReadonlyKeyword */:
23829                     // When these don't start a declaration, they may be the start of a class member if an identifier
23830                     // immediately follows. Otherwise they're an identifier in an expression statement.
23831                     return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
23832                 default:
23833                     return isStartOfExpression();
23834             }
23835         }
23836         function nextTokenIsIdentifierOrStartOfDestructuring() {
23837             nextToken();
23838             return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
23839         }
23840         function isLetDeclaration() {
23841             // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
23842             // or [.
23843             return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
23844         }
23845         function parseStatement() {
23846             switch (token()) {
23847                 case 26 /* SemicolonToken */:
23848                     return parseEmptyStatement();
23849                 case 18 /* OpenBraceToken */:
23850                     return parseBlock(/*ignoreMissingOpenBrace*/ false);
23851                 case 109 /* VarKeyword */:
23852                     return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
23853                 case 115 /* LetKeyword */:
23854                     if (isLetDeclaration()) {
23855                         return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
23856                     }
23857                     break;
23858                 case 94 /* FunctionKeyword */:
23859                     return parseFunctionDeclaration(createNodeWithJSDoc(244 /* FunctionDeclaration */));
23860                 case 80 /* ClassKeyword */:
23861                     return parseClassDeclaration(createNodeWithJSDoc(245 /* ClassDeclaration */));
23862                 case 95 /* IfKeyword */:
23863                     return parseIfStatement();
23864                 case 86 /* DoKeyword */:
23865                     return parseDoStatement();
23866                 case 111 /* WhileKeyword */:
23867                     return parseWhileStatement();
23868                 case 93 /* ForKeyword */:
23869                     return parseForOrForInOrForOfStatement();
23870                 case 82 /* ContinueKeyword */:
23871                     return parseBreakOrContinueStatement(233 /* ContinueStatement */);
23872                 case 77 /* BreakKeyword */:
23873                     return parseBreakOrContinueStatement(234 /* BreakStatement */);
23874                 case 101 /* ReturnKeyword */:
23875                     return parseReturnStatement();
23876                 case 112 /* WithKeyword */:
23877                     return parseWithStatement();
23878                 case 103 /* SwitchKeyword */:
23879                     return parseSwitchStatement();
23880                 case 105 /* ThrowKeyword */:
23881                     return parseThrowStatement();
23882                 case 107 /* TryKeyword */:
23883                 // Include 'catch' and 'finally' for error recovery.
23884                 // falls through
23885                 case 79 /* CatchKeyword */:
23886                 case 92 /* FinallyKeyword */:
23887                     return parseTryStatement();
23888                 case 83 /* DebuggerKeyword */:
23889                     return parseDebuggerStatement();
23890                 case 59 /* AtToken */:
23891                     return parseDeclaration();
23892                 case 126 /* AsyncKeyword */:
23893                 case 114 /* InterfaceKeyword */:
23894                 case 145 /* TypeKeyword */:
23895                 case 135 /* ModuleKeyword */:
23896                 case 136 /* NamespaceKeyword */:
23897                 case 130 /* DeclareKeyword */:
23898                 case 81 /* ConstKeyword */:
23899                 case 88 /* EnumKeyword */:
23900                 case 89 /* ExportKeyword */:
23901                 case 96 /* ImportKeyword */:
23902                 case 117 /* PrivateKeyword */:
23903                 case 118 /* ProtectedKeyword */:
23904                 case 119 /* PublicKeyword */:
23905                 case 122 /* AbstractKeyword */:
23906                 case 120 /* StaticKeyword */:
23907                 case 138 /* ReadonlyKeyword */:
23908                 case 150 /* GlobalKeyword */:
23909                     if (isStartOfDeclaration()) {
23910                         return parseDeclaration();
23911                     }
23912                     break;
23913             }
23914             return parseExpressionOrLabeledStatement();
23915         }
23916         function isDeclareModifier(modifier) {
23917             return modifier.kind === 130 /* DeclareKeyword */;
23918         }
23919         function parseDeclaration() {
23920             var modifiers = lookAhead(function () { return (parseDecorators(), parseModifiers()); });
23921             // `parseListElement` attempted to get the reused node at this position,
23922             // but the ambient context flag was not yet set, so the node appeared
23923             // not reusable in that context.
23924             var isAmbient = ts.some(modifiers, isDeclareModifier);
23925             if (isAmbient) {
23926                 var node_3 = tryReuseAmbientDeclaration();
23927                 if (node_3) {
23928                     return node_3;
23929                 }
23930             }
23931             var node = createNodeWithJSDoc(0 /* Unknown */);
23932             node.decorators = parseDecorators();
23933             node.modifiers = parseModifiers();
23934             if (isAmbient) {
23935                 for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
23936                     var m = _a[_i];
23937                     m.flags |= 8388608 /* Ambient */;
23938                 }
23939                 return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(node); });
23940             }
23941             else {
23942                 return parseDeclarationWorker(node);
23943             }
23944         }
23945         function tryReuseAmbientDeclaration() {
23946             return doInsideOfContext(8388608 /* Ambient */, function () {
23947                 var node = currentNode(parsingContext);
23948                 if (node) {
23949                     return consumeNode(node);
23950                 }
23951             });
23952         }
23953         function parseDeclarationWorker(node) {
23954             switch (token()) {
23955                 case 109 /* VarKeyword */:
23956                 case 115 /* LetKeyword */:
23957                 case 81 /* ConstKeyword */:
23958                     return parseVariableStatement(node);
23959                 case 94 /* FunctionKeyword */:
23960                     return parseFunctionDeclaration(node);
23961                 case 80 /* ClassKeyword */:
23962                     return parseClassDeclaration(node);
23963                 case 114 /* InterfaceKeyword */:
23964                     return parseInterfaceDeclaration(node);
23965                 case 145 /* TypeKeyword */:
23966                     return parseTypeAliasDeclaration(node);
23967                 case 88 /* EnumKeyword */:
23968                     return parseEnumDeclaration(node);
23969                 case 150 /* GlobalKeyword */:
23970                 case 135 /* ModuleKeyword */:
23971                 case 136 /* NamespaceKeyword */:
23972                     return parseModuleDeclaration(node);
23973                 case 96 /* ImportKeyword */:
23974                     return parseImportDeclarationOrImportEqualsDeclaration(node);
23975                 case 89 /* ExportKeyword */:
23976                     nextToken();
23977                     switch (token()) {
23978                         case 84 /* DefaultKeyword */:
23979                         case 62 /* EqualsToken */:
23980                             return parseExportAssignment(node);
23981                         case 123 /* AsKeyword */:
23982                             return parseNamespaceExportDeclaration(node);
23983                         default:
23984                             return parseExportDeclaration(node);
23985                     }
23986                 default:
23987                     if (node.decorators || node.modifiers) {
23988                         // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
23989                         // would follow. For recovery and error reporting purposes, return an incomplete declaration.
23990                         var missing = createMissingNode(264 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
23991                         missing.pos = node.pos;
23992                         missing.decorators = node.decorators;
23993                         missing.modifiers = node.modifiers;
23994                         return finishNode(missing);
23995                     }
23996                     return undefined; // TODO: GH#18217
23997             }
23998         }
23999         function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
24000             nextToken();
24001             return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
24002         }
24003         function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
24004             if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
24005                 parseSemicolon();
24006                 return;
24007             }
24008             return parseFunctionBlock(flags, diagnosticMessage);
24009         }
24010         // DECLARATIONS
24011         function parseArrayBindingElement() {
24012             if (token() === 27 /* CommaToken */) {
24013                 return createNode(215 /* OmittedExpression */);
24014             }
24015             var node = createNode(191 /* BindingElement */);
24016             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24017             node.name = parseIdentifierOrPattern();
24018             node.initializer = parseInitializer();
24019             return finishNode(node);
24020         }
24021         function parseObjectBindingElement() {
24022             var node = createNode(191 /* BindingElement */);
24023             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24024             var tokenIsIdentifier = isIdentifier();
24025             var propertyName = parsePropertyName();
24026             if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
24027                 node.name = propertyName;
24028             }
24029             else {
24030                 parseExpected(58 /* ColonToken */);
24031                 node.propertyName = propertyName;
24032                 node.name = parseIdentifierOrPattern();
24033             }
24034             node.initializer = parseInitializer();
24035             return finishNode(node);
24036         }
24037         function parseObjectBindingPattern() {
24038             var node = createNode(189 /* ObjectBindingPattern */);
24039             parseExpected(18 /* OpenBraceToken */);
24040             node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
24041             parseExpected(19 /* CloseBraceToken */);
24042             return finishNode(node);
24043         }
24044         function parseArrayBindingPattern() {
24045             var node = createNode(190 /* ArrayBindingPattern */);
24046             parseExpected(22 /* OpenBracketToken */);
24047             node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
24048             parseExpected(23 /* CloseBracketToken */);
24049             return finishNode(node);
24050         }
24051         function isIdentifierOrPrivateIdentifierOrPattern() {
24052             return token() === 18 /* OpenBraceToken */
24053                 || token() === 22 /* OpenBracketToken */
24054                 || token() === 76 /* PrivateIdentifier */
24055                 || isIdentifier();
24056         }
24057         function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
24058             if (token() === 22 /* OpenBracketToken */) {
24059                 return parseArrayBindingPattern();
24060             }
24061             if (token() === 18 /* OpenBraceToken */) {
24062                 return parseObjectBindingPattern();
24063             }
24064             return parseIdentifier(/*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
24065         }
24066         function parseVariableDeclarationAllowExclamation() {
24067             return parseVariableDeclaration(/*allowExclamation*/ true);
24068         }
24069         function parseVariableDeclaration(allowExclamation) {
24070             var node = createNode(242 /* VariableDeclaration */);
24071             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
24072             if (allowExclamation && node.name.kind === 75 /* Identifier */ &&
24073                 token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24074                 node.exclamationToken = parseTokenNode();
24075             }
24076             node.type = parseTypeAnnotation();
24077             if (!isInOrOfKeyword(token())) {
24078                 node.initializer = parseInitializer();
24079             }
24080             return finishNode(node);
24081         }
24082         function parseVariableDeclarationList(inForStatementInitializer) {
24083             var node = createNode(243 /* VariableDeclarationList */);
24084             switch (token()) {
24085                 case 109 /* VarKeyword */:
24086                     break;
24087                 case 115 /* LetKeyword */:
24088                     node.flags |= 1 /* Let */;
24089                     break;
24090                 case 81 /* ConstKeyword */:
24091                     node.flags |= 2 /* Const */;
24092                     break;
24093                 default:
24094                     ts.Debug.fail();
24095             }
24096             nextToken();
24097             // The user may have written the following:
24098             //
24099             //    for (let of X) { }
24100             //
24101             // In this case, we want to parse an empty declaration list, and then parse 'of'
24102             // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
24103             // So we need to look ahead to determine if 'of' should be treated as a keyword in
24104             // this context.
24105             // The checker will then give an error that there is an empty declaration list.
24106             if (token() === 152 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
24107                 node.declarations = createMissingList();
24108             }
24109             else {
24110                 var savedDisallowIn = inDisallowInContext();
24111                 setDisallowInContext(inForStatementInitializer);
24112                 node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
24113                 setDisallowInContext(savedDisallowIn);
24114             }
24115             return finishNode(node);
24116         }
24117         function canFollowContextualOfKeyword() {
24118             return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
24119         }
24120         function parseVariableStatement(node) {
24121             node.kind = 225 /* VariableStatement */;
24122             node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
24123             parseSemicolon();
24124             return finishNode(node);
24125         }
24126         function parseFunctionDeclaration(node) {
24127             node.kind = 244 /* FunctionDeclaration */;
24128             parseExpected(94 /* FunctionKeyword */);
24129             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24130             node.name = hasModifierOfKind(node, 84 /* DefaultKeyword */) ? parseOptionalIdentifier() : parseIdentifier();
24131             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
24132             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24133             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24134             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
24135             return finishNode(node);
24136         }
24137         function parseConstructorName() {
24138             if (token() === 129 /* ConstructorKeyword */) {
24139                 return parseExpected(129 /* ConstructorKeyword */);
24140             }
24141             if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
24142                 return tryParse(function () {
24143                     var literalNode = parseLiteralNode();
24144                     return literalNode.text === "constructor" ? literalNode : undefined;
24145                 });
24146             }
24147         }
24148         function tryParseConstructorDeclaration(node) {
24149             return tryParse(function () {
24150                 if (parseConstructorName()) {
24151                     node.kind = 162 /* Constructor */;
24152                     fillSignature(58 /* ColonToken */, 0 /* None */, node);
24153                     node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
24154                     return finishNode(node);
24155                 }
24156             });
24157         }
24158         function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
24159             node.kind = 161 /* MethodDeclaration */;
24160             node.asteriskToken = asteriskToken;
24161             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
24162             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24163             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24164             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
24165             return finishNode(node);
24166         }
24167         function parsePropertyDeclaration(node) {
24168             node.kind = 159 /* PropertyDeclaration */;
24169             if (!node.questionToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24170                 node.exclamationToken = parseTokenNode();
24171             }
24172             node.type = parseTypeAnnotation();
24173             node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
24174             parseSemicolon();
24175             return finishNode(node);
24176         }
24177         function parsePropertyOrMethodDeclaration(node) {
24178             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24179             node.name = parsePropertyName();
24180             // Note: this is not legal as per the grammar.  But we allow it in the parser and
24181             // report an error in the grammar checker.
24182             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
24183             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
24184                 return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
24185             }
24186             return parsePropertyDeclaration(node);
24187         }
24188         function parseAccessorDeclaration(node, kind) {
24189             node.kind = kind;
24190             node.name = parsePropertyName();
24191             fillSignature(58 /* ColonToken */, 0 /* None */, node);
24192             node.body = parseFunctionBlockOrSemicolon(0 /* None */);
24193             return finishNode(node);
24194         }
24195         function isClassMemberStart() {
24196             var idToken;
24197             if (token() === 59 /* AtToken */) {
24198                 return true;
24199             }
24200             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
24201             while (ts.isModifierKind(token())) {
24202                 idToken = token();
24203                 // If the idToken is a class modifier (protected, private, public, and static), it is
24204                 // certain that we are starting to parse class member. This allows better error recovery
24205                 // Example:
24206                 //      public foo() ...     // true
24207                 //      public @dec blah ... // true; we will then report an error later
24208                 //      export public ...    // true; we will then report an error later
24209                 if (ts.isClassMemberModifier(idToken)) {
24210                     return true;
24211                 }
24212                 nextToken();
24213             }
24214             if (token() === 41 /* AsteriskToken */) {
24215                 return true;
24216             }
24217             // Try to get the first property-like token following all modifiers.
24218             // This can either be an identifier or the 'get' or 'set' keywords.
24219             if (isLiteralPropertyName()) {
24220                 idToken = token();
24221                 nextToken();
24222             }
24223             // Index signatures and computed properties are class members; we can parse.
24224             if (token() === 22 /* OpenBracketToken */) {
24225                 return true;
24226             }
24227             // If we were able to get any potential identifier...
24228             if (idToken !== undefined) {
24229                 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
24230                 if (!ts.isKeyword(idToken) || idToken === 142 /* SetKeyword */ || idToken === 131 /* GetKeyword */) {
24231                     return true;
24232                 }
24233                 // If it *is* a keyword, but not an accessor, check a little farther along
24234                 // to see if it should actually be parsed as a class member.
24235                 switch (token()) {
24236                     case 20 /* OpenParenToken */: // Method declaration
24237                     case 29 /* LessThanToken */: // Generic Method declaration
24238                     case 53 /* ExclamationToken */: // Non-null assertion on property name
24239                     case 58 /* ColonToken */: // Type Annotation for declaration
24240                     case 62 /* EqualsToken */: // Initializer for declaration
24241                     case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
24242                         return true;
24243                     default:
24244                         // Covers
24245                         //  - Semicolons     (declaration termination)
24246                         //  - Closing braces (end-of-class, must be declaration)
24247                         //  - End-of-files   (not valid, but permitted so that it gets caught later on)
24248                         //  - Line-breaks    (enabling *automatic semicolon insertion*)
24249                         return canParseSemicolon();
24250                 }
24251             }
24252             return false;
24253         }
24254         function parseDecorators() {
24255             var list;
24256             var listPos = getNodePos();
24257             while (true) {
24258                 var decoratorStart = getNodePos();
24259                 if (!parseOptional(59 /* AtToken */)) {
24260                     break;
24261                 }
24262                 var decorator = createNode(157 /* Decorator */, decoratorStart);
24263                 decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
24264                 finishNode(decorator);
24265                 (list || (list = [])).push(decorator);
24266             }
24267             return list && createNodeArray(list, listPos);
24268         }
24269         /*
24270          * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
24271          * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
24272          * and turns it into a standalone declaration), then it is better to parse it and report an error later.
24273          *
24274          * In such situations, 'permitInvalidConstAsModifier' should be set to true.
24275          */
24276         function parseModifiers(permitInvalidConstAsModifier) {
24277             var list;
24278             var listPos = getNodePos();
24279             while (true) {
24280                 var modifierStart = scanner.getStartPos();
24281                 var modifierKind = token();
24282                 if (token() === 81 /* ConstKeyword */ && permitInvalidConstAsModifier) {
24283                     // We need to ensure that any subsequent modifiers appear on the same line
24284                     // so that when 'const' is a standalone declaration, we don't issue an error.
24285                     if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
24286                         break;
24287                     }
24288                 }
24289                 else {
24290                     if (!parseAnyContextualModifier()) {
24291                         break;
24292                     }
24293                 }
24294                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24295                 (list || (list = [])).push(modifier);
24296             }
24297             return list && createNodeArray(list, listPos);
24298         }
24299         function parseModifiersForArrowFunction() {
24300             var modifiers;
24301             if (token() === 126 /* AsyncKeyword */) {
24302                 var modifierStart = scanner.getStartPos();
24303                 var modifierKind = token();
24304                 nextToken();
24305                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24306                 modifiers = createNodeArray([modifier], modifierStart);
24307             }
24308             return modifiers;
24309         }
24310         function parseClassElement() {
24311             if (token() === 26 /* SemicolonToken */) {
24312                 var result = createNode(222 /* SemicolonClassElement */);
24313                 nextToken();
24314                 return finishNode(result);
24315             }
24316             var node = createNodeWithJSDoc(0 /* Unknown */);
24317             node.decorators = parseDecorators();
24318             node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
24319             if (parseContextualModifier(131 /* GetKeyword */)) {
24320                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
24321             }
24322             if (parseContextualModifier(142 /* SetKeyword */)) {
24323                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
24324             }
24325             if (token() === 129 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
24326                 var constructorDeclaration = tryParseConstructorDeclaration(node);
24327                 if (constructorDeclaration) {
24328                     return constructorDeclaration;
24329                 }
24330             }
24331             if (isIndexSignature()) {
24332                 return parseIndexSignatureDeclaration(node);
24333             }
24334             // It is very important that we check this *after* checking indexers because
24335             // the [ token can start an index signature or a computed property name
24336             if (ts.tokenIsIdentifierOrKeyword(token()) ||
24337                 token() === 10 /* StringLiteral */ ||
24338                 token() === 8 /* NumericLiteral */ ||
24339                 token() === 41 /* AsteriskToken */ ||
24340                 token() === 22 /* OpenBracketToken */) {
24341                 var isAmbient = node.modifiers && ts.some(node.modifiers, isDeclareModifier);
24342                 if (isAmbient) {
24343                     for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
24344                         var m = _a[_i];
24345                         m.flags |= 8388608 /* Ambient */;
24346                     }
24347                     return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(node); });
24348                 }
24349                 else {
24350                     return parsePropertyOrMethodDeclaration(node);
24351                 }
24352             }
24353             if (node.decorators || node.modifiers) {
24354                 // treat this as a property declaration with a missing name.
24355                 node.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
24356                 return parsePropertyDeclaration(node);
24357             }
24358             // 'isClassMemberStart' should have hinted not to attempt parsing.
24359             return ts.Debug.fail("Should not have attempted to parse class member declaration.");
24360         }
24361         function parseClassExpression() {
24362             return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 214 /* ClassExpression */);
24363         }
24364         function parseClassDeclaration(node) {
24365             return parseClassDeclarationOrExpression(node, 245 /* ClassDeclaration */);
24366         }
24367         function parseClassDeclarationOrExpression(node, kind) {
24368             node.kind = kind;
24369             parseExpected(80 /* ClassKeyword */);
24370             node.name = parseNameOfClassDeclarationOrExpression();
24371             node.typeParameters = parseTypeParameters();
24372             node.heritageClauses = parseHeritageClauses();
24373             if (parseExpected(18 /* OpenBraceToken */)) {
24374                 // ClassTail[Yield,Await] : (Modified) See 14.5
24375                 //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24376                 node.members = parseClassMembers();
24377                 parseExpected(19 /* CloseBraceToken */);
24378             }
24379             else {
24380                 node.members = createMissingList();
24381             }
24382             return finishNode(node);
24383         }
24384         function parseNameOfClassDeclarationOrExpression() {
24385             // implements is a future reserved word so
24386             // 'class implements' might mean either
24387             // - class expression with omitted name, 'implements' starts heritage clause
24388             // - class with name 'implements'
24389             // 'isImplementsClause' helps to disambiguate between these two cases
24390             return isIdentifier() && !isImplementsClause()
24391                 ? parseIdentifier()
24392                 : undefined;
24393         }
24394         function isImplementsClause() {
24395             return token() === 113 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
24396         }
24397         function parseHeritageClauses() {
24398             // ClassTail[Yield,Await] : (Modified) See 14.5
24399             //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24400             if (isHeritageClause()) {
24401                 return parseList(22 /* HeritageClauses */, parseHeritageClause);
24402             }
24403             return undefined;
24404         }
24405         function parseHeritageClause() {
24406             var tok = token();
24407             ts.Debug.assert(tok === 90 /* ExtendsKeyword */ || tok === 113 /* ImplementsKeyword */); // isListElement() should ensure this.
24408             var node = createNode(279 /* HeritageClause */);
24409             node.token = tok;
24410             nextToken();
24411             node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
24412             return finishNode(node);
24413         }
24414         function parseExpressionWithTypeArguments() {
24415             var node = createNode(216 /* ExpressionWithTypeArguments */);
24416             node.expression = parseLeftHandSideExpressionOrHigher();
24417             node.typeArguments = tryParseTypeArguments();
24418             return finishNode(node);
24419         }
24420         function tryParseTypeArguments() {
24421             return token() === 29 /* LessThanToken */ ?
24422                 parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
24423         }
24424         function isHeritageClause() {
24425             return token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
24426         }
24427         function parseClassMembers() {
24428             return parseList(5 /* ClassMembers */, parseClassElement);
24429         }
24430         function parseInterfaceDeclaration(node) {
24431             node.kind = 246 /* InterfaceDeclaration */;
24432             parseExpected(114 /* InterfaceKeyword */);
24433             node.name = parseIdentifier();
24434             node.typeParameters = parseTypeParameters();
24435             node.heritageClauses = parseHeritageClauses();
24436             node.members = parseObjectTypeMembers();
24437             return finishNode(node);
24438         }
24439         function parseTypeAliasDeclaration(node) {
24440             node.kind = 247 /* TypeAliasDeclaration */;
24441             parseExpected(145 /* TypeKeyword */);
24442             node.name = parseIdentifier();
24443             node.typeParameters = parseTypeParameters();
24444             parseExpected(62 /* EqualsToken */);
24445             node.type = parseType();
24446             parseSemicolon();
24447             return finishNode(node);
24448         }
24449         // In an ambient declaration, the grammar only allows integer literals as initializers.
24450         // In a non-ambient declaration, the grammar allows uninitialized members only in a
24451         // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
24452         // or any time an integer literal initializer is encountered.
24453         function parseEnumMember() {
24454             var node = createNodeWithJSDoc(284 /* EnumMember */);
24455             node.name = parsePropertyName();
24456             node.initializer = allowInAnd(parseInitializer);
24457             return finishNode(node);
24458         }
24459         function parseEnumDeclaration(node) {
24460             node.kind = 248 /* EnumDeclaration */;
24461             parseExpected(88 /* EnumKeyword */);
24462             node.name = parseIdentifier();
24463             if (parseExpected(18 /* OpenBraceToken */)) {
24464                 node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
24465                 parseExpected(19 /* CloseBraceToken */);
24466             }
24467             else {
24468                 node.members = createMissingList();
24469             }
24470             return finishNode(node);
24471         }
24472         function parseModuleBlock() {
24473             var node = createNode(250 /* ModuleBlock */);
24474             if (parseExpected(18 /* OpenBraceToken */)) {
24475                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
24476                 parseExpected(19 /* CloseBraceToken */);
24477             }
24478             else {
24479                 node.statements = createMissingList();
24480             }
24481             return finishNode(node);
24482         }
24483         function parseModuleOrNamespaceDeclaration(node, flags) {
24484             node.kind = 249 /* ModuleDeclaration */;
24485             // If we are parsing a dotted namespace name, we want to
24486             // propagate the 'Namespace' flag across the names if set.
24487             var namespaceFlag = flags & 16 /* Namespace */;
24488             node.flags |= flags;
24489             node.name = parseIdentifier();
24490             node.body = parseOptional(24 /* DotToken */)
24491                 ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
24492                 : parseModuleBlock();
24493             return finishNode(node);
24494         }
24495         function parseAmbientExternalModuleDeclaration(node) {
24496             node.kind = 249 /* ModuleDeclaration */;
24497             if (token() === 150 /* GlobalKeyword */) {
24498                 // parse 'global' as name of global scope augmentation
24499                 node.name = parseIdentifier();
24500                 node.flags |= 1024 /* GlobalAugmentation */;
24501             }
24502             else {
24503                 node.name = parseLiteralNode();
24504                 node.name.text = internIdentifier(node.name.text);
24505             }
24506             if (token() === 18 /* OpenBraceToken */) {
24507                 node.body = parseModuleBlock();
24508             }
24509             else {
24510                 parseSemicolon();
24511             }
24512             return finishNode(node);
24513         }
24514         function parseModuleDeclaration(node) {
24515             var flags = 0;
24516             if (token() === 150 /* GlobalKeyword */) {
24517                 // global augmentation
24518                 return parseAmbientExternalModuleDeclaration(node);
24519             }
24520             else if (parseOptional(136 /* NamespaceKeyword */)) {
24521                 flags |= 16 /* Namespace */;
24522             }
24523             else {
24524                 parseExpected(135 /* ModuleKeyword */);
24525                 if (token() === 10 /* StringLiteral */) {
24526                     return parseAmbientExternalModuleDeclaration(node);
24527                 }
24528             }
24529             return parseModuleOrNamespaceDeclaration(node, flags);
24530         }
24531         function isExternalModuleReference() {
24532             return token() === 139 /* RequireKeyword */ &&
24533                 lookAhead(nextTokenIsOpenParen);
24534         }
24535         function nextTokenIsOpenParen() {
24536             return nextToken() === 20 /* OpenParenToken */;
24537         }
24538         function nextTokenIsSlash() {
24539             return nextToken() === 43 /* SlashToken */;
24540         }
24541         function parseNamespaceExportDeclaration(node) {
24542             node.kind = 252 /* NamespaceExportDeclaration */;
24543             parseExpected(123 /* AsKeyword */);
24544             parseExpected(136 /* NamespaceKeyword */);
24545             node.name = parseIdentifier();
24546             parseSemicolon();
24547             return finishNode(node);
24548         }
24549         function parseImportDeclarationOrImportEqualsDeclaration(node) {
24550             parseExpected(96 /* ImportKeyword */);
24551             var afterImportPos = scanner.getStartPos();
24552             var identifier;
24553             if (isIdentifier()) {
24554                 identifier = parseIdentifier();
24555             }
24556             var isTypeOnly = false;
24557             if (token() !== 149 /* FromKeyword */ &&
24558                 (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
24559                 (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
24560                 isTypeOnly = true;
24561                 identifier = isIdentifier() ? parseIdentifier() : undefined;
24562             }
24563             if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
24564                 return parseImportEqualsDeclaration(node, identifier, isTypeOnly);
24565             }
24566             // Import statement
24567             node.kind = 254 /* ImportDeclaration */;
24568             // ImportDeclaration:
24569             //  import ImportClause from ModuleSpecifier ;
24570             //  import ModuleSpecifier;
24571             if (identifier || // import id
24572                 token() === 41 /* AsteriskToken */ || // import *
24573                 token() === 18 /* OpenBraceToken */ // import {
24574             ) {
24575                 node.importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
24576                 parseExpected(149 /* FromKeyword */);
24577             }
24578             node.moduleSpecifier = parseModuleSpecifier();
24579             parseSemicolon();
24580             return finishNode(node);
24581         }
24582         function tokenAfterImportDefinitelyProducesImportDeclaration() {
24583             return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
24584         }
24585         function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
24586             // In `import id ___`, the current token decides whether to produce
24587             // an ImportDeclaration or ImportEqualsDeclaration.
24588             return token() === 27 /* CommaToken */ || token() === 149 /* FromKeyword */;
24589         }
24590         function parseImportEqualsDeclaration(node, identifier, isTypeOnly) {
24591             node.kind = 253 /* ImportEqualsDeclaration */;
24592             node.name = identifier;
24593             parseExpected(62 /* EqualsToken */);
24594             node.moduleReference = parseModuleReference();
24595             parseSemicolon();
24596             var finished = finishNode(node);
24597             if (isTypeOnly) {
24598                 parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
24599             }
24600             return finished;
24601         }
24602         function parseImportClause(identifier, fullStart, isTypeOnly) {
24603             // ImportClause:
24604             //  ImportedDefaultBinding
24605             //  NameSpaceImport
24606             //  NamedImports
24607             //  ImportedDefaultBinding, NameSpaceImport
24608             //  ImportedDefaultBinding, NamedImports
24609             var importClause = createNode(255 /* ImportClause */, fullStart);
24610             importClause.isTypeOnly = isTypeOnly;
24611             if (identifier) {
24612                 // ImportedDefaultBinding:
24613                 //  ImportedBinding
24614                 importClause.name = identifier;
24615             }
24616             // If there was no default import or if there is comma token after default import
24617             // parse namespace or named imports
24618             if (!importClause.name ||
24619                 parseOptional(27 /* CommaToken */)) {
24620                 importClause.namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(257 /* NamedImports */);
24621             }
24622             return finishNode(importClause);
24623         }
24624         function parseModuleReference() {
24625             return isExternalModuleReference()
24626                 ? parseExternalModuleReference()
24627                 : parseEntityName(/*allowReservedWords*/ false);
24628         }
24629         function parseExternalModuleReference() {
24630             var node = createNode(265 /* ExternalModuleReference */);
24631             parseExpected(139 /* RequireKeyword */);
24632             parseExpected(20 /* OpenParenToken */);
24633             node.expression = parseModuleSpecifier();
24634             parseExpected(21 /* CloseParenToken */);
24635             return finishNode(node);
24636         }
24637         function parseModuleSpecifier() {
24638             if (token() === 10 /* StringLiteral */) {
24639                 var result = parseLiteralNode();
24640                 result.text = internIdentifier(result.text);
24641                 return result;
24642             }
24643             else {
24644                 // We allow arbitrary expressions here, even though the grammar only allows string
24645                 // literals.  We check to ensure that it is only a string literal later in the grammar
24646                 // check pass.
24647                 return parseExpression();
24648             }
24649         }
24650         function parseNamespaceImport() {
24651             // NameSpaceImport:
24652             //  * as ImportedBinding
24653             var namespaceImport = createNode(256 /* NamespaceImport */);
24654             parseExpected(41 /* AsteriskToken */);
24655             parseExpected(123 /* AsKeyword */);
24656             namespaceImport.name = parseIdentifier();
24657             return finishNode(namespaceImport);
24658         }
24659         function parseNamedImportsOrExports(kind) {
24660             var node = createNode(kind);
24661             // NamedImports:
24662             //  { }
24663             //  { ImportsList }
24664             //  { ImportsList, }
24665             // ImportsList:
24666             //  ImportSpecifier
24667             //  ImportsList, ImportSpecifier
24668             node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 257 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */);
24669             return finishNode(node);
24670         }
24671         function parseExportSpecifier() {
24672             return parseImportOrExportSpecifier(263 /* ExportSpecifier */);
24673         }
24674         function parseImportSpecifier() {
24675             return parseImportOrExportSpecifier(258 /* ImportSpecifier */);
24676         }
24677         function parseImportOrExportSpecifier(kind) {
24678             var node = createNode(kind);
24679             // ImportSpecifier:
24680             //   BindingIdentifier
24681             //   IdentifierName as BindingIdentifier
24682             // ExportSpecifier:
24683             //   IdentifierName
24684             //   IdentifierName as IdentifierName
24685             var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24686             var checkIdentifierStart = scanner.getTokenPos();
24687             var checkIdentifierEnd = scanner.getTextPos();
24688             var identifierName = parseIdentifierName();
24689             if (token() === 123 /* AsKeyword */) {
24690                 node.propertyName = identifierName;
24691                 parseExpected(123 /* AsKeyword */);
24692                 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24693                 checkIdentifierStart = scanner.getTokenPos();
24694                 checkIdentifierEnd = scanner.getTextPos();
24695                 node.name = parseIdentifierName();
24696             }
24697             else {
24698                 node.name = identifierName;
24699             }
24700             if (kind === 258 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
24701                 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
24702             }
24703             return finishNode(node);
24704         }
24705         function parseNamespaceExport(pos) {
24706             var node = createNode(262 /* NamespaceExport */, pos);
24707             node.name = parseIdentifier();
24708             return finishNode(node);
24709         }
24710         function parseExportDeclaration(node) {
24711             node.kind = 260 /* ExportDeclaration */;
24712             node.isTypeOnly = parseOptional(145 /* TypeKeyword */);
24713             var namespaceExportPos = scanner.getStartPos();
24714             if (parseOptional(41 /* AsteriskToken */)) {
24715                 if (parseOptional(123 /* AsKeyword */)) {
24716                     node.exportClause = parseNamespaceExport(namespaceExportPos);
24717                 }
24718                 parseExpected(149 /* FromKeyword */);
24719                 node.moduleSpecifier = parseModuleSpecifier();
24720             }
24721             else {
24722                 node.exportClause = parseNamedImportsOrExports(261 /* NamedExports */);
24723                 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
24724                 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
24725                 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
24726                 if (token() === 149 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
24727                     parseExpected(149 /* FromKeyword */);
24728                     node.moduleSpecifier = parseModuleSpecifier();
24729                 }
24730             }
24731             parseSemicolon();
24732             return finishNode(node);
24733         }
24734         function parseExportAssignment(node) {
24735             node.kind = 259 /* ExportAssignment */;
24736             if (parseOptional(62 /* EqualsToken */)) {
24737                 node.isExportEquals = true;
24738             }
24739             else {
24740                 parseExpected(84 /* DefaultKeyword */);
24741             }
24742             node.expression = parseAssignmentExpressionOrHigher();
24743             parseSemicolon();
24744             return finishNode(node);
24745         }
24746         function setExternalModuleIndicator(sourceFile) {
24747             // Try to use the first top-level import/export when available, then
24748             // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
24749             sourceFile.externalModuleIndicator =
24750                 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
24751                     getImportMetaIfNecessary(sourceFile);
24752         }
24753         function isAnExternalModuleIndicatorNode(node) {
24754             return hasModifierOfKind(node, 89 /* ExportKeyword */)
24755                 || node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */
24756                 || node.kind === 254 /* ImportDeclaration */
24757                 || node.kind === 259 /* ExportAssignment */
24758                 || node.kind === 260 /* ExportDeclaration */ ? node : undefined;
24759         }
24760         function getImportMetaIfNecessary(sourceFile) {
24761             return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
24762                 walkTreeForExternalModuleIndicators(sourceFile) :
24763                 undefined;
24764         }
24765         function walkTreeForExternalModuleIndicators(node) {
24766             return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
24767         }
24768         /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
24769         function hasModifierOfKind(node, kind) {
24770             return ts.some(node.modifiers, function (m) { return m.kind === kind; });
24771         }
24772         function isImportMeta(node) {
24773             return ts.isMetaProperty(node) && node.keywordToken === 96 /* ImportKeyword */ && node.name.escapedText === "meta";
24774         }
24775         var ParsingContext;
24776         (function (ParsingContext) {
24777             ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
24778             ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
24779             ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
24780             ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
24781             ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
24782             ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
24783             ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
24784             ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
24785             ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
24786             ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
24787             ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
24788             ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
24789             ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
24790             ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
24791             ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
24792             ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
24793             ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
24794             ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
24795             ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
24796             ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
24797             ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
24798             ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
24799             ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
24800             ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
24801             ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
24802         })(ParsingContext || (ParsingContext = {}));
24803         var Tristate;
24804         (function (Tristate) {
24805             Tristate[Tristate["False"] = 0] = "False";
24806             Tristate[Tristate["True"] = 1] = "True";
24807             Tristate[Tristate["Unknown"] = 2] = "Unknown";
24808         })(Tristate || (Tristate = {}));
24809         var JSDocParser;
24810         (function (JSDocParser) {
24811             function parseJSDocTypeExpressionForTests(content, start, length) {
24812                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24813                 sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
24814                 scanner.setText(content, start, length);
24815                 currentToken = scanner.scan();
24816                 var jsDocTypeExpression = parseJSDocTypeExpression();
24817                 var diagnostics = parseDiagnostics;
24818                 clearState();
24819                 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
24820             }
24821             JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
24822             // Parses out a JSDoc type expression.
24823             function parseJSDocTypeExpression(mayOmitBraces) {
24824                 var result = createNode(294 /* JSDocTypeExpression */);
24825                 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
24826                 result.type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
24827                 if (!mayOmitBraces || hasBrace) {
24828                     parseExpectedJSDoc(19 /* CloseBraceToken */);
24829                 }
24830                 fixupParentReferences(result);
24831                 return finishNode(result);
24832             }
24833             JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
24834             function parseIsolatedJSDocComment(content, start, length) {
24835                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24836                 sourceFile = { languageVariant: 0 /* Standard */, text: content };
24837                 var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
24838                 var diagnostics = parseDiagnostics;
24839                 clearState();
24840                 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
24841             }
24842             JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
24843             function parseJSDocComment(parent, start, length) {
24844                 var _a;
24845                 var saveToken = currentToken;
24846                 var saveParseDiagnosticsLength = parseDiagnostics.length;
24847                 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
24848                 var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
24849                 if (comment) {
24850                     comment.parent = parent;
24851                 }
24852                 if (contextFlags & 131072 /* JavaScriptFile */) {
24853                     if (!sourceFile.jsDocDiagnostics) {
24854                         sourceFile.jsDocDiagnostics = [];
24855                     }
24856                     (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics);
24857                 }
24858                 currentToken = saveToken;
24859                 parseDiagnostics.length = saveParseDiagnosticsLength;
24860                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
24861                 return comment;
24862             }
24863             JSDocParser.parseJSDocComment = parseJSDocComment;
24864             var JSDocState;
24865             (function (JSDocState) {
24866                 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
24867                 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
24868                 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
24869                 JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
24870             })(JSDocState || (JSDocState = {}));
24871             var PropertyLikeParse;
24872             (function (PropertyLikeParse) {
24873                 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
24874                 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
24875                 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
24876             })(PropertyLikeParse || (PropertyLikeParse = {}));
24877             function parseJSDocCommentWorker(start, length) {
24878                 if (start === void 0) { start = 0; }
24879                 var content = sourceText;
24880                 var end = length === undefined ? content.length : start + length;
24881                 length = end - start;
24882                 ts.Debug.assert(start >= 0);
24883                 ts.Debug.assert(start <= end);
24884                 ts.Debug.assert(end <= content.length);
24885                 // Check for /** (JSDoc opening part)
24886                 if (!isJSDocLikeText(content, start)) {
24887                     return undefined;
24888                 }
24889                 var tags;
24890                 var tagsPos;
24891                 var tagsEnd;
24892                 var comments = [];
24893                 // + 3 for leading /**, - 5 in total for /** */
24894                 return scanner.scanRange(start + 3, length - 5, function () {
24895                     // Initially we can parse out a tag.  We also have seen a starting asterisk.
24896                     // This is so that /** * @type */ doesn't parse.
24897                     var state = 1 /* SawAsterisk */;
24898                     var margin;
24899                     // + 4 for leading '/** '
24900                     var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
24901                     function pushComment(text) {
24902                         if (!margin) {
24903                             margin = indent;
24904                         }
24905                         comments.push(text);
24906                         indent += text.length;
24907                     }
24908                     nextTokenJSDoc();
24909                     while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
24910                         ;
24911                     if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
24912                         state = 0 /* BeginningOfLine */;
24913                         indent = 0;
24914                     }
24915                     loop: while (true) {
24916                         switch (token()) {
24917                             case 59 /* AtToken */:
24918                                 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
24919                                     removeTrailingWhitespace(comments);
24920                                     addTag(parseTag(indent));
24921                                     // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
24922                                     // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
24923                                     // for malformed examples like `/** @param {string} x @returns {number} the length */`
24924                                     state = 0 /* BeginningOfLine */;
24925                                     margin = undefined;
24926                                 }
24927                                 else {
24928                                     pushComment(scanner.getTokenText());
24929                                 }
24930                                 break;
24931                             case 4 /* NewLineTrivia */:
24932                                 comments.push(scanner.getTokenText());
24933                                 state = 0 /* BeginningOfLine */;
24934                                 indent = 0;
24935                                 break;
24936                             case 41 /* AsteriskToken */:
24937                                 var asterisk = scanner.getTokenText();
24938                                 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
24939                                     // If we've already seen an asterisk, then we can no longer parse a tag on this line
24940                                     state = 2 /* SavingComments */;
24941                                     pushComment(asterisk);
24942                                 }
24943                                 else {
24944                                     // Ignore the first asterisk on a line
24945                                     state = 1 /* SawAsterisk */;
24946                                     indent += asterisk.length;
24947                                 }
24948                                 break;
24949                             case 5 /* WhitespaceTrivia */:
24950                                 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
24951                                 var whitespace = scanner.getTokenText();
24952                                 if (state === 2 /* SavingComments */) {
24953                                     comments.push(whitespace);
24954                                 }
24955                                 else if (margin !== undefined && indent + whitespace.length > margin) {
24956                                     comments.push(whitespace.slice(margin - indent - 1));
24957                                 }
24958                                 indent += whitespace.length;
24959                                 break;
24960                             case 1 /* EndOfFileToken */:
24961                                 break loop;
24962                             default:
24963                                 // Anything else is doc comment text. We just save it. Because it
24964                                 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
24965                                 // line break.
24966                                 state = 2 /* SavingComments */;
24967                                 pushComment(scanner.getTokenText());
24968                                 break;
24969                         }
24970                         nextTokenJSDoc();
24971                     }
24972                     removeLeadingNewlines(comments);
24973                     removeTrailingWhitespace(comments);
24974                     return createJSDocComment();
24975                 });
24976                 function removeLeadingNewlines(comments) {
24977                     while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
24978                         comments.shift();
24979                     }
24980                 }
24981                 function removeTrailingWhitespace(comments) {
24982                     while (comments.length && comments[comments.length - 1].trim() === "") {
24983                         comments.pop();
24984                     }
24985                 }
24986                 function createJSDocComment() {
24987                     var result = createNode(303 /* JSDocComment */, start);
24988                     result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
24989                     result.comment = comments.length ? comments.join("") : undefined;
24990                     return finishNode(result, end);
24991                 }
24992                 function isNextNonwhitespaceTokenEndOfFile() {
24993                     // We must use infinite lookahead, as there could be any number of newlines :(
24994                     while (true) {
24995                         nextTokenJSDoc();
24996                         if (token() === 1 /* EndOfFileToken */) {
24997                             return true;
24998                         }
24999                         if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
25000                             return false;
25001                         }
25002                     }
25003                 }
25004                 function skipWhitespace() {
25005                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25006                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25007                             return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25008                         }
25009                     }
25010                     while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25011                         nextTokenJSDoc();
25012                     }
25013                 }
25014                 function skipWhitespaceOrAsterisk() {
25015                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25016                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25017                             return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25018                         }
25019                     }
25020                     var precedingLineBreak = scanner.hasPrecedingLineBreak();
25021                     var seenLineBreak = false;
25022                     var indentText = "";
25023                     while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25024                         indentText += scanner.getTokenText();
25025                         if (token() === 4 /* NewLineTrivia */) {
25026                             precedingLineBreak = true;
25027                             seenLineBreak = true;
25028                             indentText = "";
25029                         }
25030                         else if (token() === 41 /* AsteriskToken */) {
25031                             precedingLineBreak = false;
25032                         }
25033                         nextTokenJSDoc();
25034                     }
25035                     return seenLineBreak ? indentText : "";
25036                 }
25037                 function parseTag(margin) {
25038                     ts.Debug.assert(token() === 59 /* AtToken */);
25039                     var start = scanner.getTokenPos();
25040                     nextTokenJSDoc();
25041                     var tagName = parseJSDocIdentifierName(/*message*/ undefined);
25042                     var indentText = skipWhitespaceOrAsterisk();
25043                     var tag;
25044                     switch (tagName.escapedText) {
25045                         case "author":
25046                             tag = parseAuthorTag(start, tagName, margin);
25047                             break;
25048                         case "implements":
25049                             tag = parseImplementsTag(start, tagName);
25050                             break;
25051                         case "augments":
25052                         case "extends":
25053                             tag = parseAugmentsTag(start, tagName);
25054                             break;
25055                         case "class":
25056                         case "constructor":
25057                             tag = parseSimpleTag(start, 310 /* JSDocClassTag */, tagName);
25058                             break;
25059                         case "public":
25060                             tag = parseSimpleTag(start, 311 /* JSDocPublicTag */, tagName);
25061                             break;
25062                         case "private":
25063                             tag = parseSimpleTag(start, 312 /* JSDocPrivateTag */, tagName);
25064                             break;
25065                         case "protected":
25066                             tag = parseSimpleTag(start, 313 /* JSDocProtectedTag */, tagName);
25067                             break;
25068                         case "readonly":
25069                             tag = parseSimpleTag(start, 314 /* JSDocReadonlyTag */, tagName);
25070                             break;
25071                         case "this":
25072                             tag = parseThisTag(start, tagName);
25073                             break;
25074                         case "enum":
25075                             tag = parseEnumTag(start, tagName);
25076                             break;
25077                         case "arg":
25078                         case "argument":
25079                         case "param":
25080                             return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
25081                         case "return":
25082                         case "returns":
25083                             tag = parseReturnTag(start, tagName);
25084                             break;
25085                         case "template":
25086                             tag = parseTemplateTag(start, tagName);
25087                             break;
25088                         case "type":
25089                             tag = parseTypeTag(start, tagName);
25090                             break;
25091                         case "typedef":
25092                             tag = parseTypedefTag(start, tagName, margin);
25093                             break;
25094                         case "callback":
25095                             tag = parseCallbackTag(start, tagName, margin);
25096                             break;
25097                         default:
25098                             tag = parseUnknownTag(start, tagName);
25099                             break;
25100                     }
25101                     if (!tag.comment) {
25102                         // some tags, like typedef and callback, have already parsed their comments earlier
25103                         if (!indentText) {
25104                             margin += tag.end - tag.pos;
25105                         }
25106                         tag.comment = parseTagComments(margin, indentText.slice(margin));
25107                     }
25108                     return tag;
25109                 }
25110                 function parseTagComments(indent, initialMargin) {
25111                     var comments = [];
25112                     var state = 0 /* BeginningOfLine */;
25113                     var margin;
25114                     function pushComment(text) {
25115                         if (!margin) {
25116                             margin = indent;
25117                         }
25118                         comments.push(text);
25119                         indent += text.length;
25120                     }
25121                     if (initialMargin !== undefined) {
25122                         // jump straight to saving comments if there is some initial indentation
25123                         if (initialMargin !== "") {
25124                             pushComment(initialMargin);
25125                         }
25126                         state = 1 /* SawAsterisk */;
25127                     }
25128                     var tok = token();
25129                     loop: while (true) {
25130                         switch (tok) {
25131                             case 4 /* NewLineTrivia */:
25132                                 if (state >= 1 /* SawAsterisk */) {
25133                                     state = 0 /* BeginningOfLine */;
25134                                     // don't use pushComment here because we want to keep the margin unchanged
25135                                     comments.push(scanner.getTokenText());
25136                                 }
25137                                 indent = 0;
25138                                 break;
25139                             case 59 /* AtToken */:
25140                                 if (state === 3 /* SavingBackticks */) {
25141                                     comments.push(scanner.getTokenText());
25142                                     break;
25143                                 }
25144                                 scanner.setTextPos(scanner.getTextPos() - 1);
25145                             // falls through
25146                             case 1 /* EndOfFileToken */:
25147                                 // Done
25148                                 break loop;
25149                             case 5 /* WhitespaceTrivia */:
25150                                 if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
25151                                     pushComment(scanner.getTokenText());
25152                                 }
25153                                 else {
25154                                     var whitespace = scanner.getTokenText();
25155                                     // if the whitespace crosses the margin, take only the whitespace that passes the margin
25156                                     if (margin !== undefined && indent + whitespace.length > margin) {
25157                                         comments.push(whitespace.slice(margin - indent));
25158                                     }
25159                                     indent += whitespace.length;
25160                                 }
25161                                 break;
25162                             case 18 /* OpenBraceToken */:
25163                                 state = 2 /* SavingComments */;
25164                                 if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
25165                                     pushComment(scanner.getTokenText());
25166                                     nextTokenJSDoc();
25167                                     pushComment(scanner.getTokenText());
25168                                     nextTokenJSDoc();
25169                                 }
25170                                 pushComment(scanner.getTokenText());
25171                                 break;
25172                             case 61 /* BacktickToken */:
25173                                 if (state === 3 /* SavingBackticks */) {
25174                                     state = 2 /* SavingComments */;
25175                                 }
25176                                 else {
25177                                     state = 3 /* SavingBackticks */;
25178                                 }
25179                                 pushComment(scanner.getTokenText());
25180                                 break;
25181                             case 41 /* AsteriskToken */:
25182                                 if (state === 0 /* BeginningOfLine */) {
25183                                     // leading asterisks start recording on the *next* (non-whitespace) token
25184                                     state = 1 /* SawAsterisk */;
25185                                     indent += 1;
25186                                     break;
25187                                 }
25188                             // record the * as a comment
25189                             // falls through
25190                             default:
25191                                 if (state !== 3 /* SavingBackticks */) {
25192                                     state = 2 /* SavingComments */; // leading identifiers start recording as well
25193                                 }
25194                                 pushComment(scanner.getTokenText());
25195                                 break;
25196                         }
25197                         tok = nextTokenJSDoc();
25198                     }
25199                     removeLeadingNewlines(comments);
25200                     removeTrailingWhitespace(comments);
25201                     return comments.length === 0 ? undefined : comments.join("");
25202                 }
25203                 function parseUnknownTag(start, tagName) {
25204                     var result = createNode(306 /* JSDocTag */, start);
25205                     result.tagName = tagName;
25206                     return finishNode(result);
25207                 }
25208                 function addTag(tag) {
25209                     if (!tag) {
25210                         return;
25211                     }
25212                     if (!tags) {
25213                         tags = [tag];
25214                         tagsPos = tag.pos;
25215                     }
25216                     else {
25217                         tags.push(tag);
25218                     }
25219                     tagsEnd = tag.end;
25220                 }
25221                 function tryParseTypeExpression() {
25222                     skipWhitespaceOrAsterisk();
25223                     return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
25224                 }
25225                 function parseBracketNameInPropertyAndParamTag() {
25226                     // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
25227                     var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
25228                     if (isBracketed) {
25229                         skipWhitespace();
25230                     }
25231                     // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
25232                     var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
25233                     var name = parseJSDocEntityName();
25234                     if (isBackquoted) {
25235                         parseExpectedTokenJSDoc(61 /* BacktickToken */);
25236                     }
25237                     if (isBracketed) {
25238                         skipWhitespace();
25239                         // May have an optional default, e.g. '[foo = 42]'
25240                         if (parseOptionalToken(62 /* EqualsToken */)) {
25241                             parseExpression();
25242                         }
25243                         parseExpected(23 /* CloseBracketToken */);
25244                     }
25245                     return { name: name, isBracketed: isBracketed };
25246                 }
25247                 function isObjectOrObjectArrayTypeReference(node) {
25248                     switch (node.kind) {
25249                         case 141 /* ObjectKeyword */:
25250                             return true;
25251                         case 174 /* ArrayType */:
25252                             return isObjectOrObjectArrayTypeReference(node.elementType);
25253                         default:
25254                             return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
25255                     }
25256                 }
25257                 function parseParameterOrPropertyTag(start, tagName, target, indent) {
25258                     var typeExpression = tryParseTypeExpression();
25259                     var isNameFirst = !typeExpression;
25260                     skipWhitespaceOrAsterisk();
25261                     var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
25262                     skipWhitespace();
25263                     if (isNameFirst) {
25264                         typeExpression = tryParseTypeExpression();
25265                     }
25266                     var result = target === 1 /* Property */ ?
25267                         createNode(323 /* JSDocPropertyTag */, start) :
25268                         createNode(317 /* JSDocParameterTag */, start);
25269                     var comment = parseTagComments(indent + scanner.getStartPos() - start);
25270                     var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
25271                     if (nestedTypeLiteral) {
25272                         typeExpression = nestedTypeLiteral;
25273                         isNameFirst = true;
25274                     }
25275                     result.tagName = tagName;
25276                     result.typeExpression = typeExpression;
25277                     result.name = name;
25278                     result.isNameFirst = isNameFirst;
25279                     result.isBracketed = isBracketed;
25280                     result.comment = comment;
25281                     return finishNode(result);
25282                 }
25283                 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
25284                     if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25285                         var typeLiteralExpression = createNode(294 /* JSDocTypeExpression */, scanner.getTokenPos());
25286                         var child = void 0;
25287                         var jsdocTypeLiteral = void 0;
25288                         var start_3 = scanner.getStartPos();
25289                         var children = void 0;
25290                         while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
25291                             if (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) {
25292                                 children = ts.append(children, child);
25293                             }
25294                         }
25295                         if (children) {
25296                             jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start_3);
25297                             jsdocTypeLiteral.jsDocPropertyTags = children;
25298                             if (typeExpression.type.kind === 174 /* ArrayType */) {
25299                                 jsdocTypeLiteral.isArrayType = true;
25300                             }
25301                             typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
25302                             return finishNode(typeLiteralExpression);
25303                         }
25304                     }
25305                 }
25306                 function parseReturnTag(start, tagName) {
25307                     if (ts.some(tags, ts.isJSDocReturnTag)) {
25308                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25309                     }
25310                     var result = createNode(318 /* JSDocReturnTag */, start);
25311                     result.tagName = tagName;
25312                     result.typeExpression = tryParseTypeExpression();
25313                     return finishNode(result);
25314                 }
25315                 function parseTypeTag(start, tagName) {
25316                     if (ts.some(tags, ts.isJSDocTypeTag)) {
25317                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25318                     }
25319                     var result = createNode(320 /* JSDocTypeTag */, start);
25320                     result.tagName = tagName;
25321                     result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25322                     return finishNode(result);
25323                 }
25324                 function parseAuthorTag(start, tagName, indent) {
25325                     var result = createNode(309 /* JSDocAuthorTag */, start);
25326                     result.tagName = tagName;
25327                     var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
25328                     if (!authorInfoWithEmail) {
25329                         return finishNode(result);
25330                     }
25331                     result.comment = authorInfoWithEmail;
25332                     if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
25333                         var comment = parseTagComments(indent);
25334                         if (comment) {
25335                             result.comment += comment;
25336                         }
25337                     }
25338                     return finishNode(result);
25339                 }
25340                 function tryParseAuthorNameAndEmail() {
25341                     var comments = [];
25342                     var seenLessThan = false;
25343                     var seenGreaterThan = false;
25344                     var token = scanner.getToken();
25345                     loop: while (true) {
25346                         switch (token) {
25347                             case 75 /* Identifier */:
25348                             case 5 /* WhitespaceTrivia */:
25349                             case 24 /* DotToken */:
25350                             case 59 /* AtToken */:
25351                                 comments.push(scanner.getTokenText());
25352                                 break;
25353                             case 29 /* LessThanToken */:
25354                                 if (seenLessThan || seenGreaterThan) {
25355                                     return;
25356                                 }
25357                                 seenLessThan = true;
25358                                 comments.push(scanner.getTokenText());
25359                                 break;
25360                             case 31 /* GreaterThanToken */:
25361                                 if (!seenLessThan || seenGreaterThan) {
25362                                     return;
25363                                 }
25364                                 seenGreaterThan = true;
25365                                 comments.push(scanner.getTokenText());
25366                                 scanner.setTextPos(scanner.getTokenPos() + 1);
25367                                 break loop;
25368                             case 4 /* NewLineTrivia */:
25369                             case 1 /* EndOfFileToken */:
25370                                 break loop;
25371                         }
25372                         token = nextTokenJSDoc();
25373                     }
25374                     if (seenLessThan && seenGreaterThan) {
25375                         return comments.length === 0 ? undefined : comments.join("");
25376                     }
25377                 }
25378                 function parseImplementsTag(start, tagName) {
25379                     var result = createNode(308 /* JSDocImplementsTag */, start);
25380                     result.tagName = tagName;
25381                     result.class = parseExpressionWithTypeArgumentsForAugments();
25382                     return finishNode(result);
25383                 }
25384                 function parseAugmentsTag(start, tagName) {
25385                     var result = createNode(307 /* JSDocAugmentsTag */, start);
25386                     result.tagName = tagName;
25387                     result.class = parseExpressionWithTypeArgumentsForAugments();
25388                     return finishNode(result);
25389                 }
25390                 function parseExpressionWithTypeArgumentsForAugments() {
25391                     var usedBrace = parseOptional(18 /* OpenBraceToken */);
25392                     var node = createNode(216 /* ExpressionWithTypeArguments */);
25393                     node.expression = parsePropertyAccessEntityNameExpression();
25394                     node.typeArguments = tryParseTypeArguments();
25395                     var res = finishNode(node);
25396                     if (usedBrace) {
25397                         parseExpected(19 /* CloseBraceToken */);
25398                     }
25399                     return res;
25400                 }
25401                 function parsePropertyAccessEntityNameExpression() {
25402                     var node = parseJSDocIdentifierName();
25403                     while (parseOptional(24 /* DotToken */)) {
25404                         var prop = createNode(194 /* PropertyAccessExpression */, node.pos);
25405                         prop.expression = node;
25406                         prop.name = parseJSDocIdentifierName();
25407                         node = finishNode(prop);
25408                     }
25409                     return node;
25410                 }
25411                 function parseSimpleTag(start, kind, tagName) {
25412                     var tag = createNode(kind, start);
25413                     tag.tagName = tagName;
25414                     return finishNode(tag);
25415                 }
25416                 function parseThisTag(start, tagName) {
25417                     var tag = createNode(319 /* JSDocThisTag */, start);
25418                     tag.tagName = tagName;
25419                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25420                     skipWhitespace();
25421                     return finishNode(tag);
25422                 }
25423                 function parseEnumTag(start, tagName) {
25424                     var tag = createNode(316 /* JSDocEnumTag */, start);
25425                     tag.tagName = tagName;
25426                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25427                     skipWhitespace();
25428                     return finishNode(tag);
25429                 }
25430                 function parseTypedefTag(start, tagName, indent) {
25431                     var typeExpression = tryParseTypeExpression();
25432                     skipWhitespaceOrAsterisk();
25433                     var typedefTag = createNode(322 /* JSDocTypedefTag */, start);
25434                     typedefTag.tagName = tagName;
25435                     typedefTag.fullName = parseJSDocTypeNameWithNamespace();
25436                     typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
25437                     skipWhitespace();
25438                     typedefTag.comment = parseTagComments(indent);
25439                     typedefTag.typeExpression = typeExpression;
25440                     var end;
25441                     if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25442                         var child = void 0;
25443                         var jsdocTypeLiteral = void 0;
25444                         var childTypeTag = void 0;
25445                         while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
25446                             if (!jsdocTypeLiteral) {
25447                                 jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start);
25448                             }
25449                             if (child.kind === 320 /* JSDocTypeTag */) {
25450                                 if (childTypeTag) {
25451                                     break;
25452                                 }
25453                                 else {
25454                                     childTypeTag = child;
25455                                 }
25456                             }
25457                             else {
25458                                 jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child);
25459                             }
25460                         }
25461                         if (jsdocTypeLiteral) {
25462                             if (typeExpression && typeExpression.type.kind === 174 /* ArrayType */) {
25463                                 jsdocTypeLiteral.isArrayType = true;
25464                             }
25465                             typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
25466                                 childTypeTag.typeExpression :
25467                                 finishNode(jsdocTypeLiteral);
25468                             end = typedefTag.typeExpression.end;
25469                         }
25470                     }
25471                     // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
25472                     return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
25473                 }
25474                 function parseJSDocTypeNameWithNamespace(nested) {
25475                     var pos = scanner.getTokenPos();
25476                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25477                         return undefined;
25478                     }
25479                     var typeNameOrNamespaceName = parseJSDocIdentifierName();
25480                     if (parseOptional(24 /* DotToken */)) {
25481                         var jsDocNamespaceNode = createNode(249 /* ModuleDeclaration */, pos);
25482                         if (nested) {
25483                             jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
25484                         }
25485                         jsDocNamespaceNode.name = typeNameOrNamespaceName;
25486                         jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
25487                         return finishNode(jsDocNamespaceNode);
25488                     }
25489                     if (nested) {
25490                         typeNameOrNamespaceName.isInJSDocNamespace = true;
25491                     }
25492                     return typeNameOrNamespaceName;
25493                 }
25494                 function parseCallbackTag(start, tagName, indent) {
25495                     var callbackTag = createNode(315 /* JSDocCallbackTag */, start);
25496                     callbackTag.tagName = tagName;
25497                     callbackTag.fullName = parseJSDocTypeNameWithNamespace();
25498                     callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
25499                     skipWhitespace();
25500                     callbackTag.comment = parseTagComments(indent);
25501                     var child;
25502                     var jsdocSignature = createNode(305 /* JSDocSignature */, start);
25503                     jsdocSignature.parameters = [];
25504                     while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
25505                         jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
25506                     }
25507                     var returnTag = tryParse(function () {
25508                         if (parseOptionalJsdoc(59 /* AtToken */)) {
25509                             var tag = parseTag(indent);
25510                             if (tag && tag.kind === 318 /* JSDocReturnTag */) {
25511                                 return tag;
25512                             }
25513                         }
25514                     });
25515                     if (returnTag) {
25516                         jsdocSignature.type = returnTag;
25517                     }
25518                     callbackTag.typeExpression = finishNode(jsdocSignature);
25519                     return finishNode(callbackTag);
25520                 }
25521                 function getJSDocTypeAliasName(fullName) {
25522                     if (fullName) {
25523                         var rightNode = fullName;
25524                         while (true) {
25525                             if (ts.isIdentifier(rightNode) || !rightNode.body) {
25526                                 return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
25527                             }
25528                             rightNode = rightNode.body;
25529                         }
25530                     }
25531                 }
25532                 function escapedTextsEqual(a, b) {
25533                     while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
25534                         if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
25535                             a = a.left;
25536                             b = b.left;
25537                         }
25538                         else {
25539                             return false;
25540                         }
25541                     }
25542                     return a.escapedText === b.escapedText;
25543                 }
25544                 function parseChildPropertyTag(indent) {
25545                     return parseChildParameterOrPropertyTag(1 /* Property */, indent);
25546                 }
25547                 function parseChildParameterOrPropertyTag(target, indent, name) {
25548                     var canParseTag = true;
25549                     var seenAsterisk = false;
25550                     while (true) {
25551                         switch (nextTokenJSDoc()) {
25552                             case 59 /* AtToken */:
25553                                 if (canParseTag) {
25554                                     var child = tryParseChildTag(target, indent);
25555                                     if (child && (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) &&
25556                                         target !== 4 /* CallbackParameter */ &&
25557                                         name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
25558                                         return false;
25559                                     }
25560                                     return child;
25561                                 }
25562                                 seenAsterisk = false;
25563                                 break;
25564                             case 4 /* NewLineTrivia */:
25565                                 canParseTag = true;
25566                                 seenAsterisk = false;
25567                                 break;
25568                             case 41 /* AsteriskToken */:
25569                                 if (seenAsterisk) {
25570                                     canParseTag = false;
25571                                 }
25572                                 seenAsterisk = true;
25573                                 break;
25574                             case 75 /* Identifier */:
25575                                 canParseTag = false;
25576                                 break;
25577                             case 1 /* EndOfFileToken */:
25578                                 return false;
25579                         }
25580                     }
25581                 }
25582                 function tryParseChildTag(target, indent) {
25583                     ts.Debug.assert(token() === 59 /* AtToken */);
25584                     var start = scanner.getStartPos();
25585                     nextTokenJSDoc();
25586                     var tagName = parseJSDocIdentifierName();
25587                     skipWhitespace();
25588                     var t;
25589                     switch (tagName.escapedText) {
25590                         case "type":
25591                             return target === 1 /* Property */ && parseTypeTag(start, tagName);
25592                         case "prop":
25593                         case "property":
25594                             t = 1 /* Property */;
25595                             break;
25596                         case "arg":
25597                         case "argument":
25598                         case "param":
25599                             t = 2 /* Parameter */ | 4 /* CallbackParameter */;
25600                             break;
25601                         default:
25602                             return false;
25603                     }
25604                     if (!(target & t)) {
25605                         return false;
25606                     }
25607                     return parseParameterOrPropertyTag(start, tagName, target, indent);
25608                 }
25609                 function parseTemplateTag(start, tagName) {
25610                     // the template tag looks like '@template {Constraint} T,U,V'
25611                     var constraint;
25612                     if (token() === 18 /* OpenBraceToken */) {
25613                         constraint = parseJSDocTypeExpression();
25614                     }
25615                     var typeParameters = [];
25616                     var typeParametersPos = getNodePos();
25617                     do {
25618                         skipWhitespace();
25619                         var typeParameter = createNode(155 /* TypeParameter */);
25620                         typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
25621                         finishNode(typeParameter);
25622                         skipWhitespaceOrAsterisk();
25623                         typeParameters.push(typeParameter);
25624                     } while (parseOptionalJsdoc(27 /* CommaToken */));
25625                     var result = createNode(321 /* JSDocTemplateTag */, start);
25626                     result.tagName = tagName;
25627                     result.constraint = constraint;
25628                     result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
25629                     finishNode(result);
25630                     return result;
25631                 }
25632                 function parseOptionalJsdoc(t) {
25633                     if (token() === t) {
25634                         nextTokenJSDoc();
25635                         return true;
25636                     }
25637                     return false;
25638                 }
25639                 function parseJSDocEntityName() {
25640                     var entity = parseJSDocIdentifierName();
25641                     if (parseOptional(22 /* OpenBracketToken */)) {
25642                         parseExpected(23 /* CloseBracketToken */);
25643                         // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
25644                         // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
25645                         // but it's not worth it to enforce that restriction.
25646                     }
25647                     while (parseOptional(24 /* DotToken */)) {
25648                         var name = parseJSDocIdentifierName();
25649                         if (parseOptional(22 /* OpenBracketToken */)) {
25650                             parseExpected(23 /* CloseBracketToken */);
25651                         }
25652                         entity = createQualifiedName(entity, name);
25653                     }
25654                     return entity;
25655                 }
25656                 function parseJSDocIdentifierName(message) {
25657                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25658                         return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
25659                     }
25660                     identifierCount++;
25661                     var pos = scanner.getTokenPos();
25662                     var end = scanner.getTextPos();
25663                     var result = createNode(75 /* Identifier */, pos);
25664                     if (token() !== 75 /* Identifier */) {
25665                         result.originalKeywordKind = token();
25666                     }
25667                     result.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
25668                     finishNode(result, end);
25669                     nextTokenJSDoc();
25670                     return result;
25671                 }
25672             }
25673         })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
25674     })(Parser || (Parser = {}));
25675     var IncrementalParser;
25676     (function (IncrementalParser) {
25677         function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
25678             aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
25679             checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
25680             if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
25681                 // if the text didn't change, then we can just return our current source file as-is.
25682                 return sourceFile;
25683             }
25684             if (sourceFile.statements.length === 0) {
25685                 // If we don't have any statements in the current source file, then there's no real
25686                 // way to incrementally parse.  So just do a full parse instead.
25687                 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
25688             }
25689             // Make sure we're not trying to incrementally update a source file more than once.  Once
25690             // we do an update the original source file is considered unusable from that point onwards.
25691             //
25692             // This is because we do incremental parsing in-place.  i.e. we take nodes from the old
25693             // tree and give them new positions and parents.  From that point on, trusting the old
25694             // tree at all is not possible as far too much of it may violate invariants.
25695             var incrementalSourceFile = sourceFile;
25696             ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
25697             incrementalSourceFile.hasBeenIncrementallyParsed = true;
25698             var oldText = sourceFile.text;
25699             var syntaxCursor = createSyntaxCursor(sourceFile);
25700             // Make the actual change larger so that we know to reparse anything whose lookahead
25701             // might have intersected the change.
25702             var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
25703             checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
25704             // Ensure that extending the affected range only moved the start of the change range
25705             // earlier in the file.
25706             ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
25707             ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
25708             ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
25709             // The is the amount the nodes after the edit range need to be adjusted.  It can be
25710             // positive (if the edit added characters), negative (if the edit deleted characters)
25711             // or zero (if this was a pure overwrite with nothing added/removed).
25712             var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
25713             // If we added or removed characters during the edit, then we need to go and adjust all
25714             // the nodes after the edit.  Those nodes may move forward (if we inserted chars) or they
25715             // may move backward (if we deleted chars).
25716             //
25717             // Doing this helps us out in two ways.  First, it means that any nodes/tokens we want
25718             // to reuse are already at the appropriate position in the new text.  That way when we
25719             // reuse them, we don't have to figure out if they need to be adjusted.  Second, it makes
25720             // it very easy to determine if we can reuse a node.  If the node's position is at where
25721             // we are in the text, then we can reuse it.  Otherwise we can't.  If the node's position
25722             // is ahead of us, then we'll need to rescan tokens.  If the node's position is behind
25723             // us, then we'll need to skip it or crumble it as appropriate
25724             //
25725             // We will also adjust the positions of nodes that intersect the change range as well.
25726             // By doing this, we ensure that all the positions in the old tree are consistent, not
25727             // just the positions of nodes entirely before/after the change range.  By being
25728             // consistent, we can then easily map from positions to nodes in the old tree easily.
25729             //
25730             // Also, mark any syntax elements that intersect the changed span.  We know, up front,
25731             // that we cannot reuse these elements.
25732             updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
25733             // Now that we've set up our internal incremental state just proceed and parse the
25734             // source file in the normal fashion.  When possible the parser will retrieve and
25735             // reuse nodes from the old tree.
25736             //
25737             // Note: passing in 'true' for setNodeParents is very important.  When incrementally
25738             // parsing, we will be reusing nodes from the old tree, and placing it into new
25739             // parents.  If we don't set the parents now, we'll end up with an observably
25740             // inconsistent tree.  Setting the parents on the new tree should be very fast.  We
25741             // will immediately bail out of walking any subtrees when we can see that their parents
25742             // are already correct.
25743             var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
25744             result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
25745             return result;
25746         }
25747         IncrementalParser.updateSourceFile = updateSourceFile;
25748         function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
25749             if (!oldDirectives)
25750                 return newDirectives;
25751             var commentDirectives;
25752             var addedNewlyScannedDirectives = false;
25753             for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
25754                 var directive = oldDirectives_1[_i];
25755                 var range = directive.range, type = directive.type;
25756                 // Range before the change
25757                 if (range.end < changeStart) {
25758                     commentDirectives = ts.append(commentDirectives, directive);
25759                 }
25760                 else if (range.pos > changeRangeOldEnd) {
25761                     addNewlyScannedDirectives();
25762                     // Node is entirely past the change range.  We need to move both its pos and
25763                     // end, forward or backward appropriately.
25764                     var updatedDirective = {
25765                         range: { pos: range.pos + delta, end: range.end + delta },
25766                         type: type
25767                     };
25768                     commentDirectives = ts.append(commentDirectives, updatedDirective);
25769                     if (aggressiveChecks) {
25770                         ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
25771                     }
25772                 }
25773                 // Ignore ranges that fall in change range
25774             }
25775             addNewlyScannedDirectives();
25776             return commentDirectives;
25777             function addNewlyScannedDirectives() {
25778                 if (addedNewlyScannedDirectives)
25779                     return;
25780                 addedNewlyScannedDirectives = true;
25781                 if (!commentDirectives) {
25782                     commentDirectives = newDirectives;
25783                 }
25784                 else if (newDirectives) {
25785                     commentDirectives.push.apply(commentDirectives, newDirectives);
25786                 }
25787             }
25788         }
25789         function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
25790             if (isArray) {
25791                 visitArray(element);
25792             }
25793             else {
25794                 visitNode(element);
25795             }
25796             return;
25797             function visitNode(node) {
25798                 var text = "";
25799                 if (aggressiveChecks && shouldCheckNode(node)) {
25800                     text = oldText.substring(node.pos, node.end);
25801                 }
25802                 // Ditch any existing LS children we may have created.  This way we can avoid
25803                 // moving them forward.
25804                 if (node._children) {
25805                     node._children = undefined;
25806                 }
25807                 node.pos += delta;
25808                 node.end += delta;
25809                 if (aggressiveChecks && shouldCheckNode(node)) {
25810                     ts.Debug.assert(text === newText.substring(node.pos, node.end));
25811                 }
25812                 forEachChild(node, visitNode, visitArray);
25813                 if (ts.hasJSDocNodes(node)) {
25814                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
25815                         var jsDocComment = _a[_i];
25816                         visitNode(jsDocComment);
25817                     }
25818                 }
25819                 checkNodePositions(node, aggressiveChecks);
25820             }
25821             function visitArray(array) {
25822                 array._children = undefined;
25823                 array.pos += delta;
25824                 array.end += delta;
25825                 for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
25826                     var node = array_8[_i];
25827                     visitNode(node);
25828                 }
25829             }
25830         }
25831         function shouldCheckNode(node) {
25832             switch (node.kind) {
25833                 case 10 /* StringLiteral */:
25834                 case 8 /* NumericLiteral */:
25835                 case 75 /* Identifier */:
25836                     return true;
25837             }
25838             return false;
25839         }
25840         function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
25841             ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
25842             ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
25843             ts.Debug.assert(element.pos <= element.end);
25844             // We have an element that intersects the change range in some way.  It may have its
25845             // start, or its end (or both) in the changed range.  We want to adjust any part
25846             // that intersects such that the final tree is in a consistent state.  i.e. all
25847             // children have spans within the span of their parent, and all siblings are ordered
25848             // properly.
25849             // We may need to update both the 'pos' and the 'end' of the element.
25850             // If the 'pos' is before the start of the change, then we don't need to touch it.
25851             // If it isn't, then the 'pos' must be inside the change.  How we update it will
25852             // depend if delta is positive or negative. If delta is positive then we have
25853             // something like:
25854             //
25855             //  -------------------AAA-----------------
25856             //  -------------------BBBCCCCCCC-----------------
25857             //
25858             // In this case, we consider any node that started in the change range to still be
25859             // starting at the same position.
25860             //
25861             // however, if the delta is negative, then we instead have something like this:
25862             //
25863             //  -------------------XXXYYYYYYY-----------------
25864             //  -------------------ZZZ-----------------
25865             //
25866             // In this case, any element that started in the 'X' range will keep its position.
25867             // However any element that started after that will have their pos adjusted to be
25868             // at the end of the new range.  i.e. any node that started in the 'Y' range will
25869             // be adjusted to have their start at the end of the 'Z' range.
25870             //
25871             // The element will keep its position if possible.  Or Move backward to the new-end
25872             // if it's in the 'Y' range.
25873             element.pos = Math.min(element.pos, changeRangeNewEnd);
25874             // If the 'end' is after the change range, then we always adjust it by the delta
25875             // amount.  However, if the end is in the change range, then how we adjust it
25876             // will depend on if delta is positive or negative.  If delta is positive then we
25877             // have something like:
25878             //
25879             //  -------------------AAA-----------------
25880             //  -------------------BBBCCCCCCC-----------------
25881             //
25882             // In this case, we consider any node that ended inside the change range to keep its
25883             // end position.
25884             //
25885             // however, if the delta is negative, then we instead have something like this:
25886             //
25887             //  -------------------XXXYYYYYYY-----------------
25888             //  -------------------ZZZ-----------------
25889             //
25890             // In this case, any element that ended in the 'X' range will keep its position.
25891             // However any element that ended after that will have their pos adjusted to be
25892             // at the end of the new range.  i.e. any node that ended in the 'Y' range will
25893             // be adjusted to have their end at the end of the 'Z' range.
25894             if (element.end >= changeRangeOldEnd) {
25895                 // Element ends after the change range.  Always adjust the end pos.
25896                 element.end += delta;
25897             }
25898             else {
25899                 // Element ends in the change range.  The element will keep its position if
25900                 // possible. Or Move backward to the new-end if it's in the 'Y' range.
25901                 element.end = Math.min(element.end, changeRangeNewEnd);
25902             }
25903             ts.Debug.assert(element.pos <= element.end);
25904             if (element.parent) {
25905                 ts.Debug.assert(element.pos >= element.parent.pos);
25906                 ts.Debug.assert(element.end <= element.parent.end);
25907             }
25908         }
25909         function checkNodePositions(node, aggressiveChecks) {
25910             if (aggressiveChecks) {
25911                 var pos_2 = node.pos;
25912                 var visitNode_1 = function (child) {
25913                     ts.Debug.assert(child.pos >= pos_2);
25914                     pos_2 = child.end;
25915                 };
25916                 if (ts.hasJSDocNodes(node)) {
25917                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
25918                         var jsDocComment = _a[_i];
25919                         visitNode_1(jsDocComment);
25920                     }
25921                 }
25922                 forEachChild(node, visitNode_1);
25923                 ts.Debug.assert(pos_2 <= node.end);
25924             }
25925         }
25926         function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
25927             visitNode(sourceFile);
25928             return;
25929             function visitNode(child) {
25930                 ts.Debug.assert(child.pos <= child.end);
25931                 if (child.pos > changeRangeOldEnd) {
25932                     // Node is entirely past the change range.  We need to move both its pos and
25933                     // end, forward or backward appropriately.
25934                     moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
25935                     return;
25936                 }
25937                 // Check if the element intersects the change range.  If it does, then it is not
25938                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
25939                 // be able to use.
25940                 var fullEnd = child.end;
25941                 if (fullEnd >= changeStart) {
25942                     child.intersectsChange = true;
25943                     child._children = undefined;
25944                     // Adjust the pos or end (or both) of the intersecting element accordingly.
25945                     adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
25946                     forEachChild(child, visitNode, visitArray);
25947                     if (ts.hasJSDocNodes(child)) {
25948                         for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
25949                             var jsDocComment = _a[_i];
25950                             visitNode(jsDocComment);
25951                         }
25952                     }
25953                     checkNodePositions(child, aggressiveChecks);
25954                     return;
25955                 }
25956                 // Otherwise, the node is entirely before the change range.  No need to do anything with it.
25957                 ts.Debug.assert(fullEnd < changeStart);
25958             }
25959             function visitArray(array) {
25960                 ts.Debug.assert(array.pos <= array.end);
25961                 if (array.pos > changeRangeOldEnd) {
25962                     // Array is entirely after the change range.  We need to move it, and move any of
25963                     // its children.
25964                     moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
25965                     return;
25966                 }
25967                 // Check if the element intersects the change range.  If it does, then it is not
25968                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
25969                 // be able to use.
25970                 var fullEnd = array.end;
25971                 if (fullEnd >= changeStart) {
25972                     array.intersectsChange = true;
25973                     array._children = undefined;
25974                     // Adjust the pos or end (or both) of the intersecting array accordingly.
25975                     adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
25976                     for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
25977                         var node = array_9[_i];
25978                         visitNode(node);
25979                     }
25980                     return;
25981                 }
25982                 // Otherwise, the array is entirely before the change range.  No need to do anything with it.
25983                 ts.Debug.assert(fullEnd < changeStart);
25984             }
25985         }
25986         function extendToAffectedRange(sourceFile, changeRange) {
25987             // Consider the following code:
25988             //      void foo() { /; }
25989             //
25990             // If the text changes with an insertion of / just before the semicolon then we end up with:
25991             //      void foo() { //; }
25992             //
25993             // If we were to just use the changeRange a is, then we would not rescan the { token
25994             // (as it does not intersect the actual original change range).  Because an edit may
25995             // change the token touching it, we actually need to look back *at least* one token so
25996             // that the prior token sees that change.
25997             var maxLookahead = 1;
25998             var start = changeRange.span.start;
25999             // the first iteration aligns us with the change start. subsequent iteration move us to
26000             // the left by maxLookahead tokens.  We only need to do this as long as we're not at the
26001             // start of the tree.
26002             for (var i = 0; start > 0 && i <= maxLookahead; i++) {
26003                 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
26004                 ts.Debug.assert(nearestNode.pos <= start);
26005                 var position = nearestNode.pos;
26006                 start = Math.max(0, position - 1);
26007             }
26008             var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
26009             var finalLength = changeRange.newLength + (changeRange.span.start - start);
26010             return ts.createTextChangeRange(finalSpan, finalLength);
26011         }
26012         function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
26013             var bestResult = sourceFile;
26014             var lastNodeEntirelyBeforePosition;
26015             forEachChild(sourceFile, visit);
26016             if (lastNodeEntirelyBeforePosition) {
26017                 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
26018                 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
26019                     bestResult = lastChildOfLastEntireNodeBeforePosition;
26020                 }
26021             }
26022             return bestResult;
26023             function getLastDescendant(node) {
26024                 while (true) {
26025                     var lastChild = ts.getLastChild(node);
26026                     if (lastChild) {
26027                         node = lastChild;
26028                     }
26029                     else {
26030                         return node;
26031                     }
26032                 }
26033             }
26034             function visit(child) {
26035                 if (ts.nodeIsMissing(child)) {
26036                     // Missing nodes are effectively invisible to us.  We never even consider them
26037                     // When trying to find the nearest node before us.
26038                     return;
26039                 }
26040                 // If the child intersects this position, then this node is currently the nearest
26041                 // node that starts before the position.
26042                 if (child.pos <= position) {
26043                     if (child.pos >= bestResult.pos) {
26044                         // This node starts before the position, and is closer to the position than
26045                         // the previous best node we found.  It is now the new best node.
26046                         bestResult = child;
26047                     }
26048                     // Now, the node may overlap the position, or it may end entirely before the
26049                     // position.  If it overlaps with the position, then either it, or one of its
26050                     // children must be the nearest node before the position.  So we can just
26051                     // recurse into this child to see if we can find something better.
26052                     if (position < child.end) {
26053                         // The nearest node is either this child, or one of the children inside
26054                         // of it.  We've already marked this child as the best so far.  Recurse
26055                         // in case one of the children is better.
26056                         forEachChild(child, visit);
26057                         // Once we look at the children of this node, then there's no need to
26058                         // continue any further.
26059                         return true;
26060                     }
26061                     else {
26062                         ts.Debug.assert(child.end <= position);
26063                         // The child ends entirely before this position.  Say you have the following
26064                         // (where $ is the position)
26065                         //
26066                         //      <complex expr 1> ? <complex expr 2> $ : <...> <...>
26067                         //
26068                         // We would want to find the nearest preceding node in "complex expr 2".
26069                         // To support that, we keep track of this node, and once we're done searching
26070                         // for a best node, we recurse down this node to see if we can find a good
26071                         // result in it.
26072                         //
26073                         // This approach allows us to quickly skip over nodes that are entirely
26074                         // before the position, while still allowing us to find any nodes in the
26075                         // last one that might be what we want.
26076                         lastNodeEntirelyBeforePosition = child;
26077                     }
26078                 }
26079                 else {
26080                     ts.Debug.assert(child.pos > position);
26081                     // We're now at a node that is entirely past the position we're searching for.
26082                     // This node (and all following nodes) could never contribute to the result,
26083                     // so just skip them by returning 'true' here.
26084                     return true;
26085                 }
26086             }
26087         }
26088         function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
26089             var oldText = sourceFile.text;
26090             if (textChangeRange) {
26091                 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
26092                 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
26093                     var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
26094                     var newTextPrefix = newText.substr(0, textChangeRange.span.start);
26095                     ts.Debug.assert(oldTextPrefix === newTextPrefix);
26096                     var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
26097                     var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
26098                     ts.Debug.assert(oldTextSuffix === newTextSuffix);
26099                 }
26100             }
26101         }
26102         function createSyntaxCursor(sourceFile) {
26103             var currentArray = sourceFile.statements;
26104             var currentArrayIndex = 0;
26105             ts.Debug.assert(currentArrayIndex < currentArray.length);
26106             var current = currentArray[currentArrayIndex];
26107             var lastQueriedPosition = -1 /* Value */;
26108             return {
26109                 currentNode: function (position) {
26110                     // Only compute the current node if the position is different than the last time
26111                     // we were asked.  The parser commonly asks for the node at the same position
26112                     // twice.  Once to know if can read an appropriate list element at a certain point,
26113                     // and then to actually read and consume the node.
26114                     if (position !== lastQueriedPosition) {
26115                         // Much of the time the parser will need the very next node in the array that
26116                         // we just returned a node from.So just simply check for that case and move
26117                         // forward in the array instead of searching for the node again.
26118                         if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
26119                             currentArrayIndex++;
26120                             current = currentArray[currentArrayIndex];
26121                         }
26122                         // If we don't have a node, or the node we have isn't in the right position,
26123                         // then try to find a viable node at the position requested.
26124                         if (!current || current.pos !== position) {
26125                             findHighestListElementThatStartsAtPosition(position);
26126                         }
26127                     }
26128                     // Cache this query so that we don't do any extra work if the parser calls back
26129                     // into us.  Note: this is very common as the parser will make pairs of calls like
26130                     // 'isListElement -> parseListElement'.  If we were unable to find a node when
26131                     // called with 'isListElement', we don't want to redo the work when parseListElement
26132                     // is called immediately after.
26133                     lastQueriedPosition = position;
26134                     // Either we don'd have a node, or we have a node at the position being asked for.
26135                     ts.Debug.assert(!current || current.pos === position);
26136                     return current;
26137                 }
26138             };
26139             // Finds the highest element in the tree we can find that starts at the provided position.
26140             // The element must be a direct child of some node list in the tree.  This way after we
26141             // return it, we can easily return its next sibling in the list.
26142             function findHighestListElementThatStartsAtPosition(position) {
26143                 // Clear out any cached state about the last node we found.
26144                 currentArray = undefined;
26145                 currentArrayIndex = -1 /* Value */;
26146                 current = undefined;
26147                 // Recurse into the source file to find the highest node at this position.
26148                 forEachChild(sourceFile, visitNode, visitArray);
26149                 return;
26150                 function visitNode(node) {
26151                     if (position >= node.pos && position < node.end) {
26152                         // Position was within this node.  Keep searching deeper to find the node.
26153                         forEachChild(node, visitNode, visitArray);
26154                         // don't proceed any further in the search.
26155                         return true;
26156                     }
26157                     // position wasn't in this node, have to keep searching.
26158                     return false;
26159                 }
26160                 function visitArray(array) {
26161                     if (position >= array.pos && position < array.end) {
26162                         // position was in this array.  Search through this array to see if we find a
26163                         // viable element.
26164                         for (var i = 0; i < array.length; i++) {
26165                             var child = array[i];
26166                             if (child) {
26167                                 if (child.pos === position) {
26168                                     // Found the right node.  We're done.
26169                                     currentArray = array;
26170                                     currentArrayIndex = i;
26171                                     current = child;
26172                                     return true;
26173                                 }
26174                                 else {
26175                                     if (child.pos < position && position < child.end) {
26176                                         // Position in somewhere within this child.  Search in it and
26177                                         // stop searching in this array.
26178                                         forEachChild(child, visitNode, visitArray);
26179                                         return true;
26180                                     }
26181                                 }
26182                             }
26183                         }
26184                     }
26185                     // position wasn't in this array, have to keep searching.
26186                     return false;
26187                 }
26188             }
26189         }
26190         var InvalidPosition;
26191         (function (InvalidPosition) {
26192             InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
26193         })(InvalidPosition || (InvalidPosition = {}));
26194     })(IncrementalParser || (IncrementalParser = {}));
26195     /** @internal */
26196     function isDeclarationFileName(fileName) {
26197         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
26198     }
26199     ts.isDeclarationFileName = isDeclarationFileName;
26200     /*@internal*/
26201     function processCommentPragmas(context, sourceText) {
26202         var pragmas = [];
26203         for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
26204             var range = _a[_i];
26205             var comment = sourceText.substring(range.pos, range.end);
26206             extractPragmas(pragmas, range, comment);
26207         }
26208         context.pragmas = ts.createMap();
26209         for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
26210             var pragma = pragmas_1[_b];
26211             if (context.pragmas.has(pragma.name)) {
26212                 var currentValue = context.pragmas.get(pragma.name);
26213                 if (currentValue instanceof Array) {
26214                     currentValue.push(pragma.args);
26215                 }
26216                 else {
26217                     context.pragmas.set(pragma.name, [currentValue, pragma.args]);
26218                 }
26219                 continue;
26220             }
26221             context.pragmas.set(pragma.name, pragma.args);
26222         }
26223     }
26224     ts.processCommentPragmas = processCommentPragmas;
26225     /*@internal*/
26226     function processPragmasIntoFields(context, reportDiagnostic) {
26227         context.checkJsDirective = undefined;
26228         context.referencedFiles = [];
26229         context.typeReferenceDirectives = [];
26230         context.libReferenceDirectives = [];
26231         context.amdDependencies = [];
26232         context.hasNoDefaultLib = false;
26233         context.pragmas.forEach(function (entryOrList, key) {
26234             // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
26235             // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
26236             switch (key) {
26237                 case "reference": {
26238                     var referencedFiles_1 = context.referencedFiles;
26239                     var typeReferenceDirectives_1 = context.typeReferenceDirectives;
26240                     var libReferenceDirectives_1 = context.libReferenceDirectives;
26241                     ts.forEach(ts.toArray(entryOrList), function (arg) {
26242                         var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
26243                         if (arg.arguments["no-default-lib"]) {
26244                             context.hasNoDefaultLib = true;
26245                         }
26246                         else if (types) {
26247                             typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
26248                         }
26249                         else if (lib) {
26250                             libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
26251                         }
26252                         else if (path) {
26253                             referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
26254                         }
26255                         else {
26256                             reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
26257                         }
26258                     });
26259                     break;
26260                 }
26261                 case "amd-dependency": {
26262                     context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
26263                     break;
26264                 }
26265                 case "amd-module": {
26266                     if (entryOrList instanceof Array) {
26267                         for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
26268                             var entry = entryOrList_1[_i];
26269                             if (context.moduleName) {
26270                                 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
26271                                 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
26272                             }
26273                             context.moduleName = entry.arguments.name;
26274                         }
26275                     }
26276                     else {
26277                         context.moduleName = entryOrList.arguments.name;
26278                     }
26279                     break;
26280                 }
26281                 case "ts-nocheck":
26282                 case "ts-check": {
26283                     // _last_ of either nocheck or check in a file is the "winner"
26284                     ts.forEach(ts.toArray(entryOrList), function (entry) {
26285                         if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
26286                             context.checkJsDirective = {
26287                                 enabled: key === "ts-check",
26288                                 end: entry.range.end,
26289                                 pos: entry.range.pos
26290                             };
26291                         }
26292                     });
26293                     break;
26294                 }
26295                 case "jsx": return; // Accessed directly
26296                 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
26297             }
26298         });
26299     }
26300     ts.processPragmasIntoFields = processPragmasIntoFields;
26301     var namedArgRegExCache = ts.createMap();
26302     function getNamedArgRegEx(name) {
26303         if (namedArgRegExCache.has(name)) {
26304             return namedArgRegExCache.get(name);
26305         }
26306         var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
26307         namedArgRegExCache.set(name, result);
26308         return result;
26309     }
26310     var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
26311     var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
26312     function extractPragmas(pragmas, range, text) {
26313         var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
26314         if (tripleSlash) {
26315             var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
26316             var pragma = ts.commentPragmas[name];
26317             if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
26318                 return;
26319             }
26320             if (pragma.args) {
26321                 var argument = {};
26322                 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
26323                     var arg = _a[_i];
26324                     var matcher = getNamedArgRegEx(arg.name);
26325                     var matchResult = matcher.exec(text);
26326                     if (!matchResult && !arg.optional) {
26327                         return; // Missing required argument, don't parse
26328                     }
26329                     else if (matchResult) {
26330                         if (arg.captureSpan) {
26331                             var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
26332                             argument[arg.name] = {
26333                                 value: matchResult[3],
26334                                 pos: startPos,
26335                                 end: startPos + matchResult[3].length
26336                             };
26337                         }
26338                         else {
26339                             argument[arg.name] = matchResult[3];
26340                         }
26341                     }
26342                 }
26343                 pragmas.push({ name: name, args: { arguments: argument, range: range } });
26344             }
26345             else {
26346                 pragmas.push({ name: name, args: { arguments: {}, range: range } });
26347             }
26348             return;
26349         }
26350         var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
26351         if (singleLine) {
26352             return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
26353         }
26354         if (range.kind === 3 /* MultiLineCommentTrivia */) {
26355             var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
26356             var multiLineMatch = void 0;
26357             while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
26358                 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
26359             }
26360         }
26361     }
26362     function addPragmaForMatch(pragmas, range, kind, match) {
26363         if (!match)
26364             return;
26365         var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
26366         var pragma = ts.commentPragmas[name];
26367         if (!pragma || !(pragma.kind & kind)) {
26368             return;
26369         }
26370         var args = match[2]; // Split on spaces and match up positionally with definition
26371         var argument = getNamedPragmaArguments(pragma, args);
26372         if (argument === "fail")
26373             return; // Missing required argument, fail to parse it
26374         pragmas.push({ name: name, args: { arguments: argument, range: range } });
26375         return;
26376     }
26377     function getNamedPragmaArguments(pragma, text) {
26378         if (!text)
26379             return {};
26380         if (!pragma.args)
26381             return {};
26382         var args = text.split(/\s+/);
26383         var argMap = {};
26384         for (var i = 0; i < pragma.args.length; i++) {
26385             var argument = pragma.args[i];
26386             if (!args[i] && !argument.optional) {
26387                 return "fail";
26388             }
26389             if (argument.captureSpan) {
26390                 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
26391             }
26392             argMap[argument.name] = args[i];
26393         }
26394         return argMap;
26395     }
26396     /** @internal */
26397     function tagNamesAreEquivalent(lhs, rhs) {
26398         if (lhs.kind !== rhs.kind) {
26399             return false;
26400         }
26401         if (lhs.kind === 75 /* Identifier */) {
26402             return lhs.escapedText === rhs.escapedText;
26403         }
26404         if (lhs.kind === 104 /* ThisKeyword */) {
26405             return true;
26406         }
26407         // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
26408         // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
26409         // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
26410         return lhs.name.escapedText === rhs.name.escapedText &&
26411             tagNamesAreEquivalent(lhs.expression, rhs.expression);
26412     }
26413     ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
26414 })(ts || (ts = {}));
26415 var ts;
26416 (function (ts) {
26417     /* @internal */
26418     ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
26419     // NOTE: The order here is important to default lib ordering as entries will have the same
26420     //       order in the generated program (see `getDefaultLibPriority` in program.ts). This
26421     //       order also affects overload resolution when a type declared in one lib is
26422     //       augmented in another lib.
26423     var libEntries = [
26424         // JavaScript only
26425         ["es5", "lib.es5.d.ts"],
26426         ["es6", "lib.es2015.d.ts"],
26427         ["es2015", "lib.es2015.d.ts"],
26428         ["es7", "lib.es2016.d.ts"],
26429         ["es2016", "lib.es2016.d.ts"],
26430         ["es2017", "lib.es2017.d.ts"],
26431         ["es2018", "lib.es2018.d.ts"],
26432         ["es2019", "lib.es2019.d.ts"],
26433         ["es2020", "lib.es2020.d.ts"],
26434         ["esnext", "lib.esnext.d.ts"],
26435         // Host only
26436         ["dom", "lib.dom.d.ts"],
26437         ["dom.iterable", "lib.dom.iterable.d.ts"],
26438         ["webworker", "lib.webworker.d.ts"],
26439         ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
26440         ["scripthost", "lib.scripthost.d.ts"],
26441         // ES2015 Or ESNext By-feature options
26442         ["es2015.core", "lib.es2015.core.d.ts"],
26443         ["es2015.collection", "lib.es2015.collection.d.ts"],
26444         ["es2015.generator", "lib.es2015.generator.d.ts"],
26445         ["es2015.iterable", "lib.es2015.iterable.d.ts"],
26446         ["es2015.promise", "lib.es2015.promise.d.ts"],
26447         ["es2015.proxy", "lib.es2015.proxy.d.ts"],
26448         ["es2015.reflect", "lib.es2015.reflect.d.ts"],
26449         ["es2015.symbol", "lib.es2015.symbol.d.ts"],
26450         ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
26451         ["es2016.array.include", "lib.es2016.array.include.d.ts"],
26452         ["es2017.object", "lib.es2017.object.d.ts"],
26453         ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
26454         ["es2017.string", "lib.es2017.string.d.ts"],
26455         ["es2017.intl", "lib.es2017.intl.d.ts"],
26456         ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
26457         ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
26458         ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
26459         ["es2018.intl", "lib.es2018.intl.d.ts"],
26460         ["es2018.promise", "lib.es2018.promise.d.ts"],
26461         ["es2018.regexp", "lib.es2018.regexp.d.ts"],
26462         ["es2019.array", "lib.es2019.array.d.ts"],
26463         ["es2019.object", "lib.es2019.object.d.ts"],
26464         ["es2019.string", "lib.es2019.string.d.ts"],
26465         ["es2019.symbol", "lib.es2019.symbol.d.ts"],
26466         ["es2020.bigint", "lib.es2020.bigint.d.ts"],
26467         ["es2020.promise", "lib.es2020.promise.d.ts"],
26468         ["es2020.string", "lib.es2020.string.d.ts"],
26469         ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
26470         ["esnext.array", "lib.es2019.array.d.ts"],
26471         ["esnext.symbol", "lib.es2019.symbol.d.ts"],
26472         ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
26473         ["esnext.intl", "lib.esnext.intl.d.ts"],
26474         ["esnext.bigint", "lib.es2020.bigint.d.ts"],
26475         ["esnext.string", "lib.esnext.string.d.ts"],
26476         ["esnext.promise", "lib.esnext.promise.d.ts"]
26477     ];
26478     /**
26479      * An array of supported "lib" reference file names used to determine the order for inclusion
26480      * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
26481      * overload resolution when a type declared in one lib is extended by another.
26482      */
26483     /* @internal */
26484     ts.libs = libEntries.map(function (entry) { return entry[0]; });
26485     /**
26486      * A map of lib names to lib files. This map is used both for parsing the "lib" command line
26487      * option as well as for resolving lib reference directives.
26488      */
26489     /* @internal */
26490     ts.libMap = ts.createMapFromEntries(libEntries);
26491     // Watch related options
26492     /* @internal */
26493     ts.optionsForWatch = [
26494         {
26495             name: "watchFile",
26496             type: ts.createMapFromTemplate({
26497                 fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
26498                 prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
26499                 dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
26500                 usefsevents: ts.WatchFileKind.UseFsEvents,
26501                 usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
26502             }),
26503             category: ts.Diagnostics.Advanced_Options,
26504             description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
26505         },
26506         {
26507             name: "watchDirectory",
26508             type: ts.createMapFromTemplate({
26509                 usefsevents: ts.WatchDirectoryKind.UseFsEvents,
26510                 fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
26511                 dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
26512             }),
26513             category: ts.Diagnostics.Advanced_Options,
26514             description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
26515         },
26516         {
26517             name: "fallbackPolling",
26518             type: ts.createMapFromTemplate({
26519                 fixedinterval: ts.PollingWatchKind.FixedInterval,
26520                 priorityinterval: ts.PollingWatchKind.PriorityInterval,
26521                 dynamicpriority: ts.PollingWatchKind.DynamicPriority,
26522             }),
26523             category: ts.Diagnostics.Advanced_Options,
26524             description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
26525         },
26526         {
26527             name: "synchronousWatchDirectory",
26528             type: "boolean",
26529             category: ts.Diagnostics.Advanced_Options,
26530             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
26531         },
26532     ];
26533     /* @internal */
26534     ts.commonOptionsWithBuild = [
26535         {
26536             name: "help",
26537             shortName: "h",
26538             type: "boolean",
26539             showInSimplifiedHelpView: true,
26540             category: ts.Diagnostics.Command_line_Options,
26541             description: ts.Diagnostics.Print_this_message,
26542         },
26543         {
26544             name: "help",
26545             shortName: "?",
26546             type: "boolean"
26547         },
26548         {
26549             name: "watch",
26550             shortName: "w",
26551             type: "boolean",
26552             showInSimplifiedHelpView: true,
26553             category: ts.Diagnostics.Command_line_Options,
26554             description: ts.Diagnostics.Watch_input_files,
26555         },
26556         {
26557             name: "preserveWatchOutput",
26558             type: "boolean",
26559             showInSimplifiedHelpView: false,
26560             category: ts.Diagnostics.Command_line_Options,
26561             description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
26562         },
26563         {
26564             name: "listFiles",
26565             type: "boolean",
26566             category: ts.Diagnostics.Advanced_Options,
26567             description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
26568         },
26569         {
26570             name: "listEmittedFiles",
26571             type: "boolean",
26572             category: ts.Diagnostics.Advanced_Options,
26573             description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
26574         },
26575         {
26576             name: "pretty",
26577             type: "boolean",
26578             showInSimplifiedHelpView: true,
26579             category: ts.Diagnostics.Command_line_Options,
26580             description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
26581         },
26582         {
26583             name: "traceResolution",
26584             type: "boolean",
26585             category: ts.Diagnostics.Advanced_Options,
26586             description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
26587         },
26588         {
26589             name: "diagnostics",
26590             type: "boolean",
26591             category: ts.Diagnostics.Advanced_Options,
26592             description: ts.Diagnostics.Show_diagnostic_information
26593         },
26594         {
26595             name: "extendedDiagnostics",
26596             type: "boolean",
26597             category: ts.Diagnostics.Advanced_Options,
26598             description: ts.Diagnostics.Show_verbose_diagnostic_information
26599         },
26600         {
26601             name: "generateCpuProfile",
26602             type: "string",
26603             isFilePath: true,
26604             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26605             category: ts.Diagnostics.Advanced_Options,
26606             description: ts.Diagnostics.Generates_a_CPU_profile
26607         },
26608         {
26609             name: "incremental",
26610             shortName: "i",
26611             type: "boolean",
26612             category: ts.Diagnostics.Basic_Options,
26613             description: ts.Diagnostics.Enable_incremental_compilation,
26614             transpileOptionValue: undefined
26615         },
26616         {
26617             name: "assumeChangesOnlyAffectDirectDependencies",
26618             type: "boolean",
26619             affectsSemanticDiagnostics: true,
26620             affectsEmit: true,
26621             category: ts.Diagnostics.Advanced_Options,
26622             description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
26623         },
26624         {
26625             name: "locale",
26626             type: "string",
26627             category: ts.Diagnostics.Advanced_Options,
26628             description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
26629         },
26630     ];
26631     /* @internal */
26632     ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
26633         {
26634             name: "all",
26635             type: "boolean",
26636             showInSimplifiedHelpView: true,
26637             category: ts.Diagnostics.Command_line_Options,
26638             description: ts.Diagnostics.Show_all_compiler_options,
26639         },
26640         {
26641             name: "version",
26642             shortName: "v",
26643             type: "boolean",
26644             showInSimplifiedHelpView: true,
26645             category: ts.Diagnostics.Command_line_Options,
26646             description: ts.Diagnostics.Print_the_compiler_s_version,
26647         },
26648         {
26649             name: "init",
26650             type: "boolean",
26651             showInSimplifiedHelpView: true,
26652             category: ts.Diagnostics.Command_line_Options,
26653             description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
26654         },
26655         {
26656             name: "project",
26657             shortName: "p",
26658             type: "string",
26659             isFilePath: true,
26660             showInSimplifiedHelpView: true,
26661             category: ts.Diagnostics.Command_line_Options,
26662             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26663             description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
26664         },
26665         {
26666             name: "build",
26667             type: "boolean",
26668             shortName: "b",
26669             showInSimplifiedHelpView: true,
26670             category: ts.Diagnostics.Command_line_Options,
26671             description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
26672         },
26673         {
26674             name: "showConfig",
26675             type: "boolean",
26676             category: ts.Diagnostics.Command_line_Options,
26677             isCommandLineOnly: true,
26678             description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
26679         },
26680         {
26681             name: "listFilesOnly",
26682             type: "boolean",
26683             category: ts.Diagnostics.Command_line_Options,
26684             affectsSemanticDiagnostics: true,
26685             affectsEmit: true,
26686             isCommandLineOnly: true,
26687             description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
26688         },
26689         // Basic
26690         {
26691             name: "target",
26692             shortName: "t",
26693             type: ts.createMapFromTemplate({
26694                 es3: 0 /* ES3 */,
26695                 es5: 1 /* ES5 */,
26696                 es6: 2 /* ES2015 */,
26697                 es2015: 2 /* ES2015 */,
26698                 es2016: 3 /* ES2016 */,
26699                 es2017: 4 /* ES2017 */,
26700                 es2018: 5 /* ES2018 */,
26701                 es2019: 6 /* ES2019 */,
26702                 es2020: 7 /* ES2020 */,
26703                 esnext: 99 /* ESNext */,
26704             }),
26705             affectsSourceFile: true,
26706             affectsModuleResolution: true,
26707             affectsEmit: true,
26708             paramType: ts.Diagnostics.VERSION,
26709             showInSimplifiedHelpView: true,
26710             category: ts.Diagnostics.Basic_Options,
26711             description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
26712         },
26713         {
26714             name: "module",
26715             shortName: "m",
26716             type: ts.createMapFromTemplate({
26717                 none: ts.ModuleKind.None,
26718                 commonjs: ts.ModuleKind.CommonJS,
26719                 amd: ts.ModuleKind.AMD,
26720                 system: ts.ModuleKind.System,
26721                 umd: ts.ModuleKind.UMD,
26722                 es6: ts.ModuleKind.ES2015,
26723                 es2015: ts.ModuleKind.ES2015,
26724                 es2020: ts.ModuleKind.ES2020,
26725                 esnext: ts.ModuleKind.ESNext
26726             }),
26727             affectsModuleResolution: true,
26728             affectsEmit: true,
26729             paramType: ts.Diagnostics.KIND,
26730             showInSimplifiedHelpView: true,
26731             category: ts.Diagnostics.Basic_Options,
26732             description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
26733         },
26734         {
26735             name: "lib",
26736             type: "list",
26737             element: {
26738                 name: "lib",
26739                 type: ts.libMap
26740             },
26741             affectsModuleResolution: true,
26742             showInSimplifiedHelpView: true,
26743             category: ts.Diagnostics.Basic_Options,
26744             description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
26745             transpileOptionValue: undefined
26746         },
26747         {
26748             name: "allowJs",
26749             type: "boolean",
26750             affectsModuleResolution: true,
26751             showInSimplifiedHelpView: true,
26752             category: ts.Diagnostics.Basic_Options,
26753             description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
26754         },
26755         {
26756             name: "checkJs",
26757             type: "boolean",
26758             category: ts.Diagnostics.Basic_Options,
26759             description: ts.Diagnostics.Report_errors_in_js_files
26760         },
26761         {
26762             name: "jsx",
26763             type: ts.createMapFromTemplate({
26764                 "preserve": 1 /* Preserve */,
26765                 "react-native": 3 /* ReactNative */,
26766                 "react": 2 /* React */
26767             }),
26768             affectsSourceFile: true,
26769             paramType: ts.Diagnostics.KIND,
26770             showInSimplifiedHelpView: true,
26771             category: ts.Diagnostics.Basic_Options,
26772             description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
26773         },
26774         {
26775             name: "declaration",
26776             shortName: "d",
26777             type: "boolean",
26778             affectsEmit: true,
26779             showInSimplifiedHelpView: true,
26780             category: ts.Diagnostics.Basic_Options,
26781             description: ts.Diagnostics.Generates_corresponding_d_ts_file,
26782             transpileOptionValue: undefined
26783         },
26784         {
26785             name: "declarationMap",
26786             type: "boolean",
26787             affectsEmit: true,
26788             showInSimplifiedHelpView: true,
26789             category: ts.Diagnostics.Basic_Options,
26790             description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
26791             transpileOptionValue: undefined
26792         },
26793         {
26794             name: "emitDeclarationOnly",
26795             type: "boolean",
26796             affectsEmit: true,
26797             category: ts.Diagnostics.Advanced_Options,
26798             description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
26799             transpileOptionValue: undefined
26800         },
26801         {
26802             name: "sourceMap",
26803             type: "boolean",
26804             affectsEmit: true,
26805             showInSimplifiedHelpView: true,
26806             category: ts.Diagnostics.Basic_Options,
26807             description: ts.Diagnostics.Generates_corresponding_map_file,
26808         },
26809         {
26810             name: "outFile",
26811             type: "string",
26812             affectsEmit: true,
26813             isFilePath: true,
26814             paramType: ts.Diagnostics.FILE,
26815             showInSimplifiedHelpView: true,
26816             category: ts.Diagnostics.Basic_Options,
26817             description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
26818             transpileOptionValue: undefined
26819         },
26820         {
26821             name: "outDir",
26822             type: "string",
26823             affectsEmit: true,
26824             isFilePath: true,
26825             paramType: ts.Diagnostics.DIRECTORY,
26826             showInSimplifiedHelpView: true,
26827             category: ts.Diagnostics.Basic_Options,
26828             description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
26829         },
26830         {
26831             name: "rootDir",
26832             type: "string",
26833             affectsEmit: true,
26834             isFilePath: true,
26835             paramType: ts.Diagnostics.LOCATION,
26836             category: ts.Diagnostics.Basic_Options,
26837             description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
26838         },
26839         {
26840             name: "composite",
26841             type: "boolean",
26842             affectsEmit: true,
26843             isTSConfigOnly: true,
26844             category: ts.Diagnostics.Basic_Options,
26845             description: ts.Diagnostics.Enable_project_compilation,
26846             transpileOptionValue: undefined
26847         },
26848         {
26849             name: "tsBuildInfoFile",
26850             type: "string",
26851             affectsEmit: true,
26852             isFilePath: true,
26853             paramType: ts.Diagnostics.FILE,
26854             category: ts.Diagnostics.Basic_Options,
26855             description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
26856             transpileOptionValue: undefined
26857         },
26858         {
26859             name: "removeComments",
26860             type: "boolean",
26861             affectsEmit: true,
26862             showInSimplifiedHelpView: true,
26863             category: ts.Diagnostics.Basic_Options,
26864             description: ts.Diagnostics.Do_not_emit_comments_to_output,
26865         },
26866         {
26867             name: "noEmit",
26868             type: "boolean",
26869             affectsEmit: true,
26870             showInSimplifiedHelpView: true,
26871             category: ts.Diagnostics.Basic_Options,
26872             description: ts.Diagnostics.Do_not_emit_outputs,
26873             transpileOptionValue: undefined
26874         },
26875         {
26876             name: "importHelpers",
26877             type: "boolean",
26878             affectsEmit: true,
26879             category: ts.Diagnostics.Basic_Options,
26880             description: ts.Diagnostics.Import_emit_helpers_from_tslib
26881         },
26882         {
26883             name: "importsNotUsedAsValues",
26884             type: ts.createMapFromTemplate({
26885                 remove: 0 /* Remove */,
26886                 preserve: 1 /* Preserve */,
26887                 error: 2 /* Error */
26888             }),
26889             affectsEmit: true,
26890             affectsSemanticDiagnostics: true,
26891             category: ts.Diagnostics.Advanced_Options,
26892             description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
26893         },
26894         {
26895             name: "downlevelIteration",
26896             type: "boolean",
26897             affectsEmit: true,
26898             category: ts.Diagnostics.Basic_Options,
26899             description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
26900         },
26901         {
26902             name: "isolatedModules",
26903             type: "boolean",
26904             category: ts.Diagnostics.Basic_Options,
26905             description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
26906             transpileOptionValue: true
26907         },
26908         // Strict Type Checks
26909         {
26910             name: "strict",
26911             type: "boolean",
26912             showInSimplifiedHelpView: true,
26913             category: ts.Diagnostics.Strict_Type_Checking_Options,
26914             description: ts.Diagnostics.Enable_all_strict_type_checking_options
26915         },
26916         {
26917             name: "noImplicitAny",
26918             type: "boolean",
26919             affectsSemanticDiagnostics: true,
26920             strictFlag: true,
26921             showInSimplifiedHelpView: true,
26922             category: ts.Diagnostics.Strict_Type_Checking_Options,
26923             description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
26924         },
26925         {
26926             name: "strictNullChecks",
26927             type: "boolean",
26928             affectsSemanticDiagnostics: true,
26929             strictFlag: true,
26930             showInSimplifiedHelpView: true,
26931             category: ts.Diagnostics.Strict_Type_Checking_Options,
26932             description: ts.Diagnostics.Enable_strict_null_checks
26933         },
26934         {
26935             name: "strictFunctionTypes",
26936             type: "boolean",
26937             affectsSemanticDiagnostics: true,
26938             strictFlag: true,
26939             showInSimplifiedHelpView: true,
26940             category: ts.Diagnostics.Strict_Type_Checking_Options,
26941             description: ts.Diagnostics.Enable_strict_checking_of_function_types
26942         },
26943         {
26944             name: "strictBindCallApply",
26945             type: "boolean",
26946             strictFlag: true,
26947             showInSimplifiedHelpView: true,
26948             category: ts.Diagnostics.Strict_Type_Checking_Options,
26949             description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
26950         },
26951         {
26952             name: "strictPropertyInitialization",
26953             type: "boolean",
26954             affectsSemanticDiagnostics: true,
26955             strictFlag: true,
26956             showInSimplifiedHelpView: true,
26957             category: ts.Diagnostics.Strict_Type_Checking_Options,
26958             description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
26959         },
26960         {
26961             name: "noImplicitThis",
26962             type: "boolean",
26963             affectsSemanticDiagnostics: true,
26964             strictFlag: true,
26965             showInSimplifiedHelpView: true,
26966             category: ts.Diagnostics.Strict_Type_Checking_Options,
26967             description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
26968         },
26969         {
26970             name: "alwaysStrict",
26971             type: "boolean",
26972             affectsSourceFile: true,
26973             strictFlag: true,
26974             showInSimplifiedHelpView: true,
26975             category: ts.Diagnostics.Strict_Type_Checking_Options,
26976             description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
26977         },
26978         // Additional Checks
26979         {
26980             name: "noUnusedLocals",
26981             type: "boolean",
26982             affectsSemanticDiagnostics: true,
26983             showInSimplifiedHelpView: true,
26984             category: ts.Diagnostics.Additional_Checks,
26985             description: ts.Diagnostics.Report_errors_on_unused_locals,
26986         },
26987         {
26988             name: "noUnusedParameters",
26989             type: "boolean",
26990             affectsSemanticDiagnostics: true,
26991             showInSimplifiedHelpView: true,
26992             category: ts.Diagnostics.Additional_Checks,
26993             description: ts.Diagnostics.Report_errors_on_unused_parameters,
26994         },
26995         {
26996             name: "noImplicitReturns",
26997             type: "boolean",
26998             affectsSemanticDiagnostics: true,
26999             showInSimplifiedHelpView: true,
27000             category: ts.Diagnostics.Additional_Checks,
27001             description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
27002         },
27003         {
27004             name: "noFallthroughCasesInSwitch",
27005             type: "boolean",
27006             affectsBindDiagnostics: true,
27007             affectsSemanticDiagnostics: true,
27008             showInSimplifiedHelpView: true,
27009             category: ts.Diagnostics.Additional_Checks,
27010             description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
27011         },
27012         // Module Resolution
27013         {
27014             name: "moduleResolution",
27015             type: ts.createMapFromTemplate({
27016                 node: ts.ModuleResolutionKind.NodeJs,
27017                 classic: ts.ModuleResolutionKind.Classic,
27018             }),
27019             affectsModuleResolution: true,
27020             paramType: ts.Diagnostics.STRATEGY,
27021             category: ts.Diagnostics.Module_Resolution_Options,
27022             description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
27023         },
27024         {
27025             name: "baseUrl",
27026             type: "string",
27027             affectsModuleResolution: true,
27028             isFilePath: true,
27029             category: ts.Diagnostics.Module_Resolution_Options,
27030             description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
27031         },
27032         {
27033             // this option can only be specified in tsconfig.json
27034             // use type = object to copy the value as-is
27035             name: "paths",
27036             type: "object",
27037             affectsModuleResolution: true,
27038             isTSConfigOnly: true,
27039             category: ts.Diagnostics.Module_Resolution_Options,
27040             description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
27041             transpileOptionValue: undefined
27042         },
27043         {
27044             // this option can only be specified in tsconfig.json
27045             // use type = object to copy the value as-is
27046             name: "rootDirs",
27047             type: "list",
27048             isTSConfigOnly: true,
27049             element: {
27050                 name: "rootDirs",
27051                 type: "string",
27052                 isFilePath: true
27053             },
27054             affectsModuleResolution: true,
27055             category: ts.Diagnostics.Module_Resolution_Options,
27056             description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
27057             transpileOptionValue: undefined
27058         },
27059         {
27060             name: "typeRoots",
27061             type: "list",
27062             element: {
27063                 name: "typeRoots",
27064                 type: "string",
27065                 isFilePath: true
27066             },
27067             affectsModuleResolution: true,
27068             category: ts.Diagnostics.Module_Resolution_Options,
27069             description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
27070         },
27071         {
27072             name: "types",
27073             type: "list",
27074             element: {
27075                 name: "types",
27076                 type: "string"
27077             },
27078             affectsModuleResolution: true,
27079             showInSimplifiedHelpView: true,
27080             category: ts.Diagnostics.Module_Resolution_Options,
27081             description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
27082             transpileOptionValue: undefined
27083         },
27084         {
27085             name: "allowSyntheticDefaultImports",
27086             type: "boolean",
27087             affectsSemanticDiagnostics: true,
27088             category: ts.Diagnostics.Module_Resolution_Options,
27089             description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
27090         },
27091         {
27092             name: "esModuleInterop",
27093             type: "boolean",
27094             affectsSemanticDiagnostics: true,
27095             affectsEmit: true,
27096             showInSimplifiedHelpView: true,
27097             category: ts.Diagnostics.Module_Resolution_Options,
27098             description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
27099         },
27100         {
27101             name: "preserveSymlinks",
27102             type: "boolean",
27103             category: ts.Diagnostics.Module_Resolution_Options,
27104             description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
27105         },
27106         {
27107             name: "allowUmdGlobalAccess",
27108             type: "boolean",
27109             affectsSemanticDiagnostics: true,
27110             category: ts.Diagnostics.Module_Resolution_Options,
27111             description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
27112         },
27113         // Source Maps
27114         {
27115             name: "sourceRoot",
27116             type: "string",
27117             affectsEmit: true,
27118             paramType: ts.Diagnostics.LOCATION,
27119             category: ts.Diagnostics.Source_Map_Options,
27120             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
27121         },
27122         {
27123             name: "mapRoot",
27124             type: "string",
27125             affectsEmit: true,
27126             paramType: ts.Diagnostics.LOCATION,
27127             category: ts.Diagnostics.Source_Map_Options,
27128             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
27129         },
27130         {
27131             name: "inlineSourceMap",
27132             type: "boolean",
27133             affectsEmit: true,
27134             category: ts.Diagnostics.Source_Map_Options,
27135             description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
27136         },
27137         {
27138             name: "inlineSources",
27139             type: "boolean",
27140             affectsEmit: true,
27141             category: ts.Diagnostics.Source_Map_Options,
27142             description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
27143         },
27144         // Experimental
27145         {
27146             name: "experimentalDecorators",
27147             type: "boolean",
27148             affectsSemanticDiagnostics: true,
27149             category: ts.Diagnostics.Experimental_Options,
27150             description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
27151         },
27152         {
27153             name: "emitDecoratorMetadata",
27154             type: "boolean",
27155             affectsSemanticDiagnostics: true,
27156             affectsEmit: true,
27157             category: ts.Diagnostics.Experimental_Options,
27158             description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
27159         },
27160         // Advanced
27161         {
27162             name: "jsxFactory",
27163             type: "string",
27164             category: ts.Diagnostics.Advanced_Options,
27165             description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
27166         },
27167         {
27168             name: "resolveJsonModule",
27169             type: "boolean",
27170             affectsModuleResolution: true,
27171             category: ts.Diagnostics.Advanced_Options,
27172             description: ts.Diagnostics.Include_modules_imported_with_json_extension
27173         },
27174         {
27175             name: "out",
27176             type: "string",
27177             affectsEmit: true,
27178             isFilePath: false,
27179             // for correct behaviour, please use outFile
27180             category: ts.Diagnostics.Advanced_Options,
27181             paramType: ts.Diagnostics.FILE,
27182             description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
27183             transpileOptionValue: undefined
27184         },
27185         {
27186             name: "reactNamespace",
27187             type: "string",
27188             affectsEmit: true,
27189             category: ts.Diagnostics.Advanced_Options,
27190             description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
27191         },
27192         {
27193             name: "skipDefaultLibCheck",
27194             type: "boolean",
27195             category: ts.Diagnostics.Advanced_Options,
27196             description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
27197         },
27198         {
27199             name: "charset",
27200             type: "string",
27201             category: ts.Diagnostics.Advanced_Options,
27202             description: ts.Diagnostics.The_character_set_of_the_input_files
27203         },
27204         {
27205             name: "emitBOM",
27206             type: "boolean",
27207             affectsEmit: true,
27208             category: ts.Diagnostics.Advanced_Options,
27209             description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
27210         },
27211         {
27212             name: "newLine",
27213             type: ts.createMapFromTemplate({
27214                 crlf: 0 /* CarriageReturnLineFeed */,
27215                 lf: 1 /* LineFeed */
27216             }),
27217             affectsEmit: true,
27218             paramType: ts.Diagnostics.NEWLINE,
27219             category: ts.Diagnostics.Advanced_Options,
27220             description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
27221         },
27222         {
27223             name: "noErrorTruncation",
27224             type: "boolean",
27225             affectsSemanticDiagnostics: true,
27226             category: ts.Diagnostics.Advanced_Options,
27227             description: ts.Diagnostics.Do_not_truncate_error_messages
27228         },
27229         {
27230             name: "noLib",
27231             type: "boolean",
27232             affectsModuleResolution: true,
27233             category: ts.Diagnostics.Advanced_Options,
27234             description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
27235             // We are not returning a sourceFile for lib file when asked by the program,
27236             // so pass --noLib to avoid reporting a file not found error.
27237             transpileOptionValue: true
27238         },
27239         {
27240             name: "noResolve",
27241             type: "boolean",
27242             affectsModuleResolution: true,
27243             category: ts.Diagnostics.Advanced_Options,
27244             description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
27245             // We are not doing a full typecheck, we are not resolving the whole context,
27246             // so pass --noResolve to avoid reporting missing file errors.
27247             transpileOptionValue: true
27248         },
27249         {
27250             name: "stripInternal",
27251             type: "boolean",
27252             affectsEmit: true,
27253             category: ts.Diagnostics.Advanced_Options,
27254             description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
27255         },
27256         {
27257             name: "disableSizeLimit",
27258             type: "boolean",
27259             affectsSourceFile: true,
27260             category: ts.Diagnostics.Advanced_Options,
27261             description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
27262         },
27263         {
27264             name: "disableSourceOfProjectReferenceRedirect",
27265             type: "boolean",
27266             isTSConfigOnly: true,
27267             category: ts.Diagnostics.Advanced_Options,
27268             description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
27269         },
27270         {
27271             name: "disableSolutionSearching",
27272             type: "boolean",
27273             isTSConfigOnly: true,
27274             category: ts.Diagnostics.Advanced_Options,
27275             description: ts.Diagnostics.Disable_solution_searching_for_this_project
27276         },
27277         {
27278             name: "noImplicitUseStrict",
27279             type: "boolean",
27280             affectsSemanticDiagnostics: true,
27281             category: ts.Diagnostics.Advanced_Options,
27282             description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
27283         },
27284         {
27285             name: "noEmitHelpers",
27286             type: "boolean",
27287             affectsEmit: true,
27288             category: ts.Diagnostics.Advanced_Options,
27289             description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
27290         },
27291         {
27292             name: "noEmitOnError",
27293             type: "boolean",
27294             affectsEmit: true,
27295             category: ts.Diagnostics.Advanced_Options,
27296             description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
27297             transpileOptionValue: undefined
27298         },
27299         {
27300             name: "preserveConstEnums",
27301             type: "boolean",
27302             affectsEmit: true,
27303             category: ts.Diagnostics.Advanced_Options,
27304             description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
27305         },
27306         {
27307             name: "declarationDir",
27308             type: "string",
27309             affectsEmit: true,
27310             isFilePath: true,
27311             paramType: ts.Diagnostics.DIRECTORY,
27312             category: ts.Diagnostics.Advanced_Options,
27313             description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
27314             transpileOptionValue: undefined
27315         },
27316         {
27317             name: "skipLibCheck",
27318             type: "boolean",
27319             category: ts.Diagnostics.Advanced_Options,
27320             description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
27321         },
27322         {
27323             name: "allowUnusedLabels",
27324             type: "boolean",
27325             affectsBindDiagnostics: true,
27326             affectsSemanticDiagnostics: true,
27327             category: ts.Diagnostics.Advanced_Options,
27328             description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
27329         },
27330         {
27331             name: "allowUnreachableCode",
27332             type: "boolean",
27333             affectsBindDiagnostics: true,
27334             affectsSemanticDiagnostics: true,
27335             category: ts.Diagnostics.Advanced_Options,
27336             description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
27337         },
27338         {
27339             name: "suppressExcessPropertyErrors",
27340             type: "boolean",
27341             affectsSemanticDiagnostics: true,
27342             category: ts.Diagnostics.Advanced_Options,
27343             description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
27344         },
27345         {
27346             name: "suppressImplicitAnyIndexErrors",
27347             type: "boolean",
27348             affectsSemanticDiagnostics: true,
27349             category: ts.Diagnostics.Advanced_Options,
27350             description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
27351         },
27352         {
27353             name: "forceConsistentCasingInFileNames",
27354             type: "boolean",
27355             affectsModuleResolution: true,
27356             category: ts.Diagnostics.Advanced_Options,
27357             description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
27358         },
27359         {
27360             name: "maxNodeModuleJsDepth",
27361             type: "number",
27362             affectsModuleResolution: true,
27363             category: ts.Diagnostics.Advanced_Options,
27364             description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
27365         },
27366         {
27367             name: "noStrictGenericChecks",
27368             type: "boolean",
27369             affectsSemanticDiagnostics: true,
27370             category: ts.Diagnostics.Advanced_Options,
27371             description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
27372         },
27373         {
27374             name: "useDefineForClassFields",
27375             type: "boolean",
27376             affectsSemanticDiagnostics: true,
27377             affectsEmit: true,
27378             category: ts.Diagnostics.Advanced_Options,
27379             description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
27380         },
27381         {
27382             name: "keyofStringsOnly",
27383             type: "boolean",
27384             category: ts.Diagnostics.Advanced_Options,
27385             description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
27386         },
27387         {
27388             // A list of plugins to load in the language service
27389             name: "plugins",
27390             type: "list",
27391             isTSConfigOnly: true,
27392             element: {
27393                 name: "plugin",
27394                 type: "object"
27395             },
27396             description: ts.Diagnostics.List_of_language_service_plugins
27397         },
27398     ]);
27399     /* @internal */
27400     ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
27401     /* @internal */
27402     ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
27403     /* @internal */
27404     ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
27405     /* @internal */
27406     ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
27407         return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
27408     });
27409     /* @internal */
27410     ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
27411         return ts.hasProperty(option, "transpileOptionValue");
27412     });
27413     /* @internal */
27414     ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
27415         {
27416             name: "verbose",
27417             shortName: "v",
27418             category: ts.Diagnostics.Command_line_Options,
27419             description: ts.Diagnostics.Enable_verbose_logging,
27420             type: "boolean"
27421         },
27422         {
27423             name: "dry",
27424             shortName: "d",
27425             category: ts.Diagnostics.Command_line_Options,
27426             description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
27427             type: "boolean"
27428         },
27429         {
27430             name: "force",
27431             shortName: "f",
27432             category: ts.Diagnostics.Command_line_Options,
27433             description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
27434             type: "boolean"
27435         },
27436         {
27437             name: "clean",
27438             category: ts.Diagnostics.Command_line_Options,
27439             description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
27440             type: "boolean"
27441         }
27442     ]);
27443     /* @internal */
27444     ts.typeAcquisitionDeclarations = [
27445         {
27446             /* @deprecated typingOptions.enableAutoDiscovery
27447              * Use typeAcquisition.enable instead.
27448              */
27449             name: "enableAutoDiscovery",
27450             type: "boolean",
27451         },
27452         {
27453             name: "enable",
27454             type: "boolean",
27455         },
27456         {
27457             name: "include",
27458             type: "list",
27459             element: {
27460                 name: "include",
27461                 type: "string"
27462             }
27463         },
27464         {
27465             name: "exclude",
27466             type: "list",
27467             element: {
27468                 name: "exclude",
27469                 type: "string"
27470             }
27471         }
27472     ];
27473     /*@internal*/
27474     function createOptionNameMap(optionDeclarations) {
27475         var optionsNameMap = ts.createMap();
27476         var shortOptionNames = ts.createMap();
27477         ts.forEach(optionDeclarations, function (option) {
27478             optionsNameMap.set(option.name.toLowerCase(), option);
27479             if (option.shortName) {
27480                 shortOptionNames.set(option.shortName, option.name);
27481             }
27482         });
27483         return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
27484     }
27485     ts.createOptionNameMap = createOptionNameMap;
27486     var optionsNameMapCache;
27487     /* @internal */
27488     function getOptionsNameMap() {
27489         return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
27490     }
27491     ts.getOptionsNameMap = getOptionsNameMap;
27492     /* @internal */
27493     ts.defaultInitCompilerOptions = {
27494         module: ts.ModuleKind.CommonJS,
27495         target: 1 /* ES5 */,
27496         strict: true,
27497         esModuleInterop: true,
27498         forceConsistentCasingInFileNames: true,
27499         skipLibCheck: true
27500     };
27501     /* @internal */
27502     function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
27503         // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
27504         if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
27505             return {
27506                 enable: typeAcquisition.enableAutoDiscovery,
27507                 include: typeAcquisition.include || [],
27508                 exclude: typeAcquisition.exclude || []
27509             };
27510         }
27511         return typeAcquisition;
27512     }
27513     ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
27514     /* @internal */
27515     function createCompilerDiagnosticForInvalidCustomType(opt) {
27516         return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
27517     }
27518     ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
27519     function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
27520         var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
27521         return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
27522     }
27523     /* @internal */
27524     function parseCustomTypeOption(opt, value, errors) {
27525         return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
27526     }
27527     ts.parseCustomTypeOption = parseCustomTypeOption;
27528     /* @internal */
27529     function parseListTypeOption(opt, value, errors) {
27530         if (value === void 0) { value = ""; }
27531         value = trimString(value);
27532         if (ts.startsWith(value, "-")) {
27533             return undefined;
27534         }
27535         if (value === "") {
27536             return [];
27537         }
27538         var values = value.split(",");
27539         switch (opt.element.type) {
27540             case "number":
27541                 return ts.map(values, parseInt);
27542             case "string":
27543                 return ts.map(values, function (v) { return v || ""; });
27544             default:
27545                 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
27546         }
27547     }
27548     ts.parseListTypeOption = parseListTypeOption;
27549     function getOptionName(option) {
27550         return option.name;
27551     }
27552     function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
27553         var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
27554         return possibleOption ?
27555             createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
27556             createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
27557     }
27558     /*@internal*/
27559     function parseCommandLineWorker(diagnostics, commandLine, readFile) {
27560         var options = {};
27561         var watchOptions;
27562         var fileNames = [];
27563         var errors = [];
27564         parseStrings(commandLine);
27565         return {
27566             options: options,
27567             watchOptions: watchOptions,
27568             fileNames: fileNames,
27569             errors: errors
27570         };
27571         function parseStrings(args) {
27572             var i = 0;
27573             while (i < args.length) {
27574                 var s = args[i];
27575                 i++;
27576                 if (s.charCodeAt(0) === 64 /* at */) {
27577                     parseResponseFile(s.slice(1));
27578                 }
27579                 else if (s.charCodeAt(0) === 45 /* minus */) {
27580                     var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
27581                     var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27582                     if (opt) {
27583                         i = parseOptionValue(args, i, diagnostics, opt, options, errors);
27584                     }
27585                     else {
27586                         var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27587                         if (watchOpt) {
27588                             i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
27589                         }
27590                         else {
27591                             errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
27592                         }
27593                     }
27594                 }
27595                 else {
27596                     fileNames.push(s);
27597                 }
27598             }
27599         }
27600         function parseResponseFile(fileName) {
27601             var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
27602             if (!ts.isString(text)) {
27603                 errors.push(text);
27604                 return;
27605             }
27606             var args = [];
27607             var pos = 0;
27608             while (true) {
27609                 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
27610                     pos++;
27611                 if (pos >= text.length)
27612                     break;
27613                 var start = pos;
27614                 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
27615                     pos++;
27616                     while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
27617                         pos++;
27618                     if (pos < text.length) {
27619                         args.push(text.substring(start + 1, pos));
27620                         pos++;
27621                     }
27622                     else {
27623                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
27624                     }
27625                 }
27626                 else {
27627                     while (text.charCodeAt(pos) > 32 /* space */)
27628                         pos++;
27629                     args.push(text.substring(start, pos));
27630                 }
27631             }
27632             parseStrings(args);
27633         }
27634     }
27635     ts.parseCommandLineWorker = parseCommandLineWorker;
27636     function parseOptionValue(args, i, diagnostics, opt, options, errors) {
27637         if (opt.isTSConfigOnly) {
27638             var optValue = args[i];
27639             if (optValue === "null") {
27640                 options[opt.name] = undefined;
27641                 i++;
27642             }
27643             else if (opt.type === "boolean") {
27644                 if (optValue === "false") {
27645                     options[opt.name] = false;
27646                     i++;
27647                 }
27648                 else {
27649                     if (optValue === "true")
27650                         i++;
27651                     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));
27652                 }
27653             }
27654             else {
27655                 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));
27656                 if (optValue && !ts.startsWith(optValue, "-"))
27657                     i++;
27658             }
27659         }
27660         else {
27661             // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
27662             if (!args[i] && opt.type !== "boolean") {
27663                 errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
27664             }
27665             if (args[i] !== "null") {
27666                 switch (opt.type) {
27667                     case "number":
27668                         options[opt.name] = parseInt(args[i]);
27669                         i++;
27670                         break;
27671                     case "boolean":
27672                         // boolean flag has optional value true, false, others
27673                         var optValue = args[i];
27674                         options[opt.name] = optValue !== "false";
27675                         // consume next argument as boolean flag value
27676                         if (optValue === "false" || optValue === "true") {
27677                             i++;
27678                         }
27679                         break;
27680                     case "string":
27681                         options[opt.name] = args[i] || "";
27682                         i++;
27683                         break;
27684                     case "list":
27685                         var result = parseListTypeOption(opt, args[i], errors);
27686                         options[opt.name] = result || [];
27687                         if (result) {
27688                             i++;
27689                         }
27690                         break;
27691                     // If not a primitive, the possible types are specified in what is effectively a map of options.
27692                     default:
27693                         options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
27694                         i++;
27695                         break;
27696                 }
27697             }
27698             else {
27699                 options[opt.name] = undefined;
27700                 i++;
27701             }
27702         }
27703         return i;
27704     }
27705     /*@internal*/
27706     ts.compilerOptionsDidYouMeanDiagnostics = {
27707         getOptionsNameMap: getOptionsNameMap,
27708         optionDeclarations: ts.optionDeclarations,
27709         unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
27710         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
27711         optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
27712     };
27713     function parseCommandLine(commandLine, readFile) {
27714         return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
27715     }
27716     ts.parseCommandLine = parseCommandLine;
27717     /** @internal */
27718     function getOptionFromName(optionName, allowShort) {
27719         return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
27720     }
27721     ts.getOptionFromName = getOptionFromName;
27722     function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
27723         if (allowShort === void 0) { allowShort = false; }
27724         optionName = optionName.toLowerCase();
27725         var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
27726         // Try to translate short option names to their full equivalents.
27727         if (allowShort) {
27728             var short = shortOptionNames.get(optionName);
27729             if (short !== undefined) {
27730                 optionName = short;
27731             }
27732         }
27733         return optionsNameMap.get(optionName);
27734     }
27735     var buildOptionsNameMapCache;
27736     function getBuildOptionsNameMap() {
27737         return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
27738     }
27739     var buildOptionsDidYouMeanDiagnostics = {
27740         getOptionsNameMap: getBuildOptionsNameMap,
27741         optionDeclarations: ts.buildOpts,
27742         unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
27743         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
27744         optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
27745     };
27746     /*@internal*/
27747     function parseBuildCommand(args) {
27748         var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
27749         var buildOptions = options;
27750         if (projects.length === 0) {
27751             // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
27752             projects.push(".");
27753         }
27754         // Nonsensical combinations
27755         if (buildOptions.clean && buildOptions.force) {
27756             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
27757         }
27758         if (buildOptions.clean && buildOptions.verbose) {
27759             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
27760         }
27761         if (buildOptions.clean && buildOptions.watch) {
27762             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
27763         }
27764         if (buildOptions.watch && buildOptions.dry) {
27765             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
27766         }
27767         return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
27768     }
27769     ts.parseBuildCommand = parseBuildCommand;
27770     /* @internal */
27771     function getDiagnosticText(_message) {
27772         var _args = [];
27773         for (var _i = 1; _i < arguments.length; _i++) {
27774             _args[_i - 1] = arguments[_i];
27775         }
27776         var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
27777         return diagnostic.messageText;
27778     }
27779     ts.getDiagnosticText = getDiagnosticText;
27780     /**
27781      * Reads the config file, reports errors if any and exits if the config file cannot be found
27782      */
27783     function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
27784         var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
27785         if (!ts.isString(configFileText)) {
27786             host.onUnRecoverableConfigFileDiagnostic(configFileText);
27787             return undefined;
27788         }
27789         var result = ts.parseJsonText(configFileName, configFileText);
27790         var cwd = host.getCurrentDirectory();
27791         result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
27792         result.resolvedPath = result.path;
27793         result.originalFileName = result.fileName;
27794         return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), 
27795         /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
27796     }
27797     ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
27798     /**
27799      * Read tsconfig.json file
27800      * @param fileName The path to the config file
27801      */
27802     function readConfigFile(fileName, readFile) {
27803         var textOrDiagnostic = tryReadFile(fileName, readFile);
27804         return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
27805     }
27806     ts.readConfigFile = readConfigFile;
27807     /**
27808      * Parse the text of the tsconfig.json file
27809      * @param fileName The path to the config file
27810      * @param jsonText The text of the config file
27811      */
27812     function parseConfigFileTextToJson(fileName, jsonText) {
27813         var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
27814         return {
27815             config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
27816             error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
27817         };
27818     }
27819     ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
27820     /**
27821      * Read tsconfig.json file
27822      * @param fileName The path to the config file
27823      */
27824     function readJsonConfigFile(fileName, readFile) {
27825         var textOrDiagnostic = tryReadFile(fileName, readFile);
27826         return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] };
27827     }
27828     ts.readJsonConfigFile = readJsonConfigFile;
27829     /*@internal*/
27830     function tryReadFile(fileName, readFile) {
27831         var text;
27832         try {
27833             text = readFile(fileName);
27834         }
27835         catch (e) {
27836             return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
27837         }
27838         return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
27839     }
27840     ts.tryReadFile = tryReadFile;
27841     function commandLineOptionsToMap(options) {
27842         return ts.arrayToMap(options, getOptionName);
27843     }
27844     var typeAcquisitionDidYouMeanDiagnostics = {
27845         optionDeclarations: ts.typeAcquisitionDeclarations,
27846         unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
27847         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
27848     };
27849     var watchOptionsNameMapCache;
27850     function getWatchOptionsNameMap() {
27851         return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
27852     }
27853     var watchOptionsDidYouMeanDiagnostics = {
27854         getOptionsNameMap: getWatchOptionsNameMap,
27855         optionDeclarations: ts.optionsForWatch,
27856         unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
27857         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
27858         optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
27859     };
27860     var commandLineCompilerOptionsMapCache;
27861     function getCommandLineCompilerOptionsMap() {
27862         return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
27863     }
27864     var commandLineWatchOptionsMapCache;
27865     function getCommandLineWatchOptionsMap() {
27866         return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
27867     }
27868     var commandLineTypeAcquisitionMapCache;
27869     function getCommandLineTypeAcquisitionMap() {
27870         return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
27871     }
27872     var _tsconfigRootOptions;
27873     function getTsconfigRootOptionsMap() {
27874         if (_tsconfigRootOptions === undefined) {
27875             _tsconfigRootOptions = {
27876                 name: undefined,
27877                 type: "object",
27878                 elementOptions: commandLineOptionsToMap([
27879                     {
27880                         name: "compilerOptions",
27881                         type: "object",
27882                         elementOptions: getCommandLineCompilerOptionsMap(),
27883                         extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
27884                     },
27885                     {
27886                         name: "watchOptions",
27887                         type: "object",
27888                         elementOptions: getCommandLineWatchOptionsMap(),
27889                         extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
27890                     },
27891                     {
27892                         name: "typingOptions",
27893                         type: "object",
27894                         elementOptions: getCommandLineTypeAcquisitionMap(),
27895                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
27896                     },
27897                     {
27898                         name: "typeAcquisition",
27899                         type: "object",
27900                         elementOptions: getCommandLineTypeAcquisitionMap(),
27901                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
27902                     },
27903                     {
27904                         name: "extends",
27905                         type: "string"
27906                     },
27907                     {
27908                         name: "references",
27909                         type: "list",
27910                         element: {
27911                             name: "references",
27912                             type: "object"
27913                         }
27914                     },
27915                     {
27916                         name: "files",
27917                         type: "list",
27918                         element: {
27919                             name: "files",
27920                             type: "string"
27921                         }
27922                     },
27923                     {
27924                         name: "include",
27925                         type: "list",
27926                         element: {
27927                             name: "include",
27928                             type: "string"
27929                         }
27930                     },
27931                     {
27932                         name: "exclude",
27933                         type: "list",
27934                         element: {
27935                             name: "exclude",
27936                             type: "string"
27937                         }
27938                     },
27939                     ts.compileOnSaveCommandLineOption
27940                 ])
27941             };
27942         }
27943         return _tsconfigRootOptions;
27944     }
27945     /**
27946      * Convert the json syntax tree into the json value
27947      */
27948     function convertToObject(sourceFile, errors) {
27949         return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
27950     }
27951     ts.convertToObject = convertToObject;
27952     /**
27953      * Convert the json syntax tree into the json value and report errors
27954      * This returns the json value (apart from checking errors) only if returnValue provided is true.
27955      * Otherwise it just checks the errors and returns undefined
27956      */
27957     /*@internal*/
27958     function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
27959         if (!sourceFile.statements.length) {
27960             return returnValue ? {} : undefined;
27961         }
27962         return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
27963         function isRootOptionMap(knownOptions) {
27964             return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
27965         }
27966         function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
27967             var result = returnValue ? {} : undefined;
27968             var _loop_3 = function (element) {
27969                 if (element.kind !== 281 /* PropertyAssignment */) {
27970                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
27971                     return "continue";
27972                 }
27973                 if (element.questionToken) {
27974                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
27975                 }
27976                 if (!isDoubleQuotedString(element.name)) {
27977                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
27978                 }
27979                 var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
27980                 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
27981                 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
27982                 if (keyText && extraKeyDiagnostics && !option) {
27983                     if (knownOptions) {
27984                         errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
27985                     }
27986                     else {
27987                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
27988                     }
27989                 }
27990                 var value = convertPropertyValueToJson(element.initializer, option);
27991                 if (typeof keyText !== "undefined") {
27992                     if (returnValue) {
27993                         result[keyText] = value;
27994                     }
27995                     // Notify key value set, if user asked for it
27996                     if (jsonConversionNotifier &&
27997                         // Current callbacks are only on known parent option or if we are setting values in the root
27998                         (parentOption || isRootOptionMap(knownOptions))) {
27999                         var isValidOptionValue = isCompilerOptionsValue(option, value);
28000                         if (parentOption) {
28001                             if (isValidOptionValue) {
28002                                 // Notify option set in the parent if its a valid option value
28003                                 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
28004                             }
28005                         }
28006                         else if (isRootOptionMap(knownOptions)) {
28007                             if (isValidOptionValue) {
28008                                 // Notify about the valid root key value being set
28009                                 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28010                             }
28011                             else if (!option) {
28012                                 // Notify about the unknown root key value being set
28013                                 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28014                             }
28015                         }
28016                     }
28017                 }
28018             };
28019             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
28020                 var element = _a[_i];
28021                 _loop_3(element);
28022             }
28023             return result;
28024         }
28025         function convertArrayLiteralExpressionToJson(elements, elementOption) {
28026             if (!returnValue) {
28027                 return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
28028             }
28029             // Filter out invalid values
28030             return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
28031         }
28032         function convertPropertyValueToJson(valueExpression, option) {
28033             switch (valueExpression.kind) {
28034                 case 106 /* TrueKeyword */:
28035                     reportInvalidOptionValue(option && option.type !== "boolean");
28036                     return true;
28037                 case 91 /* FalseKeyword */:
28038                     reportInvalidOptionValue(option && option.type !== "boolean");
28039                     return false;
28040                 case 100 /* NullKeyword */:
28041                     reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
28042                     return null; // eslint-disable-line no-null/no-null
28043                 case 10 /* StringLiteral */:
28044                     if (!isDoubleQuotedString(valueExpression)) {
28045                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
28046                     }
28047                     reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
28048                     var text = valueExpression.text;
28049                     if (option && !ts.isString(option.type)) {
28050                         var customOption = option;
28051                         // Validate custom option type
28052                         if (!customOption.type.has(text.toLowerCase())) {
28053                             errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
28054                         }
28055                     }
28056                     return text;
28057                 case 8 /* NumericLiteral */:
28058                     reportInvalidOptionValue(option && option.type !== "number");
28059                     return Number(valueExpression.text);
28060                 case 207 /* PrefixUnaryExpression */:
28061                     if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
28062                         break; // not valid JSON syntax
28063                     }
28064                     reportInvalidOptionValue(option && option.type !== "number");
28065                     return -Number(valueExpression.operand.text);
28066                 case 193 /* ObjectLiteralExpression */:
28067                     reportInvalidOptionValue(option && option.type !== "object");
28068                     var objectLiteralExpression = valueExpression;
28069                     // Currently having element option declaration in the tsconfig with type "object"
28070                     // determines if it needs onSetValidOptionKeyValueInParent callback or not
28071                     // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
28072                     // that satifies it and need it to modify options set in them (for normalizing file paths)
28073                     // vs what we set in the json
28074                     // If need arises, we can modify this interface and callbacks as needed
28075                     if (option) {
28076                         var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
28077                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
28078                     }
28079                     else {
28080                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, 
28081                         /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
28082                     }
28083                 case 192 /* ArrayLiteralExpression */:
28084                     reportInvalidOptionValue(option && option.type !== "list");
28085                     return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
28086             }
28087             // Not in expected format
28088             if (option) {
28089                 reportInvalidOptionValue(/*isError*/ true);
28090             }
28091             else {
28092                 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));
28093             }
28094             return undefined;
28095             function reportInvalidOptionValue(isError) {
28096                 if (isError) {
28097                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
28098                 }
28099             }
28100         }
28101         function isDoubleQuotedString(node) {
28102             return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
28103         }
28104     }
28105     ts.convertToObjectWorker = convertToObjectWorker;
28106     function getCompilerOptionValueTypeString(option) {
28107         return option.type === "list" ?
28108             "Array" :
28109             ts.isString(option.type) ? option.type : "string";
28110     }
28111     function isCompilerOptionsValue(option, value) {
28112         if (option) {
28113             if (isNullOrUndefined(value))
28114                 return true; // All options are undefinable/nullable
28115             if (option.type === "list") {
28116                 return ts.isArray(value);
28117             }
28118             var expectedType = ts.isString(option.type) ? option.type : "string";
28119             return typeof value === expectedType;
28120         }
28121         return false;
28122     }
28123     /**
28124      * Generate an uncommented, complete tsconfig for use with "--showConfig"
28125      * @param configParseResult options to be generated into tsconfig.json
28126      * @param configFileName name of the parsed config file - output paths will be generated relative to this
28127      * @param host provides current directory and case sensitivity services
28128      */
28129     /** @internal */
28130     function convertToTSConfig(configParseResult, configFileName, host) {
28131         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
28132         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); });
28133         var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
28134         var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
28135         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 ? {
28136             include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
28137             exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
28138         } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
28139         return config;
28140     }
28141     ts.convertToTSConfig = convertToTSConfig;
28142     function optionMapToObject(optionMap) {
28143         return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
28144             var _a;
28145             return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
28146         }, {}));
28147     }
28148     function filterSameAsDefaultInclude(specs) {
28149         if (!ts.length(specs))
28150             return undefined;
28151         if (ts.length(specs) !== 1)
28152             return specs;
28153         if (specs[0] === "**/*")
28154             return undefined;
28155         return specs;
28156     }
28157     function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
28158         if (!includeSpecs)
28159             return function (_) { return true; };
28160         var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
28161         var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
28162         var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
28163         if (includeRe) {
28164             if (excludeRe) {
28165                 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
28166             }
28167             return function (path) { return !includeRe.test(path); };
28168         }
28169         if (excludeRe) {
28170             return function (path) { return excludeRe.test(path); };
28171         }
28172         return function (_) { return true; };
28173     }
28174     function getCustomTypeMapOfCommandLineOption(optionDefinition) {
28175         if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
28176             // this is of a type CommandLineOptionOfPrimitiveType
28177             return undefined;
28178         }
28179         else if (optionDefinition.type === "list") {
28180             return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
28181         }
28182         else {
28183             return optionDefinition.type;
28184         }
28185     }
28186     function getNameOfCompilerOptionValue(value, customTypeMap) {
28187         // There is a typeMap associated with this command-line option so use it to map value back to its name
28188         return ts.forEachEntry(customTypeMap, function (mapValue, key) {
28189             if (mapValue === value) {
28190                 return key;
28191             }
28192         });
28193     }
28194     function serializeCompilerOptions(options, pathOptions) {
28195         return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
28196     }
28197     function serializeWatchOptions(options) {
28198         return serializeOptionBaseObject(options, getWatchOptionsNameMap());
28199     }
28200     function serializeOptionBaseObject(options, _a, pathOptions) {
28201         var optionsNameMap = _a.optionsNameMap;
28202         var result = ts.createMap();
28203         var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
28204         var _loop_4 = function (name) {
28205             if (ts.hasProperty(options, name)) {
28206                 // tsconfig only options cannot be specified via command line,
28207                 // so we can assume that only types that can appear here string | number | boolean
28208                 if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
28209                     return "continue";
28210                 }
28211                 var value = options[name];
28212                 var optionDefinition = optionsNameMap.get(name.toLowerCase());
28213                 if (optionDefinition) {
28214                     var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
28215                     if (!customTypeMap_1) {
28216                         // There is no map associated with this compiler option then use the value as-is
28217                         // This is the case if the value is expect to be string, number, boolean or list of string
28218                         if (pathOptions && optionDefinition.isFilePath) {
28219                             result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
28220                         }
28221                         else {
28222                             result.set(name, value);
28223                         }
28224                     }
28225                     else {
28226                         if (optionDefinition.type === "list") {
28227                             result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
28228                         }
28229                         else {
28230                             // There is a typeMap associated with this command-line option so use it to map value back to its name
28231                             result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
28232                         }
28233                     }
28234                 }
28235             }
28236         };
28237         for (var name in options) {
28238             _loop_4(name);
28239         }
28240         return result;
28241     }
28242     /**
28243      * Generate tsconfig configuration when running command line "--init"
28244      * @param options commandlineOptions to be generated into tsconfig.json
28245      * @param fileNames array of filenames to be generated into tsconfig.json
28246      */
28247     /* @internal */
28248     function generateTSConfig(options, fileNames, newLine) {
28249         var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
28250         var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
28251         return writeConfigurations();
28252         function getDefaultValueForOption(option) {
28253             switch (option.type) {
28254                 case "number":
28255                     return 1;
28256                 case "boolean":
28257                     return true;
28258                 case "string":
28259                     return option.isFilePath ? "./" : "";
28260                 case "list":
28261                     return [];
28262                 case "object":
28263                     return {};
28264                 default:
28265                     var iterResult = option.type.keys().next();
28266                     if (!iterResult.done)
28267                         return iterResult.value;
28268                     return ts.Debug.fail("Expected 'option.type' to have entries.");
28269             }
28270         }
28271         function makePadding(paddingLength) {
28272             return Array(paddingLength + 1).join(" ");
28273         }
28274         function isAllowedOption(_a) {
28275             var category = _a.category, name = _a.name;
28276             // Skip options which do not have a category or have category `Command_line_Options`
28277             // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
28278             return category !== undefined
28279                 && category !== ts.Diagnostics.Command_line_Options
28280                 && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
28281         }
28282         function writeConfigurations() {
28283             // Filter applicable options to place in the file
28284             var categorizedOptions = ts.createMultiMap();
28285             for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
28286                 var option = optionDeclarations_1[_i];
28287                 var category = option.category;
28288                 if (isAllowedOption(option)) {
28289                     categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
28290                 }
28291             }
28292             // Serialize all options and their descriptions
28293             var marginLength = 0;
28294             var seenKnownKeys = 0;
28295             var entries = [];
28296             categorizedOptions.forEach(function (options, category) {
28297                 if (entries.length !== 0) {
28298                     entries.push({ value: "" });
28299                 }
28300                 entries.push({ value: "/* " + category + " */" });
28301                 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
28302                     var option = options_1[_i];
28303                     var optionName = void 0;
28304                     if (compilerOptionsMap.has(option.name)) {
28305                         optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
28306                     }
28307                     else {
28308                         optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
28309                     }
28310                     entries.push({
28311                         value: optionName,
28312                         description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"
28313                     });
28314                     marginLength = Math.max(optionName.length, marginLength);
28315                 }
28316             });
28317             // Write the output
28318             var tab = makePadding(2);
28319             var result = [];
28320             result.push("{");
28321             result.push(tab + "\"compilerOptions\": {");
28322             result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */");
28323             result.push("");
28324             // Print out each row, aligning all the descriptions on the same column.
28325             for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) {
28326                 var entry = entries_3[_a];
28327                 var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
28328                 result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description)));
28329             }
28330             if (fileNames.length) {
28331                 result.push(tab + "},");
28332                 result.push(tab + "\"files\": [");
28333                 for (var i = 0; i < fileNames.length; i++) {
28334                     result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
28335                 }
28336                 result.push(tab + "]");
28337             }
28338             else {
28339                 result.push(tab + "}");
28340             }
28341             result.push("}");
28342             return result.join(newLine) + newLine;
28343         }
28344     }
28345     ts.generateTSConfig = generateTSConfig;
28346     /* @internal */
28347     function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
28348         var result = {};
28349         var optionsNameMap = getOptionsNameMap().optionsNameMap;
28350         for (var name in options) {
28351             if (ts.hasProperty(options, name)) {
28352                 result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
28353             }
28354         }
28355         if (result.configFilePath) {
28356             result.configFilePath = toAbsolutePath(result.configFilePath);
28357         }
28358         return result;
28359     }
28360     ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
28361     function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
28362         if (option && !isNullOrUndefined(value)) {
28363             if (option.type === "list") {
28364                 var values = value;
28365                 if (option.element.isFilePath && values.length) {
28366                     return values.map(toAbsolutePath);
28367                 }
28368             }
28369             else if (option.isFilePath) {
28370                 return toAbsolutePath(value);
28371             }
28372         }
28373         return value;
28374     }
28375     /**
28376      * Parse the contents of a config file (tsconfig.json).
28377      * @param json The contents of the config file to parse
28378      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28379      * @param basePath A root directory to resolve relative path entries in the config
28380      *    file to. e.g. outDir
28381      */
28382     function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28383         return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28384     }
28385     ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
28386     /**
28387      * Parse the contents of a config file (tsconfig.json).
28388      * @param jsonNode The contents of the config file to parse
28389      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28390      * @param basePath A root directory to resolve relative path entries in the config
28391      *    file to. e.g. outDir
28392      */
28393     function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28394         return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28395     }
28396     ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
28397     /*@internal*/
28398     function setConfigFileInOptions(options, configFile) {
28399         if (configFile) {
28400             Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
28401         }
28402     }
28403     ts.setConfigFileInOptions = setConfigFileInOptions;
28404     function isNullOrUndefined(x) {
28405         return x === undefined || x === null; // eslint-disable-line no-null/no-null
28406     }
28407     function directoryOfCombinedPath(fileName, basePath) {
28408         // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
28409         // until consistent casing errors are reported
28410         return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
28411     }
28412     /**
28413      * Parse the contents of a config file from json or json source file (tsconfig.json).
28414      * @param json The contents of the config file to parse
28415      * @param sourceFile sourceFile corresponding to the Json
28416      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28417      * @param basePath A root directory to resolve relative path entries in the config
28418      *    file to. e.g. outDir
28419      * @param resolutionStack Only present for backwards-compatibility. Should be empty.
28420      */
28421     function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
28422         if (existingOptions === void 0) { existingOptions = {}; }
28423         if (resolutionStack === void 0) { resolutionStack = []; }
28424         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
28425         ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
28426         var errors = [];
28427         var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
28428         var raw = parsedConfig.raw;
28429         var options = ts.extend(existingOptions, parsedConfig.options || {});
28430         var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
28431             ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
28432             parsedConfig.watchOptions || existingWatchOptions;
28433         options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
28434         setConfigFileInOptions(options, sourceFile);
28435         var projectReferences;
28436         var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
28437         return {
28438             options: options,
28439             watchOptions: watchOptions,
28440             fileNames: fileNames,
28441             projectReferences: projectReferences,
28442             typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
28443             raw: raw,
28444             errors: errors,
28445             wildcardDirectories: wildcardDirectories,
28446             compileOnSave: !!raw.compileOnSave,
28447             configFileSpecs: spec
28448         };
28449         function getFileNames() {
28450             var filesSpecs;
28451             if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) {
28452                 if (ts.isArray(raw.files)) {
28453                     filesSpecs = raw.files;
28454                     var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references);
28455                     var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0;
28456                     var hasExtends = ts.hasProperty(raw, "extends");
28457                     if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
28458                         if (sourceFile) {
28459                             var fileName = configFileName || "tsconfig.json";
28460                             var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
28461                             var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
28462                             var error = nodeValue
28463                                 ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
28464                                 : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
28465                             errors.push(error);
28466                         }
28467                         else {
28468                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
28469                         }
28470                     }
28471                 }
28472                 else {
28473                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array");
28474                 }
28475             }
28476             var includeSpecs;
28477             if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) {
28478                 if (ts.isArray(raw.include)) {
28479                     includeSpecs = raw.include;
28480                 }
28481                 else {
28482                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array");
28483                 }
28484             }
28485             var excludeSpecs;
28486             if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) {
28487                 if (ts.isArray(raw.exclude)) {
28488                     excludeSpecs = raw.exclude;
28489                 }
28490                 else {
28491                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
28492                 }
28493             }
28494             else if (raw.compilerOptions) {
28495                 var outDir = raw.compilerOptions.outDir;
28496                 var declarationDir = raw.compilerOptions.declarationDir;
28497                 if (outDir || declarationDir) {
28498                     excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
28499                 }
28500             }
28501             if (filesSpecs === undefined && includeSpecs === undefined) {
28502                 includeSpecs = ["**/*"];
28503             }
28504             var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
28505             if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) {
28506                 errors.push(getErrorForNoInputFiles(result.spec, configFileName));
28507             }
28508             if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
28509                 if (ts.isArray(raw.references)) {
28510                     for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
28511                         var ref = _a[_i];
28512                         if (typeof ref.path !== "string") {
28513                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
28514                         }
28515                         else {
28516                             (projectReferences || (projectReferences = [])).push({
28517                                 path: ts.getNormalizedAbsolutePath(ref.path, basePath),
28518                                 originalPath: ref.path,
28519                                 prepend: ref.prepend,
28520                                 circular: ref.circular
28521                             });
28522                         }
28523                     }
28524                 }
28525                 else {
28526                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
28527                 }
28528             }
28529             return result;
28530         }
28531         function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
28532             if (!sourceFile) {
28533                 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
28534             }
28535         }
28536     }
28537     function isErrorNoInputFiles(error) {
28538         return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
28539     }
28540     function getErrorForNoInputFiles(_a, configFileName) {
28541         var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
28542         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 || []));
28543     }
28544     function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
28545         return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
28546     }
28547     /*@internal*/
28548     function canJsonReportNoInutFiles(raw) {
28549         return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
28550     }
28551     ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles;
28552     /*@internal*/
28553     function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
28554         var existingErrors = configParseDiagnostics.length;
28555         if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
28556             configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
28557         }
28558         else {
28559             ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
28560         }
28561         return existingErrors !== configParseDiagnostics.length;
28562     }
28563     ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
28564     function isSuccessfulParsedTsconfig(value) {
28565         return !!value.options;
28566     }
28567     /**
28568      * This *just* extracts options/include/exclude/files out of a config file.
28569      * It does *not* resolve the included files.
28570      */
28571     function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
28572         basePath = ts.normalizeSlashes(basePath);
28573         var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
28574         if (resolutionStack.indexOf(resolvedPath) >= 0) {
28575             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
28576             return { raw: json || convertToObject(sourceFile, errors) };
28577         }
28578         var ownConfig = json ?
28579             parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
28580             parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
28581         if (ownConfig.extendedConfigPath) {
28582             // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
28583             resolutionStack = resolutionStack.concat([resolvedPath]);
28584             var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache);
28585             if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
28586                 var baseRaw_1 = extendedConfig.raw;
28587                 var raw_1 = ownConfig.raw;
28588                 var setPropertyInRawIfNotUndefined = function (propertyName) {
28589                     var value = raw_1[propertyName] || baseRaw_1[propertyName];
28590                     if (value) {
28591                         raw_1[propertyName] = value;
28592                     }
28593                 };
28594                 setPropertyInRawIfNotUndefined("include");
28595                 setPropertyInRawIfNotUndefined("exclude");
28596                 setPropertyInRawIfNotUndefined("files");
28597                 if (raw_1.compileOnSave === undefined) {
28598                     raw_1.compileOnSave = baseRaw_1.compileOnSave;
28599                 }
28600                 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
28601                 ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
28602                     ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
28603                     ownConfig.watchOptions || extendedConfig.watchOptions;
28604                 // TODO extend type typeAcquisition
28605             }
28606         }
28607         return ownConfig;
28608     }
28609     function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
28610         if (ts.hasProperty(json, "excludes")) {
28611             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28612         }
28613         var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
28614         // typingOptions has been deprecated and is only supported for backward compatibility purposes.
28615         // It should be removed in future releases - use typeAcquisition instead.
28616         var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
28617         var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
28618         json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
28619         var extendedConfigPath;
28620         if (json.extends) {
28621             if (!ts.isString(json.extends)) {
28622                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
28623             }
28624             else {
28625                 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28626                 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
28627             }
28628         }
28629         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28630     }
28631     function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
28632         var options = getDefaultCompilerOptions(configFileName);
28633         var typeAcquisition, typingOptionstypeAcquisition;
28634         var watchOptions;
28635         var extendedConfigPath;
28636         var optionsIterator = {
28637             onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
28638                 var currentOption;
28639                 switch (parentOption) {
28640                     case "compilerOptions":
28641                         currentOption = options;
28642                         break;
28643                     case "watchOptions":
28644                         currentOption = (watchOptions || (watchOptions = {}));
28645                         break;
28646                     case "typeAcquisition":
28647                         currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
28648                         break;
28649                     case "typingOptions":
28650                         currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
28651                         break;
28652                     default:
28653                         ts.Debug.fail("Unknown option");
28654                 }
28655                 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
28656             },
28657             onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
28658                 switch (key) {
28659                     case "extends":
28660                         var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28661                         extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
28662                             return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
28663                         });
28664                         return;
28665                 }
28666             },
28667             onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
28668                 if (key === "excludes") {
28669                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28670                 }
28671             }
28672         };
28673         var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
28674         if (!typeAcquisition) {
28675             if (typingOptionstypeAcquisition) {
28676                 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
28677                     {
28678                         enable: typingOptionstypeAcquisition.enableAutoDiscovery,
28679                         include: typingOptionstypeAcquisition.include,
28680                         exclude: typingOptionstypeAcquisition.exclude
28681                     } :
28682                     typingOptionstypeAcquisition;
28683             }
28684             else {
28685                 typeAcquisition = getDefaultTypeAcquisition(configFileName);
28686             }
28687         }
28688         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28689     }
28690     function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
28691         extendedConfig = ts.normalizeSlashes(extendedConfig);
28692         if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
28693             var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
28694             if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
28695                 extendedConfigPath = extendedConfigPath + ".json";
28696                 if (!host.fileExists(extendedConfigPath)) {
28697                     errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28698                     return undefined;
28699                 }
28700             }
28701             return extendedConfigPath;
28702         }
28703         // If the path isn't a rooted or relative path, resolve like a module
28704         var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
28705         if (resolved.resolvedModule) {
28706             return resolved.resolvedModule.resolvedFileName;
28707         }
28708         errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28709         return undefined;
28710     }
28711     function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
28712         var _a;
28713         var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
28714         var value;
28715         var extendedResult;
28716         var extendedConfig;
28717         if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
28718             (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
28719         }
28720         else {
28721             extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
28722             if (!extendedResult.parseDiagnostics.length) {
28723                 var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
28724                 extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
28725                 if (isSuccessfulParsedTsconfig(extendedConfig)) {
28726                     // Update the paths to reflect base path
28727                     var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
28728                     var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
28729                     var mapPropertiesInRawIfNotUndefined = function (propertyName) {
28730                         if (raw_2[propertyName]) {
28731                             raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
28732                         }
28733                     };
28734                     var raw_2 = extendedConfig.raw;
28735                     mapPropertiesInRawIfNotUndefined("include");
28736                     mapPropertiesInRawIfNotUndefined("exclude");
28737                     mapPropertiesInRawIfNotUndefined("files");
28738                 }
28739             }
28740             if (extendedConfigCache) {
28741                 extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
28742             }
28743         }
28744         if (sourceFile) {
28745             sourceFile.extendedSourceFiles = [extendedResult.fileName];
28746             if (extendedResult.extendedSourceFiles) {
28747                 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
28748             }
28749         }
28750         if (extendedResult.parseDiagnostics.length) {
28751             errors.push.apply(errors, extendedResult.parseDiagnostics);
28752             return undefined;
28753         }
28754         return extendedConfig;
28755     }
28756     function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
28757         if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
28758             return false;
28759         }
28760         var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
28761         return typeof result === "boolean" && result;
28762     }
28763     function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
28764         var errors = [];
28765         var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28766         return { options: options, errors: errors };
28767     }
28768     ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
28769     function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
28770         var errors = [];
28771         var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28772         return { options: options, errors: errors };
28773     }
28774     ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
28775     function getDefaultCompilerOptions(configFileName) {
28776         var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
28777             ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
28778             : {};
28779         return options;
28780     }
28781     function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28782         var options = getDefaultCompilerOptions(configFileName);
28783         convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
28784         if (configFileName) {
28785             options.configFilePath = ts.normalizeSlashes(configFileName);
28786         }
28787         return options;
28788     }
28789     function getDefaultTypeAcquisition(configFileName) {
28790         return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
28791     }
28792     function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28793         var options = getDefaultTypeAcquisition(configFileName);
28794         var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
28795         convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
28796         return options;
28797     }
28798     function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
28799         return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
28800     }
28801     function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
28802         if (!jsonOptions) {
28803             return;
28804         }
28805         for (var id in jsonOptions) {
28806             var opt = optionsNameMap.get(id);
28807             if (opt) {
28808                 (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
28809             }
28810             else {
28811                 errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
28812             }
28813         }
28814         return defaultOptions;
28815     }
28816     function convertJsonOption(opt, value, basePath, errors) {
28817         if (isCompilerOptionsValue(opt, value)) {
28818             var optType = opt.type;
28819             if (optType === "list" && ts.isArray(value)) {
28820                 return convertJsonOptionOfListType(opt, value, basePath, errors);
28821             }
28822             else if (!ts.isString(optType)) {
28823                 return convertJsonOptionOfCustomType(opt, value, errors);
28824             }
28825             return normalizeNonListOptionValue(opt, basePath, value);
28826         }
28827         else {
28828             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
28829         }
28830     }
28831     function normalizeOptionValue(option, basePath, value) {
28832         if (isNullOrUndefined(value))
28833             return undefined;
28834         if (option.type === "list") {
28835             var listOption_1 = option;
28836             if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
28837                 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
28838             }
28839             return value;
28840         }
28841         else if (!ts.isString(option.type)) {
28842             return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
28843         }
28844         return normalizeNonListOptionValue(option, basePath, value);
28845     }
28846     function normalizeNonListOptionValue(option, basePath, value) {
28847         if (option.isFilePath) {
28848             value = ts.getNormalizedAbsolutePath(value, basePath);
28849             if (value === "") {
28850                 value = ".";
28851             }
28852         }
28853         return value;
28854     }
28855     function convertJsonOptionOfCustomType(opt, value, errors) {
28856         if (isNullOrUndefined(value))
28857             return undefined;
28858         var key = value.toLowerCase();
28859         var val = opt.type.get(key);
28860         if (val !== undefined) {
28861             return val;
28862         }
28863         else {
28864             errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
28865         }
28866     }
28867     function convertJsonOptionOfListType(option, values, basePath, errors) {
28868         return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
28869     }
28870     function trimString(s) {
28871         return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
28872     }
28873     /**
28874      * Tests for a path that ends in a recursive directory wildcard.
28875      * Matches **, \**, **\, and \**\, but not a**b.
28876      *
28877      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28878      *
28879      * Breakdown:
28880      *  (^|\/)      # matches either the beginning of the string or a directory separator.
28881      *  \*\*        # matches the recursive directory wildcard "**".
28882      *  \/?$        # matches an optional trailing directory separator at the end of the string.
28883      */
28884     var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
28885     /**
28886      * Tests for a path where .. appears after a recursive directory wildcard.
28887      * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
28888      *
28889      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28890      *
28891      * Breakdown:
28892      *  (^|\/)      # matches either the beginning of the string or a directory separator.
28893      *  \*\*\/      # matches a recursive directory wildcard "**" followed by a directory separator.
28894      *  (.*\/)?     # optionally matches any number of characters followed by a directory separator.
28895      *  \.\.        # matches a parent directory path component ".."
28896      *  ($|\/)      # matches either the end of the string or a directory separator.
28897      */
28898     var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
28899     /**
28900      * Tests for a path containing a wildcard character in a directory component of the path.
28901      * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
28902      *
28903      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28904      *
28905      * Breakdown:
28906      *  \/          # matches a directory separator.
28907      *  [^/]*?      # matches any number of characters excluding directory separators (non-greedy).
28908      *  [*?]        # matches either a wildcard character (* or ?)
28909      *  [^/]*       # matches any number of characters excluding directory separators (greedy).
28910      *  \/          # matches a directory separator.
28911      */
28912     var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
28913     /**
28914      * Matches the portion of a wildcard path that does not contain wildcards.
28915      * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
28916      *
28917      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28918      *
28919      * Breakdown:
28920      *  ^                   # matches the beginning of the string
28921      *  [^*?]*              # matches any number of non-wildcard characters
28922      *  (?=\/[^/]*[*?])     # lookahead that matches a directory separator followed by
28923      *                      # a path component that contains at least one wildcard character (* or ?).
28924      */
28925     var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
28926     /**
28927      * Expands an array of file specifications.
28928      *
28929      * @param filesSpecs The literal file names to include.
28930      * @param includeSpecs The wildcard file specifications to include.
28931      * @param excludeSpecs The wildcard file specifications to exclude.
28932      * @param basePath The base path for any relative file specifications.
28933      * @param options Compiler options.
28934      * @param host The host used to resolve files and directories.
28935      * @param errors An array for diagnostic reporting.
28936      */
28937     function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
28938         basePath = ts.normalizePath(basePath);
28939         var validatedIncludeSpecs, validatedExcludeSpecs;
28940         // The exclude spec list is converted into a regular expression, which allows us to quickly
28941         // test whether a file or directory should be excluded before recursively traversing the
28942         // file system.
28943         if (includeSpecs) {
28944             validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
28945         }
28946         if (excludeSpecs) {
28947             validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
28948         }
28949         // Wildcard directories (provided as part of a wildcard path) are stored in a
28950         // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
28951         // or a recursive directory. This information is used by filesystem watchers to monitor for
28952         // new entries in these paths.
28953         var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
28954         var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
28955         return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
28956     }
28957     /**
28958      * Gets the file names from the provided config file specs that contain, files, include, exclude and
28959      * other properties needed to resolve the file names
28960      * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
28961      * @param basePath The base path for any relative file specifications.
28962      * @param options Compiler options.
28963      * @param host The host used to resolve files and directories.
28964      * @param extraFileExtensions optionaly file extra file extension information from host
28965      */
28966     /* @internal */
28967     function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
28968         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
28969         basePath = ts.normalizePath(basePath);
28970         var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
28971         // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
28972         // file map with a possibly case insensitive key. We use this map later when when including
28973         // wildcard paths.
28974         var literalFileMap = ts.createMap();
28975         // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
28976         // file map with a possibly case insensitive key. We use this map to store paths matched
28977         // via wildcard, and to handle extension priority.
28978         var wildcardFileMap = ts.createMap();
28979         // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
28980         // file map with a possibly case insensitive key. We use this map to store paths matched
28981         // via wildcard of *.json kind
28982         var wildCardJsonFileMap = ts.createMap();
28983         var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
28984         // Rather than requery this for each file and filespec, we query the supported extensions
28985         // once and store it on the expansion context.
28986         var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
28987         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
28988         // Literal files are always included verbatim. An "include" or "exclude" specification cannot
28989         // remove a literal file.
28990         if (filesSpecs) {
28991             for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
28992                 var fileName = filesSpecs_1[_i];
28993                 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
28994                 literalFileMap.set(keyMapper(file), file);
28995             }
28996         }
28997         var jsonOnlyIncludeRegexes;
28998         if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
28999             var _loop_5 = function (file) {
29000                 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
29001                     // Valid only if *.json specified
29002                     if (!jsonOnlyIncludeRegexes) {
29003                         var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
29004                         var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
29005                         jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
29006                     }
29007                     var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
29008                     if (includeIndex !== -1) {
29009                         var key_1 = keyMapper(file);
29010                         if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
29011                             wildCardJsonFileMap.set(key_1, file);
29012                         }
29013                     }
29014                     return "continue";
29015                 }
29016                 // If we have already included a literal or wildcard path with a
29017                 // higher priority extension, we should skip this file.
29018                 //
29019                 // This handles cases where we may encounter both <file>.ts and
29020                 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
29021                 // directory when they are compilation outputs.
29022                 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
29023                     return "continue";
29024                 }
29025                 // We may have included a wildcard path with a lower priority
29026                 // extension due to the user-defined order of entries in the
29027                 // "include" array. If there is a lower priority extension in the
29028                 // same directory, we should remove it.
29029                 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
29030                 var key = keyMapper(file);
29031                 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
29032                     wildcardFileMap.set(key, file);
29033                 }
29034             };
29035             for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
29036                 var file = _b[_a];
29037                 _loop_5(file);
29038             }
29039         }
29040         var literalFiles = ts.arrayFrom(literalFileMap.values());
29041         var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
29042         return {
29043             fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
29044             wildcardDirectories: wildcardDirectories,
29045             spec: spec
29046         };
29047     }
29048     ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
29049     function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
29050         return specs.filter(function (spec) {
29051             var diag = specToDiagnostic(spec, allowTrailingRecursion);
29052             if (diag !== undefined) {
29053                 errors.push(createDiagnostic(diag, spec));
29054             }
29055             return diag === undefined;
29056         });
29057         function createDiagnostic(message, spec) {
29058             var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
29059             return element ?
29060                 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
29061                 ts.createCompilerDiagnostic(message, spec);
29062         }
29063     }
29064     function specToDiagnostic(spec, allowTrailingRecursion) {
29065         if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
29066             return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29067         }
29068         else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
29069             return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29070         }
29071     }
29072     /**
29073      * Gets directories in a set of include patterns that should be watched for changes.
29074      */
29075     function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
29076         // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
29077         // of the pattern:
29078         //
29079         //  /a/b/**/d   - Watch /a/b recursively to catch changes to any d in any subfolder recursively
29080         //  /a/b/*/d    - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
29081         //  /a/b        - Watch /a/b recursively to catch changes to anything in any recursive subfoler
29082         //
29083         // We watch a directory without recursion if it contains a wildcard in the file segment of
29084         // the pattern:
29085         //
29086         //  /a/b/*      - Watch /a/b directly to catch any new file
29087         //  /a/b/a?z    - Watch /a/b directly to catch any new file matching a?z
29088         var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
29089         var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
29090         var wildcardDirectories = {};
29091         if (include !== undefined) {
29092             var recursiveKeys = [];
29093             for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
29094                 var file = include_1[_i];
29095                 var spec = ts.normalizePath(ts.combinePaths(path, file));
29096                 if (excludeRegex && excludeRegex.test(spec)) {
29097                     continue;
29098                 }
29099                 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
29100                 if (match) {
29101                     var key = match.key, flags = match.flags;
29102                     var existingFlags = wildcardDirectories[key];
29103                     if (existingFlags === undefined || existingFlags < flags) {
29104                         wildcardDirectories[key] = flags;
29105                         if (flags === 1 /* Recursive */) {
29106                             recursiveKeys.push(key);
29107                         }
29108                     }
29109                 }
29110             }
29111             // Remove any subpaths under an existing recursively watched directory.
29112             for (var key in wildcardDirectories) {
29113                 if (ts.hasProperty(wildcardDirectories, key)) {
29114                     for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
29115                         var recursiveKey = recursiveKeys_1[_a];
29116                         if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
29117                             delete wildcardDirectories[key];
29118                         }
29119                     }
29120                 }
29121             }
29122         }
29123         return wildcardDirectories;
29124     }
29125     function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
29126         var match = wildcardDirectoryPattern.exec(spec);
29127         if (match) {
29128             return {
29129                 key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
29130                 flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
29131             };
29132         }
29133         if (ts.isImplicitGlob(spec)) {
29134             return { key: spec, flags: 1 /* Recursive */ };
29135         }
29136         return undefined;
29137     }
29138     /**
29139      * Determines whether a literal or wildcard file has already been included that has a higher
29140      * extension priority.
29141      *
29142      * @param file The path to the file.
29143      * @param extensionPriority The priority of the extension.
29144      * @param context The expansion context.
29145      */
29146     function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
29147         var extensionPriority = ts.getExtensionPriority(file, extensions);
29148         var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
29149         for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
29150             var higherPriorityExtension = extensions[i];
29151             var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
29152             if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
29153                 return true;
29154             }
29155         }
29156         return false;
29157     }
29158     /**
29159      * Removes files included via wildcard expansion with a lower extension priority that have
29160      * already been included.
29161      *
29162      * @param file The path to the file.
29163      * @param extensionPriority The priority of the extension.
29164      * @param context The expansion context.
29165      */
29166     function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
29167         var extensionPriority = ts.getExtensionPriority(file, extensions);
29168         var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
29169         for (var i = nextExtensionPriority; i < extensions.length; i++) {
29170             var lowerPriorityExtension = extensions[i];
29171             var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
29172             wildcardFiles.delete(lowerPriorityPath);
29173         }
29174     }
29175     /**
29176      * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
29177      * Also converts enum values back to strings.
29178      */
29179     /* @internal */
29180     function convertCompilerOptionsForTelemetry(opts) {
29181         var out = {};
29182         for (var key in opts) {
29183             if (opts.hasOwnProperty(key)) {
29184                 var type = getOptionFromName(key);
29185                 if (type !== undefined) { // Ignore unknown options
29186                     out[key] = getOptionValueWithEmptyStrings(opts[key], type);
29187                 }
29188             }
29189         }
29190         return out;
29191     }
29192     ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
29193     function getOptionValueWithEmptyStrings(value, option) {
29194         switch (option.type) {
29195             case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
29196                 return "";
29197             case "string": // Could be any arbitrary string -- use empty string instead.
29198                 return "";
29199             case "number": // Allow numbers, but be sure to check it's actually a number.
29200                 return typeof value === "number" ? value : "";
29201             case "boolean":
29202                 return typeof value === "boolean" ? value : "";
29203             case "list":
29204                 var elementType_1 = option.element;
29205                 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
29206             default:
29207                 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
29208                     if (optionEnumValue === value) {
29209                         return optionStringValue;
29210                     }
29211                 }); // TODO: GH#18217
29212         }
29213     }
29214 })(ts || (ts = {}));
29215 var ts;
29216 (function (ts) {
29217     function trace(host) {
29218         host.trace(ts.formatMessage.apply(undefined, arguments));
29219     }
29220     ts.trace = trace;
29221     /* @internal */
29222     function isTraceEnabled(compilerOptions, host) {
29223         return !!compilerOptions.traceResolution && host.trace !== undefined;
29224     }
29225     ts.isTraceEnabled = isTraceEnabled;
29226     function withPackageId(packageInfo, r) {
29227         var packageId;
29228         if (r && packageInfo) {
29229             var packageJsonContent = packageInfo.packageJsonContent;
29230             if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
29231                 packageId = {
29232                     name: packageJsonContent.name,
29233                     subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
29234                     version: packageJsonContent.version
29235                 };
29236             }
29237         }
29238         return r && { path: r.path, extension: r.ext, packageId: packageId };
29239     }
29240     function noPackageId(r) {
29241         return withPackageId(/*packageInfo*/ undefined, r);
29242     }
29243     function removeIgnoredPackageId(r) {
29244         if (r) {
29245             ts.Debug.assert(r.packageId === undefined);
29246             return { path: r.path, ext: r.extension };
29247         }
29248     }
29249     /**
29250      * Kinds of file that we are currently looking for.
29251      * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
29252      */
29253     var Extensions;
29254     (function (Extensions) {
29255         Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
29256         Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
29257         Extensions[Extensions["Json"] = 2] = "Json";
29258         Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
29259         Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
29260     })(Extensions || (Extensions = {}));
29261     /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
29262     function resolvedTypeScriptOnly(resolved) {
29263         if (!resolved) {
29264             return undefined;
29265         }
29266         ts.Debug.assert(ts.extensionIsTS(resolved.extension));
29267         return { fileName: resolved.path, packageId: resolved.packageId };
29268     }
29269     function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
29270         var _a;
29271         if (resultFromCache) {
29272             (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
29273             return resultFromCache;
29274         }
29275         return {
29276             resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
29277             failedLookupLocations: failedLookupLocations
29278         };
29279     }
29280     function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
29281         if (!ts.hasProperty(jsonContent, fieldName)) {
29282             if (state.traceEnabled) {
29283                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
29284             }
29285             return;
29286         }
29287         var value = jsonContent[fieldName];
29288         if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
29289             if (state.traceEnabled) {
29290                 // eslint-disable-next-line no-null/no-null
29291                 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);
29292             }
29293             return;
29294         }
29295         return value;
29296     }
29297     function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
29298         var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
29299         if (fileName === undefined) {
29300             return;
29301         }
29302         if (!fileName) {
29303             if (state.traceEnabled) {
29304                 trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
29305             }
29306             return;
29307         }
29308         var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
29309         if (state.traceEnabled) {
29310             trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
29311         }
29312         return path;
29313     }
29314     function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
29315         return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
29316             || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
29317     }
29318     function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
29319         return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
29320     }
29321     function readPackageJsonMainField(jsonContent, baseDirectory, state) {
29322         return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
29323     }
29324     function readPackageJsonTypesVersionsField(jsonContent, state) {
29325         var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
29326         if (typesVersions === undefined)
29327             return;
29328         if (state.traceEnabled) {
29329             trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
29330         }
29331         return typesVersions;
29332     }
29333     function readPackageJsonTypesVersionPaths(jsonContent, state) {
29334         var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
29335         if (typesVersions === undefined)
29336             return;
29337         if (state.traceEnabled) {
29338             for (var key in typesVersions) {
29339                 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
29340                     trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
29341                 }
29342             }
29343         }
29344         var result = getPackageJsonTypesVersionsPaths(typesVersions);
29345         if (!result) {
29346             if (state.traceEnabled) {
29347                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
29348             }
29349             return;
29350         }
29351         var bestVersionKey = result.version, bestVersionPaths = result.paths;
29352         if (typeof bestVersionPaths !== "object") {
29353             if (state.traceEnabled) {
29354                 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
29355             }
29356             return;
29357         }
29358         return result;
29359     }
29360     var typeScriptVersion;
29361     /* @internal */
29362     function getPackageJsonTypesVersionsPaths(typesVersions) {
29363         if (!typeScriptVersion)
29364             typeScriptVersion = new ts.Version(ts.version);
29365         for (var key in typesVersions) {
29366             if (!ts.hasProperty(typesVersions, key))
29367                 continue;
29368             var keyRange = ts.VersionRange.tryParse(key);
29369             if (keyRange === undefined) {
29370                 continue;
29371             }
29372             // return the first entry whose range matches the current compiler version.
29373             if (keyRange.test(typeScriptVersion)) {
29374                 return { version: key, paths: typesVersions[key] };
29375             }
29376         }
29377     }
29378     ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
29379     function getEffectiveTypeRoots(options, host) {
29380         if (options.typeRoots) {
29381             return options.typeRoots;
29382         }
29383         var currentDirectory;
29384         if (options.configFilePath) {
29385             currentDirectory = ts.getDirectoryPath(options.configFilePath);
29386         }
29387         else if (host.getCurrentDirectory) {
29388             currentDirectory = host.getCurrentDirectory();
29389         }
29390         if (currentDirectory !== undefined) {
29391             return getDefaultTypeRoots(currentDirectory, host);
29392         }
29393     }
29394     ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
29395     /**
29396      * Returns the path to every node_modules/@types directory from some ancestor directory.
29397      * Returns undefined if there are none.
29398      */
29399     function getDefaultTypeRoots(currentDirectory, host) {
29400         if (!host.directoryExists) {
29401             return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
29402             // And if it doesn't exist, tough.
29403         }
29404         var typeRoots;
29405         ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
29406             var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
29407             if (host.directoryExists(atTypes)) {
29408                 (typeRoots || (typeRoots = [])).push(atTypes);
29409             }
29410             return undefined;
29411         });
29412         return typeRoots;
29413     }
29414     var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
29415     /**
29416      * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
29417      * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
29418      * is assumed to be the same as root directory of the project.
29419      */
29420     function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
29421         var traceEnabled = isTraceEnabled(options, host);
29422         if (redirectedReference) {
29423             options = redirectedReference.commandLine.options;
29424         }
29425         var failedLookupLocations = [];
29426         var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
29427         var typeRoots = getEffectiveTypeRoots(options, host);
29428         if (traceEnabled) {
29429             if (containingFile === undefined) {
29430                 if (typeRoots === undefined) {
29431                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
29432                 }
29433                 else {
29434                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
29435                 }
29436             }
29437             else {
29438                 if (typeRoots === undefined) {
29439                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
29440                 }
29441                 else {
29442                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
29443                 }
29444             }
29445             if (redirectedReference) {
29446                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29447             }
29448         }
29449         var resolved = primaryLookup();
29450         var primary = true;
29451         if (!resolved) {
29452             resolved = secondaryLookup();
29453             primary = false;
29454         }
29455         var resolvedTypeReferenceDirective;
29456         if (resolved) {
29457             var fileName = resolved.fileName, packageId = resolved.packageId;
29458             var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
29459             if (traceEnabled) {
29460                 if (packageId) {
29461                     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);
29462                 }
29463                 else {
29464                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
29465                 }
29466             }
29467             resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
29468         }
29469         return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
29470         function primaryLookup() {
29471             // Check primary library paths
29472             if (typeRoots && typeRoots.length) {
29473                 if (traceEnabled) {
29474                     trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
29475                 }
29476                 return ts.firstDefined(typeRoots, function (typeRoot) {
29477                     var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
29478                     var candidateDirectory = ts.getDirectoryPath(candidate);
29479                     var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
29480                     if (!directoryExists && traceEnabled) {
29481                         trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
29482                     }
29483                     return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
29484                 });
29485             }
29486             else {
29487                 if (traceEnabled) {
29488                     trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
29489                 }
29490             }
29491         }
29492         function secondaryLookup() {
29493             var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
29494             if (initialLocationForSecondaryLookup !== undefined) {
29495                 // check secondary locations
29496                 if (traceEnabled) {
29497                     trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
29498                 }
29499                 var result = void 0;
29500                 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
29501                     var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
29502                     result = searchResult && searchResult.value;
29503                 }
29504                 else {
29505                     var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
29506                     result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
29507                 }
29508                 var resolvedFile = resolvedTypeScriptOnly(result);
29509                 if (!resolvedFile && traceEnabled) {
29510                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
29511                 }
29512                 return resolvedFile;
29513             }
29514             else {
29515                 if (traceEnabled) {
29516                     trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
29517                 }
29518             }
29519         }
29520     }
29521     ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
29522     /**
29523      * Given a set of options, returns the set of type directive names
29524      *   that should be included for this program automatically.
29525      * This list could either come from the config file,
29526      *   or from enumerating the types root + initial secondary types lookup location.
29527      * More type directives might appear in the program later as a result of loading actual source files;
29528      *   this list is only the set of defaults that are implicitly included.
29529      */
29530     function getAutomaticTypeDirectiveNames(options, host) {
29531         // Use explicit type list from tsconfig.json
29532         if (options.types) {
29533             return options.types;
29534         }
29535         // Walk the primary type lookup locations
29536         var result = [];
29537         if (host.directoryExists && host.getDirectories) {
29538             var typeRoots = getEffectiveTypeRoots(options, host);
29539             if (typeRoots) {
29540                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
29541                     var root = typeRoots_1[_i];
29542                     if (host.directoryExists(root)) {
29543                         for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
29544                             var typeDirectivePath = _b[_a];
29545                             var normalized = ts.normalizePath(typeDirectivePath);
29546                             var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
29547                             // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
29548                             // See `createNotNeededPackageJSON` in the types-publisher` repo.
29549                             // eslint-disable-next-line no-null/no-null
29550                             var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
29551                             if (!isNotNeededPackage) {
29552                                 var baseFileName = ts.getBaseFileName(normalized);
29553                                 // At this stage, skip results with leading dot.
29554                                 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
29555                                     // Return just the type directive names
29556                                     result.push(baseFileName);
29557                                 }
29558                             }
29559                         }
29560                     }
29561                 }
29562             }
29563         }
29564         return result;
29565     }
29566     ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
29567     function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
29568         return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
29569     }
29570     ts.createModuleResolutionCache = createModuleResolutionCache;
29571     /*@internal*/
29572     function createCacheWithRedirects(options) {
29573         var ownMap = ts.createMap();
29574         var redirectsMap = ts.createMap();
29575         return {
29576             ownMap: ownMap,
29577             redirectsMap: redirectsMap,
29578             getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
29579             clear: clear,
29580             setOwnOptions: setOwnOptions,
29581             setOwnMap: setOwnMap
29582         };
29583         function setOwnOptions(newOptions) {
29584             options = newOptions;
29585         }
29586         function setOwnMap(newOwnMap) {
29587             ownMap = newOwnMap;
29588         }
29589         function getOrCreateMapOfCacheRedirects(redirectedReference) {
29590             if (!redirectedReference) {
29591                 return ownMap;
29592             }
29593             var path = redirectedReference.sourceFile.path;
29594             var redirects = redirectsMap.get(path);
29595             if (!redirects) {
29596                 // Reuse map if redirected reference map uses same resolution
29597                 redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? ts.createMap() : ownMap;
29598                 redirectsMap.set(path, redirects);
29599             }
29600             return redirects;
29601         }
29602         function clear() {
29603             ownMap.clear();
29604             redirectsMap.clear();
29605         }
29606     }
29607     ts.createCacheWithRedirects = createCacheWithRedirects;
29608     /*@internal*/
29609     function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
29610         return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
29611         function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
29612             var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
29613             return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap);
29614         }
29615         function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
29616             ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
29617             return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
29618         }
29619         function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
29620             var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
29621             var result = cache.get(key);
29622             if (!result) {
29623                 result = create();
29624                 cache.set(key, result);
29625             }
29626             return result;
29627         }
29628         function createPerModuleNameCache() {
29629             var directoryPathMap = ts.createMap();
29630             return { get: get, set: set };
29631             function get(directory) {
29632                 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
29633             }
29634             /**
29635              * At first this function add entry directory -> module resolution result to the table.
29636              * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
29637              * and for every parent folder in set it adds entry: parent -> module resolution. .
29638              * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
29639              * Set of parent folders that should have the same result will be:
29640              * [
29641              *     /a/b/c/d, /a/b/c, /a/b
29642              * ]
29643              * this means that request for module resolution from file in any of these folder will be immediately found in cache.
29644              */
29645             function set(directory, result) {
29646                 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
29647                 // if entry is already in cache do nothing
29648                 if (directoryPathMap.has(path)) {
29649                     return;
29650                 }
29651                 directoryPathMap.set(path, result);
29652                 var resolvedFileName = result.resolvedModule &&
29653                     (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
29654                 // find common prefix between directory and resolved file name
29655                 // this common prefix should be the shortest path that has the same resolution
29656                 // directory: /a/b/c/d/e
29657                 // resolvedFileName: /a/b/foo.d.ts
29658                 // commonPrefix: /a/b
29659                 // for failed lookups cache the result for every directory up to root
29660                 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
29661                 var current = path;
29662                 while (current !== commonPrefix) {
29663                     var parent = ts.getDirectoryPath(current);
29664                     if (parent === current || directoryPathMap.has(parent)) {
29665                         break;
29666                     }
29667                     directoryPathMap.set(parent, result);
29668                     current = parent;
29669                 }
29670             }
29671             function getCommonPrefix(directory, resolution) {
29672                 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
29673                 // find first position where directory and resolution differs
29674                 var i = 0;
29675                 var limit = Math.min(directory.length, resolutionDirectory.length);
29676                 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
29677                     i++;
29678                 }
29679                 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
29680                     return directory;
29681                 }
29682                 var rootLength = ts.getRootLength(directory);
29683                 if (i < rootLength) {
29684                     return undefined;
29685                 }
29686                 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
29687                 if (sep === -1) {
29688                     return undefined;
29689                 }
29690                 return directory.substr(0, Math.max(sep, rootLength));
29691             }
29692         }
29693     }
29694     ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
29695     function resolveModuleNameFromCache(moduleName, containingFile, cache) {
29696         var containingDirectory = ts.getDirectoryPath(containingFile);
29697         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
29698         return perFolderCache && perFolderCache.get(moduleName);
29699     }
29700     ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
29701     function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
29702         var traceEnabled = isTraceEnabled(compilerOptions, host);
29703         if (redirectedReference) {
29704             compilerOptions = redirectedReference.commandLine.options;
29705         }
29706         if (traceEnabled) {
29707             trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
29708             if (redirectedReference) {
29709                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29710             }
29711         }
29712         var containingDirectory = ts.getDirectoryPath(containingFile);
29713         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
29714         var result = perFolderCache && perFolderCache.get(moduleName);
29715         if (result) {
29716             if (traceEnabled) {
29717                 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
29718             }
29719         }
29720         else {
29721             var moduleResolution = compilerOptions.moduleResolution;
29722             if (moduleResolution === undefined) {
29723                 moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
29724                 if (traceEnabled) {
29725                     trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
29726                 }
29727             }
29728             else {
29729                 if (traceEnabled) {
29730                     trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
29731                 }
29732             }
29733             ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
29734             switch (moduleResolution) {
29735                 case ts.ModuleResolutionKind.NodeJs:
29736                     result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29737                     break;
29738                 case ts.ModuleResolutionKind.Classic:
29739                     result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29740                     break;
29741                 default:
29742                     return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
29743             }
29744             if (result && result.resolvedModule)
29745                 ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
29746             ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
29747             if (perFolderCache) {
29748                 perFolderCache.set(moduleName, result);
29749                 if (!ts.isExternalModuleNameRelative(moduleName)) {
29750                     // put result in per-module name cache
29751                     cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
29752                 }
29753             }
29754         }
29755         if (traceEnabled) {
29756             if (result.resolvedModule) {
29757                 if (result.resolvedModule.packageId) {
29758                     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));
29759                 }
29760                 else {
29761                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
29762                 }
29763             }
29764             else {
29765                 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
29766             }
29767         }
29768         return result;
29769     }
29770     ts.resolveModuleName = resolveModuleName;
29771     /**
29772      * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
29773      * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
29774      * can be resolved successfully by TypeScript compiler and runtime module loader.
29775      * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
29776      * fallback to standard resolution routine.
29777      *
29778      * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
29779      * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
29780      * be '/a/b/c/d'
29781      * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
29782      * will be resolved based on the content of the module name.
29783      * Structure of 'paths' compiler options
29784      * 'paths': {
29785      *    pattern-1: [...substitutions],
29786      *    pattern-2: [...substitutions],
29787      *    ...
29788      *    pattern-n: [...substitutions]
29789      * }
29790      * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
29791      * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
29792      * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
29793      * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
29794      * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
29795      * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
29796      * from the candidate location.
29797      * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
29798      * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
29799      * will be converted to absolute using baseUrl.
29800      * For example:
29801      * baseUrl: /a/b/c
29802      * "paths": {
29803      *     // match all module names
29804      *     "*": [
29805      *         "*",        // use matched name as is,
29806      *                     // <matched name> will be looked as /a/b/c/<matched name>
29807      *
29808      *         "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
29809      *                     // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
29810      *     ],
29811      *     // match module names that start with 'components/'
29812      *     "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
29813      *                                              // it is rooted so it will be final candidate location
29814      * }
29815      *
29816      * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
29817      * they were in the same location. For example lets say there are two files
29818      * '/local/src/content/file1.ts'
29819      * '/shared/components/contracts/src/content/protocols/file2.ts'
29820      * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
29821      * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
29822      * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
29823      * root dirs were merged together.
29824      * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
29825      * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
29826      * '/local/src/content/protocols/file2' and try to load it - failure.
29827      * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
29828      * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
29829      * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
29830      */
29831     function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
29832         var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
29833         if (resolved)
29834             return resolved.value;
29835         if (!ts.isExternalModuleNameRelative(moduleName)) {
29836             return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
29837         }
29838         else {
29839             return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
29840         }
29841     }
29842     function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
29843         var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
29844         if (baseUrl && paths && !ts.pathIsRelative(moduleName)) {
29845             if (state.traceEnabled) {
29846                 trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
29847                 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
29848             }
29849             return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
29850         }
29851     }
29852     function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
29853         if (!state.compilerOptions.rootDirs) {
29854             return undefined;
29855         }
29856         if (state.traceEnabled) {
29857             trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
29858         }
29859         var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
29860         var matchedRootDir;
29861         var matchedNormalizedPrefix;
29862         for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
29863             var rootDir = _a[_i];
29864             // rootDirs are expected to be absolute
29865             // in case of tsconfig.json this will happen automatically - compiler will expand relative names
29866             // using location of tsconfig.json as base location
29867             var normalizedRoot = ts.normalizePath(rootDir);
29868             if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
29869                 normalizedRoot += ts.directorySeparator;
29870             }
29871             var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
29872                 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
29873             if (state.traceEnabled) {
29874                 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
29875             }
29876             if (isLongestMatchingPrefix) {
29877                 matchedNormalizedPrefix = normalizedRoot;
29878                 matchedRootDir = rootDir;
29879             }
29880         }
29881         if (matchedNormalizedPrefix) {
29882             if (state.traceEnabled) {
29883                 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
29884             }
29885             var suffix = candidate.substr(matchedNormalizedPrefix.length);
29886             // first - try to load from a initial location
29887             if (state.traceEnabled) {
29888                 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
29889             }
29890             var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
29891             if (resolvedFileName) {
29892                 return resolvedFileName;
29893             }
29894             if (state.traceEnabled) {
29895                 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
29896             }
29897             // then try to resolve using remaining entries in rootDirs
29898             for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
29899                 var rootDir = _c[_b];
29900                 if (rootDir === matchedRootDir) {
29901                     // skip the initially matched entry
29902                     continue;
29903                 }
29904                 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
29905                 if (state.traceEnabled) {
29906                     trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
29907                 }
29908                 var baseDirectory = ts.getDirectoryPath(candidate_1);
29909                 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
29910                 if (resolvedFileName_1) {
29911                     return resolvedFileName_1;
29912                 }
29913             }
29914             if (state.traceEnabled) {
29915                 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
29916             }
29917         }
29918         return undefined;
29919     }
29920     function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
29921         var baseUrl = state.compilerOptions.baseUrl;
29922         if (!baseUrl) {
29923             return undefined;
29924         }
29925         if (state.traceEnabled) {
29926             trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
29927         }
29928         var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
29929         if (state.traceEnabled) {
29930             trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
29931         }
29932         return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
29933     }
29934     /**
29935      * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
29936      * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
29937      * Throws an error if the module can't be resolved.
29938      */
29939     /* @internal */
29940     function resolveJSModule(moduleName, initialDir, host) {
29941         var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
29942         if (!resolvedModule) {
29943             throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
29944         }
29945         return resolvedModule.resolvedFileName;
29946     }
29947     ts.resolveJSModule = resolveJSModule;
29948     /* @internal */
29949     function tryResolveJSModule(moduleName, initialDir, host) {
29950         var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
29951         return resolvedModule && resolvedModule.resolvedFileName;
29952     }
29953     ts.tryResolveJSModule = tryResolveJSModule;
29954     var jsOnlyExtensions = [Extensions.JavaScript];
29955     var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
29956     var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
29957     var tsconfigExtensions = [Extensions.TSConfig];
29958     function tryResolveJSModuleWorker(moduleName, initialDir, host) {
29959         return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
29960     }
29961     function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
29962         return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
29963     }
29964     ts.nodeModuleNameResolver = nodeModuleNameResolver;
29965     function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
29966         var _a, _b;
29967         var traceEnabled = isTraceEnabled(compilerOptions, host);
29968         var failedLookupLocations = [];
29969         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
29970         var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
29971         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);
29972         function tryResolve(extensions) {
29973             var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
29974             var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
29975             if (resolved) {
29976                 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
29977             }
29978             if (!ts.isExternalModuleNameRelative(moduleName)) {
29979                 if (traceEnabled) {
29980                     trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
29981                 }
29982                 var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
29983                 if (!resolved_1)
29984                     return undefined;
29985                 var resolvedValue = resolved_1.value;
29986                 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
29987                     var path = realPath(resolvedValue.path, host, traceEnabled);
29988                     var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
29989                     resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
29990                 }
29991                 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
29992                 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
29993             }
29994             else {
29995                 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
29996                 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
29997                 // Treat explicit "node_modules" import as an external library import.
29998                 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
29999             }
30000         }
30001     }
30002     function realPath(path, host, traceEnabled) {
30003         if (!host.realpath) {
30004             return path;
30005         }
30006         var real = ts.normalizePath(host.realpath(path));
30007         if (traceEnabled) {
30008             trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
30009         }
30010         ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
30011         return real;
30012     }
30013     function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30014         if (state.traceEnabled) {
30015             trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
30016         }
30017         if (!ts.hasTrailingDirectorySeparator(candidate)) {
30018             if (!onlyRecordFailures) {
30019                 var parentOfCandidate = ts.getDirectoryPath(candidate);
30020                 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
30021                     if (state.traceEnabled) {
30022                         trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
30023                     }
30024                     onlyRecordFailures = true;
30025                 }
30026             }
30027             var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
30028             if (resolvedFromFile) {
30029                 var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
30030                 var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
30031                 return withPackageId(packageInfo, resolvedFromFile);
30032             }
30033         }
30034         if (!onlyRecordFailures) {
30035             var candidateExists = ts.directoryProbablyExists(candidate, state.host);
30036             if (!candidateExists) {
30037                 if (state.traceEnabled) {
30038                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
30039                 }
30040                 onlyRecordFailures = true;
30041             }
30042         }
30043         return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
30044     }
30045     /*@internal*/
30046     ts.nodeModulesPathPart = "/node_modules/";
30047     /*@internal*/
30048     function pathContainsNodeModules(path) {
30049         return ts.stringContains(path, ts.nodeModulesPathPart);
30050     }
30051     ts.pathContainsNodeModules = pathContainsNodeModules;
30052     /**
30053      * This will be called on the successfully resolved path from `loadModuleFromFile`.
30054      * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
30055      *
30056      * packageDirectory is the directory of the package itself.
30057      *   For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
30058      *   For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
30059      *   For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
30060      *   For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
30061      */
30062     function parseNodeModuleFromPath(resolved) {
30063         var path = ts.normalizePath(resolved.path);
30064         var idx = path.lastIndexOf(ts.nodeModulesPathPart);
30065         if (idx === -1) {
30066             return undefined;
30067         }
30068         var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
30069         var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
30070         if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
30071             indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
30072         }
30073         return path.slice(0, indexAfterPackageName);
30074     }
30075     function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
30076         var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
30077         return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
30078     }
30079     function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
30080         return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
30081     }
30082     /**
30083      * @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
30084      * 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.
30085      */
30086     function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
30087         if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
30088             var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
30089             return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
30090         }
30091         // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
30092         var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
30093         if (resolvedByAddingExtension) {
30094             return resolvedByAddingExtension;
30095         }
30096         // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
30097         // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
30098         if (ts.hasJSFileExtension(candidate)) {
30099             var extensionless = ts.removeFileExtension(candidate);
30100             if (state.traceEnabled) {
30101                 var extension = candidate.substring(extensionless.length);
30102                 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
30103             }
30104             return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
30105         }
30106     }
30107     /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
30108     function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
30109         if (!onlyRecordFailures) {
30110             // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
30111             var directory = ts.getDirectoryPath(candidate);
30112             if (directory) {
30113                 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
30114             }
30115         }
30116         switch (extensions) {
30117             case Extensions.DtsOnly:
30118                 return tryExtension(".d.ts" /* Dts */);
30119             case Extensions.TypeScript:
30120                 return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
30121             case Extensions.JavaScript:
30122                 return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
30123             case Extensions.TSConfig:
30124             case Extensions.Json:
30125                 return tryExtension(".json" /* Json */);
30126         }
30127         function tryExtension(ext) {
30128             var path = tryFile(candidate + ext, onlyRecordFailures, state);
30129             return path === undefined ? undefined : { path: path, ext: ext };
30130         }
30131     }
30132     /** Return the file if it exists. */
30133     function tryFile(fileName, onlyRecordFailures, state) {
30134         if (!onlyRecordFailures) {
30135             if (state.host.fileExists(fileName)) {
30136                 if (state.traceEnabled) {
30137                     trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
30138                 }
30139                 return fileName;
30140             }
30141             else {
30142                 if (state.traceEnabled) {
30143                     trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
30144                 }
30145             }
30146         }
30147         state.failedLookupLocations.push(fileName);
30148         return undefined;
30149     }
30150     function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30151         if (considerPackageJson === void 0) { considerPackageJson = true; }
30152         var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
30153         var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
30154         var versionPaths = packageInfo && packageInfo.versionPaths;
30155         return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
30156     }
30157     function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
30158         var host = state.host, traceEnabled = state.traceEnabled;
30159         var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
30160         var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
30161         if (directoryExists && host.fileExists(packageJsonPath)) {
30162             var packageJsonContent = ts.readJson(packageJsonPath, host);
30163             if (traceEnabled) {
30164                 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
30165             }
30166             var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
30167             return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
30168         }
30169         else {
30170             if (directoryExists && traceEnabled) {
30171                 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
30172             }
30173             // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
30174             state.failedLookupLocations.push(packageJsonPath);
30175         }
30176     }
30177     function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
30178         var packageFile;
30179         if (jsonContent) {
30180             switch (extensions) {
30181                 case Extensions.JavaScript:
30182                 case Extensions.Json:
30183                     packageFile = readPackageJsonMainField(jsonContent, candidate, state);
30184                     break;
30185                 case Extensions.TypeScript:
30186                     // When resolving typescript modules, try resolving using main field as well
30187                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
30188                     break;
30189                 case Extensions.DtsOnly:
30190                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
30191                     break;
30192                 case Extensions.TSConfig:
30193                     packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
30194                     break;
30195                 default:
30196                     return ts.Debug.assertNever(extensions);
30197             }
30198         }
30199         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30200             var fromFile = tryFile(candidate, onlyRecordFailures, state);
30201             if (fromFile) {
30202                 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
30203                 if (resolved) {
30204                     return noPackageId(resolved);
30205                 }
30206                 if (state.traceEnabled) {
30207                     trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
30208                 }
30209             }
30210             // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
30211             var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
30212             // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
30213             return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
30214         };
30215         var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
30216         var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
30217         var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
30218         if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
30219             var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
30220             if (state.traceEnabled) {
30221                 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);
30222             }
30223             var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
30224             if (result) {
30225                 return removeIgnoredPackageId(result.value);
30226             }
30227         }
30228         // It won't have a `packageId` set, because we disabled `considerPackageJson`.
30229         var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
30230         if (packageFileResult)
30231             return packageFileResult;
30232         return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
30233     }
30234     /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
30235     function resolvedIfExtensionMatches(extensions, path) {
30236         var ext = ts.tryGetExtensionFromPath(path);
30237         return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
30238     }
30239     /** True if `extension` is one of the supported `extensions`. */
30240     function extensionIsOk(extensions, extension) {
30241         switch (extensions) {
30242             case Extensions.JavaScript:
30243                 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
30244             case Extensions.TSConfig:
30245             case Extensions.Json:
30246                 return extension === ".json" /* Json */;
30247             case Extensions.TypeScript:
30248                 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
30249             case Extensions.DtsOnly:
30250                 return extension === ".d.ts" /* Dts */;
30251         }
30252     }
30253     /* @internal */
30254     function parsePackageName(moduleName) {
30255         var idx = moduleName.indexOf(ts.directorySeparator);
30256         if (moduleName[0] === "@") {
30257             idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
30258         }
30259         return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
30260     }
30261     ts.parsePackageName = parsePackageName;
30262     function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
30263         return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
30264     }
30265     function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
30266         // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
30267         return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
30268     }
30269     function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
30270         var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30271         return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
30272             if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
30273                 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
30274                 if (resolutionFromCache) {
30275                     return resolutionFromCache;
30276                 }
30277                 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
30278             }
30279         });
30280     }
30281     function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
30282         var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
30283         var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
30284         if (!nodeModulesFolderExists && state.traceEnabled) {
30285             trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
30286         }
30287         var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
30288         if (packageResult) {
30289             return packageResult;
30290         }
30291         if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
30292             var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
30293             var nodeModulesAtTypesExists = nodeModulesFolderExists;
30294             if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
30295                 if (state.traceEnabled) {
30296                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
30297                 }
30298                 nodeModulesAtTypesExists = false;
30299             }
30300             return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
30301         }
30302     }
30303     function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
30304         var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
30305         // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
30306         var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
30307         if (packageInfo) {
30308             var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
30309             if (fromFile) {
30310                 return noPackageId(fromFile);
30311             }
30312             var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
30313             return withPackageId(packageInfo, fromDirectory);
30314         }
30315         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30316             var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
30317                 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
30318             return withPackageId(packageInfo, pathAndExtension);
30319         };
30320         var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
30321         if (rest !== "") { // If "rest" is empty, we just did this search above.
30322             var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
30323             // 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.
30324             packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
30325             if (packageInfo && packageInfo.versionPaths) {
30326                 if (state.traceEnabled) {
30327                     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);
30328                 }
30329                 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
30330                 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
30331                 if (fromPaths) {
30332                     return fromPaths.value;
30333                 }
30334             }
30335         }
30336         return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
30337     }
30338     function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
30339         var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
30340         if (matchedPattern) {
30341             var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
30342             var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
30343             if (state.traceEnabled) {
30344                 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
30345             }
30346             var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
30347                 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
30348                 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
30349                 if (state.traceEnabled) {
30350                     trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
30351                 }
30352                 // A path mapping may have an extension, in contrast to an import, which should omit it.
30353                 var extension = ts.tryGetExtensionFromPath(candidate);
30354                 if (extension !== undefined) {
30355                     var path_1 = tryFile(candidate, onlyRecordFailures, state);
30356                     if (path_1 !== undefined) {
30357                         return noPackageId({ path: path_1, ext: extension });
30358                     }
30359                 }
30360                 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
30361             });
30362             return { value: resolved };
30363         }
30364     }
30365     /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
30366     var mangledScopedPackageSeparator = "__";
30367     /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
30368     function mangleScopedPackageNameWithTrace(packageName, state) {
30369         var mangled = mangleScopedPackageName(packageName);
30370         if (state.traceEnabled && mangled !== packageName) {
30371             trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
30372         }
30373         return mangled;
30374     }
30375     /* @internal */
30376     function getTypesPackageName(packageName) {
30377         return "@types/" + mangleScopedPackageName(packageName);
30378     }
30379     ts.getTypesPackageName = getTypesPackageName;
30380     /* @internal */
30381     function mangleScopedPackageName(packageName) {
30382         if (ts.startsWith(packageName, "@")) {
30383             var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
30384             if (replaceSlash !== packageName) {
30385                 return replaceSlash.slice(1); // Take off the "@"
30386             }
30387         }
30388         return packageName;
30389     }
30390     ts.mangleScopedPackageName = mangleScopedPackageName;
30391     /* @internal */
30392     function getPackageNameFromTypesPackageName(mangledName) {
30393         var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
30394         if (withoutAtTypePrefix !== mangledName) {
30395             return unmangleScopedPackageName(withoutAtTypePrefix);
30396         }
30397         return mangledName;
30398     }
30399     ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
30400     /* @internal */
30401     function unmangleScopedPackageName(typesPackageName) {
30402         return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
30403             "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
30404             typesPackageName;
30405     }
30406     ts.unmangleScopedPackageName = unmangleScopedPackageName;
30407     function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
30408         var result = cache && cache.get(containingDirectory);
30409         if (result) {
30410             if (state.traceEnabled) {
30411                 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
30412             }
30413             state.resultFromCache = result;
30414             return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
30415         }
30416     }
30417     function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
30418         var traceEnabled = isTraceEnabled(compilerOptions, host);
30419         var failedLookupLocations = [];
30420         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30421         var containingDirectory = ts.getDirectoryPath(containingFile);
30422         var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
30423         // No originalPath because classic resolution doesn't resolve realPath
30424         return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
30425         function tryResolve(extensions) {
30426             var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
30427             if (resolvedUsingSettings) {
30428                 return { value: resolvedUsingSettings };
30429             }
30430             if (!ts.isExternalModuleNameRelative(moduleName)) {
30431                 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30432                 // Climb up parent directories looking for a module.
30433                 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
30434                     var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
30435                     if (resolutionFromCache) {
30436                         return resolutionFromCache;
30437                     }
30438                     var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
30439                     return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
30440                 });
30441                 if (resolved_3) {
30442                     return resolved_3;
30443                 }
30444                 if (extensions === Extensions.TypeScript) {
30445                     // If we didn't find the file normally, look it up in @types.
30446                     return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
30447                 }
30448             }
30449             else {
30450                 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
30451                 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
30452             }
30453         }
30454     }
30455     ts.classicNameResolver = classicNameResolver;
30456     /**
30457      * A host may load a module from a global cache of typings.
30458      * This is the minumum code needed to expose that functionality; the rest is in the host.
30459      */
30460     /* @internal */
30461     function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
30462         var traceEnabled = isTraceEnabled(compilerOptions, host);
30463         if (traceEnabled) {
30464             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);
30465         }
30466         var failedLookupLocations = [];
30467         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30468         var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
30469         return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
30470     }
30471     ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
30472     /**
30473      * Wraps value to SearchResult.
30474      * @returns undefined if value is undefined or { value } otherwise
30475      */
30476     function toSearchResult(value) {
30477         return value !== undefined ? { value: value } : undefined;
30478     }
30479 })(ts || (ts = {}));
30480 /* @internal */
30481 var ts;
30482 (function (ts) {
30483     var ModuleInstanceState;
30484     (function (ModuleInstanceState) {
30485         ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
30486         ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
30487         ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
30488     })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
30489     function getModuleInstanceState(node, visited) {
30490         if (node.body && !node.body.parent) {
30491             // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
30492             setParentPointers(node, node.body);
30493         }
30494         return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
30495     }
30496     ts.getModuleInstanceState = getModuleInstanceState;
30497     function getModuleInstanceStateCached(node, visited) {
30498         if (visited === void 0) { visited = ts.createMap(); }
30499         var nodeId = "" + ts.getNodeId(node);
30500         if (visited.has(nodeId)) {
30501             return visited.get(nodeId) || 0 /* NonInstantiated */;
30502         }
30503         visited.set(nodeId, undefined);
30504         var result = getModuleInstanceStateWorker(node, visited);
30505         visited.set(nodeId, result);
30506         return result;
30507     }
30508     function getModuleInstanceStateWorker(node, visited) {
30509         // A module is uninstantiated if it contains only
30510         switch (node.kind) {
30511             // 1. interface declarations, type alias declarations
30512             case 246 /* InterfaceDeclaration */:
30513             case 247 /* TypeAliasDeclaration */:
30514                 return 0 /* NonInstantiated */;
30515             // 2. const enum declarations
30516             case 248 /* EnumDeclaration */:
30517                 if (ts.isEnumConst(node)) {
30518                     return 2 /* ConstEnumOnly */;
30519                 }
30520                 break;
30521             // 3. non-exported import declarations
30522             case 254 /* ImportDeclaration */:
30523             case 253 /* ImportEqualsDeclaration */:
30524                 if (!(ts.hasModifier(node, 1 /* Export */))) {
30525                     return 0 /* NonInstantiated */;
30526                 }
30527                 break;
30528             // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
30529             case 260 /* ExportDeclaration */:
30530                 var exportDeclaration = node;
30531                 if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 261 /* NamedExports */) {
30532                     var state = 0 /* NonInstantiated */;
30533                     for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
30534                         var specifier = _a[_i];
30535                         var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
30536                         if (specifierState > state) {
30537                             state = specifierState;
30538                         }
30539                         if (state === 1 /* Instantiated */) {
30540                             return state;
30541                         }
30542                     }
30543                     return state;
30544                 }
30545                 break;
30546             // 5. other uninstantiated module declarations.
30547             case 250 /* ModuleBlock */: {
30548                 var state_1 = 0 /* NonInstantiated */;
30549                 ts.forEachChild(node, function (n) {
30550                     var childState = getModuleInstanceStateCached(n, visited);
30551                     switch (childState) {
30552                         case 0 /* NonInstantiated */:
30553                             // child is non-instantiated - continue searching
30554                             return;
30555                         case 2 /* ConstEnumOnly */:
30556                             // child is const enum only - record state and continue searching
30557                             state_1 = 2 /* ConstEnumOnly */;
30558                             return;
30559                         case 1 /* Instantiated */:
30560                             // child is instantiated - record state and stop
30561                             state_1 = 1 /* Instantiated */;
30562                             return true;
30563                         default:
30564                             ts.Debug.assertNever(childState);
30565                     }
30566                 });
30567                 return state_1;
30568             }
30569             case 249 /* ModuleDeclaration */:
30570                 return getModuleInstanceState(node, visited);
30571             case 75 /* Identifier */:
30572                 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
30573                 // be considered the same as type alias
30574                 if (node.isInJSDocNamespace) {
30575                     return 0 /* NonInstantiated */;
30576                 }
30577         }
30578         return 1 /* Instantiated */;
30579     }
30580     function getModuleInstanceStateForAliasTarget(specifier, visited) {
30581         var name = specifier.propertyName || specifier.name;
30582         var p = specifier.parent;
30583         while (p) {
30584             if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
30585                 var statements = p.statements;
30586                 var found = void 0;
30587                 for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
30588                     var statement = statements_1[_i];
30589                     if (ts.nodeHasName(statement, name)) {
30590                         if (!statement.parent) {
30591                             setParentPointers(p, statement);
30592                         }
30593                         var state = getModuleInstanceStateCached(statement, visited);
30594                         if (found === undefined || state > found) {
30595                             found = state;
30596                         }
30597                         if (found === 1 /* Instantiated */) {
30598                             return found;
30599                         }
30600                     }
30601                 }
30602                 if (found !== undefined) {
30603                     return found;
30604                 }
30605             }
30606             p = p.parent;
30607         }
30608         return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
30609     }
30610     var ContainerFlags;
30611     (function (ContainerFlags) {
30612         // The current node is not a container, and no container manipulation should happen before
30613         // recursing into it.
30614         ContainerFlags[ContainerFlags["None"] = 0] = "None";
30615         // The current node is a container.  It should be set as the current container (and block-
30616         // container) before recursing into it.  The current node does not have locals.  Examples:
30617         //
30618         //      Classes, ObjectLiterals, TypeLiterals, Interfaces...
30619         ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
30620         // The current node is a block-scoped-container.  It should be set as the current block-
30621         // container before recursing into it.  Examples:
30622         //
30623         //      Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
30624         ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
30625         // The current node is the container of a control flow path. The current control flow should
30626         // be saved and restored, and a new control flow initialized within the container.
30627         ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
30628         ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
30629         ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
30630         ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
30631         ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
30632         ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
30633     })(ContainerFlags || (ContainerFlags = {}));
30634     function initFlowNode(node) {
30635         ts.Debug.attachFlowNodeDebugInfo(node);
30636         return node;
30637     }
30638     var binder = createBinder();
30639     function bindSourceFile(file, options) {
30640         ts.performance.mark("beforeBind");
30641         ts.perfLogger.logStartBindFile("" + file.fileName);
30642         binder(file, options);
30643         ts.perfLogger.logStopBindFile();
30644         ts.performance.mark("afterBind");
30645         ts.performance.measure("Bind", "beforeBind", "afterBind");
30646     }
30647     ts.bindSourceFile = bindSourceFile;
30648     function createBinder() {
30649         var file;
30650         var options;
30651         var languageVersion;
30652         var parent;
30653         var container;
30654         var thisParentContainer; // Container one level up
30655         var blockScopeContainer;
30656         var lastContainer;
30657         var delayedTypeAliases;
30658         var seenThisKeyword;
30659         // state used by control flow analysis
30660         var currentFlow;
30661         var currentBreakTarget;
30662         var currentContinueTarget;
30663         var currentReturnTarget;
30664         var currentTrueTarget;
30665         var currentFalseTarget;
30666         var currentExceptionTarget;
30667         var preSwitchCaseFlow;
30668         var activeLabelList;
30669         var hasExplicitReturn;
30670         // state used for emit helpers
30671         var emitFlags;
30672         // If this file is an external module, then it is automatically in strict-mode according to
30673         // ES6.  If it is not an external module, then we'll determine if it is in strict mode or
30674         // not depending on if we see "use strict" in certain places or if we hit a class/namespace
30675         // or if compiler options contain alwaysStrict.
30676         var inStrictMode;
30677         var symbolCount = 0;
30678         var Symbol;
30679         var classifiableNames;
30680         var unreachableFlow = { flags: 1 /* Unreachable */ };
30681         var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
30682         // state used to aggregate transform flags during bind.
30683         var subtreeTransformFlags = 0 /* None */;
30684         var skipTransformFlagAggregation;
30685         /**
30686          * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
30687          * 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)
30688          * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
30689          */
30690         function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
30691             return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
30692         }
30693         function bindSourceFile(f, opts) {
30694             file = f;
30695             options = opts;
30696             languageVersion = ts.getEmitScriptTarget(options);
30697             inStrictMode = bindInStrictMode(file, opts);
30698             classifiableNames = ts.createUnderscoreEscapedMap();
30699             symbolCount = 0;
30700             skipTransformFlagAggregation = file.isDeclarationFile;
30701             Symbol = ts.objectAllocator.getSymbolConstructor();
30702             // Attach debugging information if necessary
30703             ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
30704             ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
30705             if (!file.locals) {
30706                 bind(file);
30707                 file.symbolCount = symbolCount;
30708                 file.classifiableNames = classifiableNames;
30709                 delayedBindJSDocTypedefTag();
30710             }
30711             file = undefined;
30712             options = undefined;
30713             languageVersion = undefined;
30714             parent = undefined;
30715             container = undefined;
30716             thisParentContainer = undefined;
30717             blockScopeContainer = undefined;
30718             lastContainer = undefined;
30719             delayedTypeAliases = undefined;
30720             seenThisKeyword = false;
30721             currentFlow = undefined;
30722             currentBreakTarget = undefined;
30723             currentContinueTarget = undefined;
30724             currentReturnTarget = undefined;
30725             currentTrueTarget = undefined;
30726             currentFalseTarget = undefined;
30727             currentExceptionTarget = undefined;
30728             activeLabelList = undefined;
30729             hasExplicitReturn = false;
30730             emitFlags = 0 /* None */;
30731             subtreeTransformFlags = 0 /* None */;
30732         }
30733         return bindSourceFile;
30734         function bindInStrictMode(file, opts) {
30735             if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
30736                 // bind in strict mode source files with alwaysStrict option
30737                 return true;
30738             }
30739             else {
30740                 return !!file.externalModuleIndicator;
30741             }
30742         }
30743         function createSymbol(flags, name) {
30744             symbolCount++;
30745             return new Symbol(flags, name);
30746         }
30747         function addDeclarationToSymbol(symbol, node, symbolFlags) {
30748             symbol.flags |= symbolFlags;
30749             node.symbol = symbol;
30750             symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
30751             if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
30752                 symbol.exports = ts.createSymbolTable();
30753             }
30754             if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
30755                 symbol.members = ts.createSymbolTable();
30756             }
30757             // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
30758             if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
30759                 symbol.constEnumOnlyModule = false;
30760             }
30761             if (symbolFlags & 111551 /* Value */) {
30762                 ts.setValueDeclaration(symbol, node);
30763             }
30764         }
30765         // Should not be called on a declaration with a computed property name,
30766         // unless it is a well known Symbol.
30767         function getDeclarationName(node) {
30768             if (node.kind === 259 /* ExportAssignment */) {
30769                 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
30770             }
30771             var name = ts.getNameOfDeclaration(node);
30772             if (name) {
30773                 if (ts.isAmbientModule(node)) {
30774                     var moduleName = ts.getTextOfIdentifierOrLiteral(name);
30775                     return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
30776                 }
30777                 if (name.kind === 154 /* ComputedPropertyName */) {
30778                     var nameExpression = name.expression;
30779                     // treat computed property names where expression is string/numeric literal as just string/numeric literal
30780                     if (ts.isStringOrNumericLiteralLike(nameExpression)) {
30781                         return ts.escapeLeadingUnderscores(nameExpression.text);
30782                     }
30783                     if (ts.isSignedNumericLiteral(nameExpression)) {
30784                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
30785                     }
30786                     ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
30787                     return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
30788                 }
30789                 if (ts.isWellKnownSymbolSyntactically(name)) {
30790                     return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
30791                 }
30792                 if (ts.isPrivateIdentifier(name)) {
30793                     // containingClass exists because private names only allowed inside classes
30794                     var containingClass = ts.getContainingClass(node);
30795                     if (!containingClass) {
30796                         // we can get here in cases where there is already a parse error.
30797                         return undefined;
30798                     }
30799                     var containingClassSymbol = containingClass.symbol;
30800                     return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
30801                 }
30802                 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
30803             }
30804             switch (node.kind) {
30805                 case 162 /* Constructor */:
30806                     return "__constructor" /* Constructor */;
30807                 case 170 /* FunctionType */:
30808                 case 165 /* CallSignature */:
30809                 case 305 /* JSDocSignature */:
30810                     return "__call" /* Call */;
30811                 case 171 /* ConstructorType */:
30812                 case 166 /* ConstructSignature */:
30813                     return "__new" /* New */;
30814                 case 167 /* IndexSignature */:
30815                     return "__index" /* Index */;
30816                 case 260 /* ExportDeclaration */:
30817                     return "__export" /* ExportStar */;
30818                 case 290 /* SourceFile */:
30819                     // json file should behave as
30820                     // module.exports = ...
30821                     return "export=" /* ExportEquals */;
30822                 case 209 /* BinaryExpression */:
30823                     if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
30824                         // module.exports = ...
30825                         return "export=" /* ExportEquals */;
30826                     }
30827                     ts.Debug.fail("Unknown binary declaration kind");
30828                     break;
30829                 case 300 /* JSDocFunctionType */:
30830                     return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
30831                 case 156 /* Parameter */:
30832                     // Parameters with names are handled at the top of this function.  Parameters
30833                     // without names can only come from JSDocFunctionTypes.
30834                     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"; });
30835                     var functionType = node.parent;
30836                     var index = functionType.parameters.indexOf(node);
30837                     return "arg" + index;
30838             }
30839         }
30840         function getDisplayName(node) {
30841             return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
30842         }
30843         /**
30844          * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
30845          * @param symbolTable - The symbol table which node will be added to.
30846          * @param parent - node's parent declaration.
30847          * @param node - The declaration to be added to the symbol table
30848          * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
30849          * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
30850          */
30851         function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
30852             ts.Debug.assert(!ts.hasDynamicName(node));
30853             var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
30854             // The exported symbol for an export default function/class node is always named "default"
30855             var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
30856             var symbol;
30857             if (name === undefined) {
30858                 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
30859             }
30860             else {
30861                 // Check and see if the symbol table already has a symbol with this name.  If not,
30862                 // create a new symbol with this name and add it to the table.  Note that we don't
30863                 // give the new symbol any flags *yet*.  This ensures that it will not conflict
30864                 // with the 'excludes' flags we pass in.
30865                 //
30866                 // If we do get an existing symbol, see if it conflicts with the new symbol we're
30867                 // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within
30868                 // the same symbol table.  If we have a conflict, report the issue on each
30869                 // declaration we have for this symbol, and then create a new symbol for this
30870                 // declaration.
30871                 //
30872                 // Note that when properties declared in Javascript constructors
30873                 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
30874                 // Always. This allows the common Javascript pattern of overwriting a prototype method
30875                 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
30876                 //
30877                 // If we created a new symbol, either because we didn't have a symbol with this name
30878                 // in the symbol table, or we conflicted with an existing symbol, then just add this
30879                 // node as the sole declaration of the new symbol.
30880                 //
30881                 // Otherwise, we'll be merging into a compatible existing symbol (for example when
30882                 // you have multiple 'vars' with the same name in the same container).  In this case
30883                 // just add this node into the declarations list of the symbol.
30884                 symbol = symbolTable.get(name);
30885                 if (includes & 2885600 /* Classifiable */) {
30886                     classifiableNames.set(name, true);
30887                 }
30888                 if (!symbol) {
30889                     symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
30890                     if (isReplaceableByMethod)
30891                         symbol.isReplaceableByMethod = true;
30892                 }
30893                 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
30894                     // A symbol already exists, so don't add this as a declaration.
30895                     return symbol;
30896                 }
30897                 else if (symbol.flags & excludes) {
30898                     if (symbol.isReplaceableByMethod) {
30899                         // Javascript constructor-declared symbols can be discarded in favor of
30900                         // prototype symbols like methods.
30901                         symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
30902                     }
30903                     else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
30904                         // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
30905                         if (ts.isNamedDeclaration(node)) {
30906                             node.name.parent = node;
30907                         }
30908                         // Report errors every position with duplicate declaration
30909                         // Report errors on previous encountered declarations
30910                         var message_1 = symbol.flags & 2 /* BlockScopedVariable */
30911                             ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
30912                             : ts.Diagnostics.Duplicate_identifier_0;
30913                         var messageNeedsName_1 = true;
30914                         if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
30915                             message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
30916                             messageNeedsName_1 = false;
30917                         }
30918                         var multipleDefaultExports_1 = false;
30919                         if (ts.length(symbol.declarations)) {
30920                             // If the current node is a default export of some sort, then check if
30921                             // there are any other default exports that we need to error on.
30922                             // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
30923                             if (isDefaultExport) {
30924                                 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
30925                                 messageNeedsName_1 = false;
30926                                 multipleDefaultExports_1 = true;
30927                             }
30928                             else {
30929                                 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
30930                                 // Error on multiple export default in the following case:
30931                                 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
30932                                 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
30933                                 if (symbol.declarations && symbol.declarations.length &&
30934                                     (node.kind === 259 /* ExportAssignment */ && !node.isExportEquals)) {
30935                                     message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
30936                                     messageNeedsName_1 = false;
30937                                     multipleDefaultExports_1 = true;
30938                                 }
30939                             }
30940                         }
30941                         var relatedInformation_1 = [];
30942                         if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
30943                             // export type T; - may have meant export type { T }?
30944                             relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
30945                         }
30946                         var declarationName_1 = ts.getNameOfDeclaration(node) || node;
30947                         ts.forEach(symbol.declarations, function (declaration, index) {
30948                             var decl = ts.getNameOfDeclaration(declaration) || declaration;
30949                             var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
30950                             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);
30951                             if (multipleDefaultExports_1) {
30952                                 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
30953                             }
30954                         });
30955                         var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
30956                         file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
30957                         symbol = createSymbol(0 /* None */, name);
30958                     }
30959                 }
30960             }
30961             addDeclarationToSymbol(symbol, node, includes);
30962             if (symbol.parent) {
30963                 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
30964             }
30965             else {
30966                 symbol.parent = parent;
30967             }
30968             return symbol;
30969         }
30970         function declareModuleMember(node, symbolFlags, symbolExcludes) {
30971             var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
30972             if (symbolFlags & 2097152 /* Alias */) {
30973                 if (node.kind === 263 /* ExportSpecifier */ || (node.kind === 253 /* ImportEqualsDeclaration */ && hasExportModifier)) {
30974                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
30975                 }
30976                 else {
30977                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
30978                 }
30979             }
30980             else {
30981                 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
30982                 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
30983                 //
30984                 //   1. We treat locals and exports of the same name as mutually exclusive within a container.
30985                 //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
30986                 //      with the same name in the same container.
30987                 //      TODO: Make this a more specific error and decouple it from the exclusion logic.
30988                 //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
30989                 //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
30990                 //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
30991                 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
30992                 //       during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
30993                 //       and this case is specially handled. Module augmentations should only be merged with original module definition
30994                 //       and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
30995                 if (ts.isJSDocTypeAlias(node))
30996                     ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
30997                 if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
30998                     if (!container.locals || (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
30999                         return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
31000                     }
31001                     var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
31002                     var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
31003                     local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
31004                     node.localSymbol = local;
31005                     return local;
31006                 }
31007                 else {
31008                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
31009                 }
31010             }
31011         }
31012         // All container nodes are kept on a linked list in declaration order. This list is used by
31013         // the getLocalNameOfContainer function in the type checker to validate that the local name
31014         // used for a container is unique.
31015         function bindContainer(node, containerFlags) {
31016             // Before we recurse into a node's children, we first save the existing parent, container
31017             // and block-container.  Then after we pop out of processing the children, we restore
31018             // these saved values.
31019             var saveContainer = container;
31020             var saveThisParentContainer = thisParentContainer;
31021             var savedBlockScopeContainer = blockScopeContainer;
31022             // Depending on what kind of node this is, we may have to adjust the current container
31023             // and block-container.   If the current node is a container, then it is automatically
31024             // considered the current block-container as well.  Also, for containers that we know
31025             // may contain locals, we eagerly initialize the .locals field. We do this because
31026             // it's highly likely that the .locals will be needed to place some child in (for example,
31027             // a parameter, or variable declaration).
31028             //
31029             // However, we do not proactively create the .locals for block-containers because it's
31030             // totally normal and common for block-containers to never actually have a block-scoped
31031             // variable in them.  We don't want to end up allocating an object for every 'block' we
31032             // run into when most of them won't be necessary.
31033             //
31034             // Finally, if this is a block-container, then we clear out any existing .locals object
31035             // it may contain within it.  This happens in incremental scenarios.  Because we can be
31036             // reusing a node from a previous compilation, that node may have had 'locals' created
31037             // for it.  We must clear this so we don't accidentally move any stale data forward from
31038             // a previous compilation.
31039             if (containerFlags & 1 /* IsContainer */) {
31040                 if (node.kind !== 202 /* ArrowFunction */) {
31041                     thisParentContainer = container;
31042                 }
31043                 container = blockScopeContainer = node;
31044                 if (containerFlags & 32 /* HasLocals */) {
31045                     container.locals = ts.createSymbolTable();
31046                 }
31047                 addToContainerChain(container);
31048             }
31049             else if (containerFlags & 2 /* IsBlockScopedContainer */) {
31050                 blockScopeContainer = node;
31051                 blockScopeContainer.locals = undefined;
31052             }
31053             if (containerFlags & 4 /* IsControlFlowContainer */) {
31054                 var saveCurrentFlow = currentFlow;
31055                 var saveBreakTarget = currentBreakTarget;
31056                 var saveContinueTarget = currentContinueTarget;
31057                 var saveReturnTarget = currentReturnTarget;
31058                 var saveExceptionTarget = currentExceptionTarget;
31059                 var saveActiveLabelList = activeLabelList;
31060                 var saveHasExplicitReturn = hasExplicitReturn;
31061                 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) &&
31062                     !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
31063                 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
31064                 // similarly to break statements that exit to a label just past the statement body.
31065                 if (!isIIFE) {
31066                     currentFlow = initFlowNode({ flags: 2 /* Start */ });
31067                     if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
31068                         currentFlow.node = node;
31069                     }
31070                 }
31071                 // We create a return control flow graph for IIFEs and constructors. For constructors
31072                 // we use the return control flow graph in strict property initialization checks.
31073                 currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined;
31074                 currentExceptionTarget = undefined;
31075                 currentBreakTarget = undefined;
31076                 currentContinueTarget = undefined;
31077                 activeLabelList = undefined;
31078                 hasExplicitReturn = false;
31079                 bindChildren(node);
31080                 // Reset all reachability check related flags on node (for incremental scenarios)
31081                 node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
31082                 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
31083                     node.flags |= 256 /* HasImplicitReturn */;
31084                     if (hasExplicitReturn)
31085                         node.flags |= 512 /* HasExplicitReturn */;
31086                     node.endFlowNode = currentFlow;
31087                 }
31088                 if (node.kind === 290 /* SourceFile */) {
31089                     node.flags |= emitFlags;
31090                 }
31091                 if (currentReturnTarget) {
31092                     addAntecedent(currentReturnTarget, currentFlow);
31093                     currentFlow = finishFlowLabel(currentReturnTarget);
31094                     if (node.kind === 162 /* Constructor */) {
31095                         node.returnFlowNode = currentFlow;
31096                     }
31097                 }
31098                 if (!isIIFE) {
31099                     currentFlow = saveCurrentFlow;
31100                 }
31101                 currentBreakTarget = saveBreakTarget;
31102                 currentContinueTarget = saveContinueTarget;
31103                 currentReturnTarget = saveReturnTarget;
31104                 currentExceptionTarget = saveExceptionTarget;
31105                 activeLabelList = saveActiveLabelList;
31106                 hasExplicitReturn = saveHasExplicitReturn;
31107             }
31108             else if (containerFlags & 64 /* IsInterface */) {
31109                 seenThisKeyword = false;
31110                 bindChildren(node);
31111                 node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
31112             }
31113             else {
31114                 bindChildren(node);
31115             }
31116             container = saveContainer;
31117             thisParentContainer = saveThisParentContainer;
31118             blockScopeContainer = savedBlockScopeContainer;
31119         }
31120         function bindChildren(node) {
31121             if (skipTransformFlagAggregation) {
31122                 bindChildrenWorker(node);
31123             }
31124             else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
31125                 skipTransformFlagAggregation = true;
31126                 bindChildrenWorker(node);
31127                 skipTransformFlagAggregation = false;
31128                 subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
31129             }
31130             else {
31131                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31132                 subtreeTransformFlags = 0;
31133                 bindChildrenWorker(node);
31134                 subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags);
31135             }
31136         }
31137         function bindEachFunctionsFirst(nodes) {
31138             bindEach(nodes, function (n) { return n.kind === 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31139             bindEach(nodes, function (n) { return n.kind !== 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31140         }
31141         function bindEach(nodes, bindFunction) {
31142             if (bindFunction === void 0) { bindFunction = bind; }
31143             if (nodes === undefined) {
31144                 return;
31145             }
31146             if (skipTransformFlagAggregation) {
31147                 ts.forEach(nodes, bindFunction);
31148             }
31149             else {
31150                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31151                 subtreeTransformFlags = 0 /* None */;
31152                 var nodeArrayFlags = 0 /* None */;
31153                 for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
31154                     var node = nodes_2[_i];
31155                     bindFunction(node);
31156                     nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
31157                 }
31158                 nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
31159                 subtreeTransformFlags |= savedSubtreeTransformFlags;
31160             }
31161         }
31162         function bindEachChild(node) {
31163             ts.forEachChild(node, bind, bindEach);
31164         }
31165         function bindChildrenWorker(node) {
31166             if (checkUnreachable(node)) {
31167                 bindEachChild(node);
31168                 bindJSDoc(node);
31169                 return;
31170             }
31171             if (node.kind >= 225 /* FirstStatement */ && node.kind <= 241 /* LastStatement */ && !options.allowUnreachableCode) {
31172                 node.flowNode = currentFlow;
31173             }
31174             switch (node.kind) {
31175                 case 229 /* WhileStatement */:
31176                     bindWhileStatement(node);
31177                     break;
31178                 case 228 /* DoStatement */:
31179                     bindDoStatement(node);
31180                     break;
31181                 case 230 /* ForStatement */:
31182                     bindForStatement(node);
31183                     break;
31184                 case 231 /* ForInStatement */:
31185                 case 232 /* ForOfStatement */:
31186                     bindForInOrForOfStatement(node);
31187                     break;
31188                 case 227 /* IfStatement */:
31189                     bindIfStatement(node);
31190                     break;
31191                 case 235 /* ReturnStatement */:
31192                 case 239 /* ThrowStatement */:
31193                     bindReturnOrThrow(node);
31194                     break;
31195                 case 234 /* BreakStatement */:
31196                 case 233 /* ContinueStatement */:
31197                     bindBreakOrContinueStatement(node);
31198                     break;
31199                 case 240 /* TryStatement */:
31200                     bindTryStatement(node);
31201                     break;
31202                 case 237 /* SwitchStatement */:
31203                     bindSwitchStatement(node);
31204                     break;
31205                 case 251 /* CaseBlock */:
31206                     bindCaseBlock(node);
31207                     break;
31208                 case 277 /* CaseClause */:
31209                     bindCaseClause(node);
31210                     break;
31211                 case 226 /* ExpressionStatement */:
31212                     bindExpressionStatement(node);
31213                     break;
31214                 case 238 /* LabeledStatement */:
31215                     bindLabeledStatement(node);
31216                     break;
31217                 case 207 /* PrefixUnaryExpression */:
31218                     bindPrefixUnaryExpressionFlow(node);
31219                     break;
31220                 case 208 /* PostfixUnaryExpression */:
31221                     bindPostfixUnaryExpressionFlow(node);
31222                     break;
31223                 case 209 /* BinaryExpression */:
31224                     bindBinaryExpressionFlow(node);
31225                     break;
31226                 case 203 /* DeleteExpression */:
31227                     bindDeleteExpressionFlow(node);
31228                     break;
31229                 case 210 /* ConditionalExpression */:
31230                     bindConditionalExpressionFlow(node);
31231                     break;
31232                 case 242 /* VariableDeclaration */:
31233                     bindVariableDeclarationFlow(node);
31234                     break;
31235                 case 194 /* PropertyAccessExpression */:
31236                 case 195 /* ElementAccessExpression */:
31237                     bindAccessExpressionFlow(node);
31238                     break;
31239                 case 196 /* CallExpression */:
31240                     bindCallExpressionFlow(node);
31241                     break;
31242                 case 218 /* NonNullExpression */:
31243                     bindNonNullExpressionFlow(node);
31244                     break;
31245                 case 322 /* JSDocTypedefTag */:
31246                 case 315 /* JSDocCallbackTag */:
31247                 case 316 /* JSDocEnumTag */:
31248                     bindJSDocTypeAlias(node);
31249                     break;
31250                 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
31251                 case 290 /* SourceFile */: {
31252                     bindEachFunctionsFirst(node.statements);
31253                     bind(node.endOfFileToken);
31254                     break;
31255                 }
31256                 case 223 /* Block */:
31257                 case 250 /* ModuleBlock */:
31258                     bindEachFunctionsFirst(node.statements);
31259                     break;
31260                 default:
31261                     bindEachChild(node);
31262                     break;
31263             }
31264             bindJSDoc(node);
31265         }
31266         function isNarrowingExpression(expr) {
31267             switch (expr.kind) {
31268                 case 75 /* Identifier */:
31269                 case 104 /* ThisKeyword */:
31270                 case 194 /* PropertyAccessExpression */:
31271                 case 195 /* ElementAccessExpression */:
31272                     return containsNarrowableReference(expr);
31273                 case 196 /* CallExpression */:
31274                     return hasNarrowableArgument(expr);
31275                 case 200 /* ParenthesizedExpression */:
31276                     return isNarrowingExpression(expr.expression);
31277                 case 209 /* BinaryExpression */:
31278                     return isNarrowingBinaryExpression(expr);
31279                 case 207 /* PrefixUnaryExpression */:
31280                     return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
31281                 case 204 /* TypeOfExpression */:
31282                     return isNarrowingExpression(expr.expression);
31283             }
31284             return false;
31285         }
31286         function isNarrowableReference(expr) {
31287             return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ ||
31288                 (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
31289                 ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression);
31290         }
31291         function containsNarrowableReference(expr) {
31292             return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
31293         }
31294         function hasNarrowableArgument(expr) {
31295             if (expr.arguments) {
31296                 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
31297                     var argument = _a[_i];
31298                     if (containsNarrowableReference(argument)) {
31299                         return true;
31300                     }
31301                 }
31302             }
31303             if (expr.expression.kind === 194 /* PropertyAccessExpression */ &&
31304                 containsNarrowableReference(expr.expression.expression)) {
31305                 return true;
31306             }
31307             return false;
31308         }
31309         function isNarrowingTypeofOperands(expr1, expr2) {
31310             return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
31311         }
31312         function isNarrowableInOperands(left, right) {
31313             return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
31314         }
31315         function isNarrowingBinaryExpression(expr) {
31316             switch (expr.operatorToken.kind) {
31317                 case 62 /* EqualsToken */:
31318                     return containsNarrowableReference(expr.left);
31319                 case 34 /* EqualsEqualsToken */:
31320                 case 35 /* ExclamationEqualsToken */:
31321                 case 36 /* EqualsEqualsEqualsToken */:
31322                 case 37 /* ExclamationEqualsEqualsToken */:
31323                     return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
31324                         isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
31325                 case 98 /* InstanceOfKeyword */:
31326                     return isNarrowableOperand(expr.left);
31327                 case 97 /* InKeyword */:
31328                     return isNarrowableInOperands(expr.left, expr.right);
31329                 case 27 /* CommaToken */:
31330                     return isNarrowingExpression(expr.right);
31331             }
31332             return false;
31333         }
31334         function isNarrowableOperand(expr) {
31335             switch (expr.kind) {
31336                 case 200 /* ParenthesizedExpression */:
31337                     return isNarrowableOperand(expr.expression);
31338                 case 209 /* BinaryExpression */:
31339                     switch (expr.operatorToken.kind) {
31340                         case 62 /* EqualsToken */:
31341                             return isNarrowableOperand(expr.left);
31342                         case 27 /* CommaToken */:
31343                             return isNarrowableOperand(expr.right);
31344                     }
31345             }
31346             return containsNarrowableReference(expr);
31347         }
31348         function createBranchLabel() {
31349             return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
31350         }
31351         function createLoopLabel() {
31352             return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
31353         }
31354         function createReduceLabel(target, antecedents, antecedent) {
31355             return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
31356         }
31357         function setFlowNodeReferenced(flow) {
31358             // On first reference we set the Referenced flag, thereafter we set the Shared flag
31359             flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
31360         }
31361         function addAntecedent(label, antecedent) {
31362             if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
31363                 (label.antecedents || (label.antecedents = [])).push(antecedent);
31364                 setFlowNodeReferenced(antecedent);
31365             }
31366         }
31367         function createFlowCondition(flags, antecedent, expression) {
31368             if (antecedent.flags & 1 /* Unreachable */) {
31369                 return antecedent;
31370             }
31371             if (!expression) {
31372                 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
31373             }
31374             if ((expression.kind === 106 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
31375                 expression.kind === 91 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
31376                 !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
31377                 return unreachableFlow;
31378             }
31379             if (!isNarrowingExpression(expression)) {
31380                 return antecedent;
31381             }
31382             setFlowNodeReferenced(antecedent);
31383             return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
31384         }
31385         function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
31386             setFlowNodeReferenced(antecedent);
31387             return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
31388         }
31389         function createFlowMutation(flags, antecedent, node) {
31390             setFlowNodeReferenced(antecedent);
31391             var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
31392             if (currentExceptionTarget) {
31393                 addAntecedent(currentExceptionTarget, result);
31394             }
31395             return result;
31396         }
31397         function createFlowCall(antecedent, node) {
31398             setFlowNodeReferenced(antecedent);
31399             return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
31400         }
31401         function finishFlowLabel(flow) {
31402             var antecedents = flow.antecedents;
31403             if (!antecedents) {
31404                 return unreachableFlow;
31405             }
31406             if (antecedents.length === 1) {
31407                 return antecedents[0];
31408             }
31409             return flow;
31410         }
31411         function isStatementCondition(node) {
31412             var parent = node.parent;
31413             switch (parent.kind) {
31414                 case 227 /* IfStatement */:
31415                 case 229 /* WhileStatement */:
31416                 case 228 /* DoStatement */:
31417                     return parent.expression === node;
31418                 case 230 /* ForStatement */:
31419                 case 210 /* ConditionalExpression */:
31420                     return parent.condition === node;
31421             }
31422             return false;
31423         }
31424         function isLogicalExpression(node) {
31425             while (true) {
31426                 if (node.kind === 200 /* ParenthesizedExpression */) {
31427                     node = node.expression;
31428                 }
31429                 else if (node.kind === 207 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
31430                     node = node.operand;
31431                 }
31432                 else {
31433                     return node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
31434                         node.operatorToken.kind === 56 /* BarBarToken */ ||
31435                         node.operatorToken.kind === 60 /* QuestionQuestionToken */);
31436                 }
31437             }
31438         }
31439         function isTopLevelLogicalExpression(node) {
31440             while (ts.isParenthesizedExpression(node.parent) ||
31441                 ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
31442                 node = node.parent;
31443             }
31444             return !isStatementCondition(node) &&
31445                 !isLogicalExpression(node.parent) &&
31446                 !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
31447         }
31448         function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
31449             var savedTrueTarget = currentTrueTarget;
31450             var savedFalseTarget = currentFalseTarget;
31451             currentTrueTarget = trueTarget;
31452             currentFalseTarget = falseTarget;
31453             action(value);
31454             currentTrueTarget = savedTrueTarget;
31455             currentFalseTarget = savedFalseTarget;
31456         }
31457         function bindCondition(node, trueTarget, falseTarget) {
31458             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
31459             if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
31460                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
31461                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
31462             }
31463         }
31464         function bindIterativeStatement(node, breakTarget, continueTarget) {
31465             var saveBreakTarget = currentBreakTarget;
31466             var saveContinueTarget = currentContinueTarget;
31467             currentBreakTarget = breakTarget;
31468             currentContinueTarget = continueTarget;
31469             bind(node);
31470             currentBreakTarget = saveBreakTarget;
31471             currentContinueTarget = saveContinueTarget;
31472         }
31473         function setContinueTarget(node, target) {
31474             var label = activeLabelList;
31475             while (label && node.parent.kind === 238 /* LabeledStatement */) {
31476                 label.continueTarget = target;
31477                 label = label.next;
31478                 node = node.parent;
31479             }
31480             return target;
31481         }
31482         function bindWhileStatement(node) {
31483             var preWhileLabel = setContinueTarget(node, createLoopLabel());
31484             var preBodyLabel = createBranchLabel();
31485             var postWhileLabel = createBranchLabel();
31486             addAntecedent(preWhileLabel, currentFlow);
31487             currentFlow = preWhileLabel;
31488             bindCondition(node.expression, preBodyLabel, postWhileLabel);
31489             currentFlow = finishFlowLabel(preBodyLabel);
31490             bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
31491             addAntecedent(preWhileLabel, currentFlow);
31492             currentFlow = finishFlowLabel(postWhileLabel);
31493         }
31494         function bindDoStatement(node) {
31495             var preDoLabel = createLoopLabel();
31496             var preConditionLabel = setContinueTarget(node, createBranchLabel());
31497             var postDoLabel = createBranchLabel();
31498             addAntecedent(preDoLabel, currentFlow);
31499             currentFlow = preDoLabel;
31500             bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
31501             addAntecedent(preConditionLabel, currentFlow);
31502             currentFlow = finishFlowLabel(preConditionLabel);
31503             bindCondition(node.expression, preDoLabel, postDoLabel);
31504             currentFlow = finishFlowLabel(postDoLabel);
31505         }
31506         function bindForStatement(node) {
31507             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31508             var preBodyLabel = createBranchLabel();
31509             var postLoopLabel = createBranchLabel();
31510             bind(node.initializer);
31511             addAntecedent(preLoopLabel, currentFlow);
31512             currentFlow = preLoopLabel;
31513             bindCondition(node.condition, preBodyLabel, postLoopLabel);
31514             currentFlow = finishFlowLabel(preBodyLabel);
31515             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31516             bind(node.incrementor);
31517             addAntecedent(preLoopLabel, currentFlow);
31518             currentFlow = finishFlowLabel(postLoopLabel);
31519         }
31520         function bindForInOrForOfStatement(node) {
31521             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31522             var postLoopLabel = createBranchLabel();
31523             bind(node.expression);
31524             addAntecedent(preLoopLabel, currentFlow);
31525             currentFlow = preLoopLabel;
31526             if (node.kind === 232 /* ForOfStatement */) {
31527                 bind(node.awaitModifier);
31528             }
31529             addAntecedent(postLoopLabel, currentFlow);
31530             bind(node.initializer);
31531             if (node.initializer.kind !== 243 /* VariableDeclarationList */) {
31532                 bindAssignmentTargetFlow(node.initializer);
31533             }
31534             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31535             addAntecedent(preLoopLabel, currentFlow);
31536             currentFlow = finishFlowLabel(postLoopLabel);
31537         }
31538         function bindIfStatement(node) {
31539             var thenLabel = createBranchLabel();
31540             var elseLabel = createBranchLabel();
31541             var postIfLabel = createBranchLabel();
31542             bindCondition(node.expression, thenLabel, elseLabel);
31543             currentFlow = finishFlowLabel(thenLabel);
31544             bind(node.thenStatement);
31545             addAntecedent(postIfLabel, currentFlow);
31546             currentFlow = finishFlowLabel(elseLabel);
31547             bind(node.elseStatement);
31548             addAntecedent(postIfLabel, currentFlow);
31549             currentFlow = finishFlowLabel(postIfLabel);
31550         }
31551         function bindReturnOrThrow(node) {
31552             bind(node.expression);
31553             if (node.kind === 235 /* ReturnStatement */) {
31554                 hasExplicitReturn = true;
31555                 if (currentReturnTarget) {
31556                     addAntecedent(currentReturnTarget, currentFlow);
31557                 }
31558             }
31559             currentFlow = unreachableFlow;
31560         }
31561         function findActiveLabel(name) {
31562             for (var label = activeLabelList; label; label = label.next) {
31563                 if (label.name === name) {
31564                     return label;
31565                 }
31566             }
31567             return undefined;
31568         }
31569         function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
31570             var flowLabel = node.kind === 234 /* BreakStatement */ ? breakTarget : continueTarget;
31571             if (flowLabel) {
31572                 addAntecedent(flowLabel, currentFlow);
31573                 currentFlow = unreachableFlow;
31574             }
31575         }
31576         function bindBreakOrContinueStatement(node) {
31577             bind(node.label);
31578             if (node.label) {
31579                 var activeLabel = findActiveLabel(node.label.escapedText);
31580                 if (activeLabel) {
31581                     activeLabel.referenced = true;
31582                     bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
31583                 }
31584             }
31585             else {
31586                 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
31587             }
31588         }
31589         function bindTryStatement(node) {
31590             // We conservatively assume that *any* code in the try block can cause an exception, but we only need
31591             // to track code that causes mutations (because only mutations widen the possible control flow type of
31592             // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
31593             // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
31594             // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
31595             // represent exceptions that occur before any mutations.
31596             var saveReturnTarget = currentReturnTarget;
31597             var saveExceptionTarget = currentExceptionTarget;
31598             var normalExitLabel = createBranchLabel();
31599             var returnLabel = createBranchLabel();
31600             var exceptionLabel = createBranchLabel();
31601             if (node.finallyBlock) {
31602                 currentReturnTarget = returnLabel;
31603             }
31604             addAntecedent(exceptionLabel, currentFlow);
31605             currentExceptionTarget = exceptionLabel;
31606             bind(node.tryBlock);
31607             addAntecedent(normalExitLabel, currentFlow);
31608             if (node.catchClause) {
31609                 // Start of catch clause is the target of exceptions from try block.
31610                 currentFlow = finishFlowLabel(exceptionLabel);
31611                 // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
31612                 // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
31613                 // acts like a second try block.
31614                 exceptionLabel = createBranchLabel();
31615                 addAntecedent(exceptionLabel, currentFlow);
31616                 currentExceptionTarget = exceptionLabel;
31617                 bind(node.catchClause);
31618                 addAntecedent(normalExitLabel, currentFlow);
31619             }
31620             currentReturnTarget = saveReturnTarget;
31621             currentExceptionTarget = saveExceptionTarget;
31622             if (node.finallyBlock) {
31623                 // Possible ways control can reach the finally block:
31624                 // 1) Normal completion of try block of a try-finally or try-catch-finally
31625                 // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
31626                 // 3) Return in try or catch block of a try-finally or try-catch-finally
31627                 // 4) Exception in try block of a try-finally
31628                 // 5) Exception in catch block of a try-catch-finally
31629                 // When analyzing a control flow graph that starts inside a finally block we want to consider all
31630                 // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
31631                 // the finally block, we only want to consider the first two (if we're past a finally block then it
31632                 // must have completed normally). Likewise, when analyzing a control flow graph from return statements
31633                 // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
31634                 // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
31635                 // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
31636                 // node, the pre-finally label is temporarily switched to the reduced antecedent set.
31637                 var finallyLabel = createBranchLabel();
31638                 finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
31639                 currentFlow = finallyLabel;
31640                 bind(node.finallyBlock);
31641                 if (currentFlow.flags & 1 /* Unreachable */) {
31642                     // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
31643                     currentFlow = unreachableFlow;
31644                 }
31645                 else {
31646                     // If we have an IIFE return target and return statements in the try or catch blocks, add a control
31647                     // flow that goes back through the finally block and back through only the return statements.
31648                     if (currentReturnTarget && returnLabel.antecedents) {
31649                         addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
31650                     }
31651                     // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
31652                     // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
31653                     // result in an unreachable current control flow.
31654                     currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
31655                 }
31656             }
31657             else {
31658                 currentFlow = finishFlowLabel(normalExitLabel);
31659             }
31660         }
31661         function bindSwitchStatement(node) {
31662             var postSwitchLabel = createBranchLabel();
31663             bind(node.expression);
31664             var saveBreakTarget = currentBreakTarget;
31665             var savePreSwitchCaseFlow = preSwitchCaseFlow;
31666             currentBreakTarget = postSwitchLabel;
31667             preSwitchCaseFlow = currentFlow;
31668             bind(node.caseBlock);
31669             addAntecedent(postSwitchLabel, currentFlow);
31670             var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 278 /* DefaultClause */; });
31671             // We mark a switch statement as possibly exhaustive if it has no default clause and if all
31672             // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
31673             // this property in control flow analysis, it's there only for backwards compatibility.
31674             node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
31675             if (!hasDefault) {
31676                 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
31677             }
31678             currentBreakTarget = saveBreakTarget;
31679             preSwitchCaseFlow = savePreSwitchCaseFlow;
31680             currentFlow = finishFlowLabel(postSwitchLabel);
31681         }
31682         function bindCaseBlock(node) {
31683             var savedSubtreeTransformFlags = subtreeTransformFlags;
31684             subtreeTransformFlags = 0;
31685             var clauses = node.clauses;
31686             var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
31687             var fallthroughFlow = unreachableFlow;
31688             for (var i = 0; i < clauses.length; i++) {
31689                 var clauseStart = i;
31690                 while (!clauses[i].statements.length && i + 1 < clauses.length) {
31691                     bind(clauses[i]);
31692                     i++;
31693                 }
31694                 var preCaseLabel = createBranchLabel();
31695                 addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
31696                 addAntecedent(preCaseLabel, fallthroughFlow);
31697                 currentFlow = finishFlowLabel(preCaseLabel);
31698                 var clause = clauses[i];
31699                 bind(clause);
31700                 fallthroughFlow = currentFlow;
31701                 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
31702                     clause.fallthroughFlowNode = currentFlow;
31703                 }
31704             }
31705             clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */;
31706             subtreeTransformFlags |= savedSubtreeTransformFlags;
31707         }
31708         function bindCaseClause(node) {
31709             var saveCurrentFlow = currentFlow;
31710             currentFlow = preSwitchCaseFlow;
31711             bind(node.expression);
31712             currentFlow = saveCurrentFlow;
31713             bindEach(node.statements);
31714         }
31715         function bindExpressionStatement(node) {
31716             bind(node.expression);
31717             // A top level call expression with a dotted function name and at least one argument
31718             // is potentially an assertion and is therefore included in the control flow.
31719             if (node.expression.kind === 196 /* CallExpression */) {
31720                 var call = node.expression;
31721                 if (ts.isDottedName(call.expression)) {
31722                     currentFlow = createFlowCall(currentFlow, call);
31723                 }
31724             }
31725         }
31726         function bindLabeledStatement(node) {
31727             var postStatementLabel = createBranchLabel();
31728             activeLabelList = {
31729                 next: activeLabelList,
31730                 name: node.label.escapedText,
31731                 breakTarget: postStatementLabel,
31732                 continueTarget: undefined,
31733                 referenced: false
31734             };
31735             bind(node.label);
31736             bind(node.statement);
31737             if (!activeLabelList.referenced && !options.allowUnusedLabels) {
31738                 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
31739             }
31740             activeLabelList = activeLabelList.next;
31741             addAntecedent(postStatementLabel, currentFlow);
31742             currentFlow = finishFlowLabel(postStatementLabel);
31743         }
31744         function bindDestructuringTargetFlow(node) {
31745             if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
31746                 bindAssignmentTargetFlow(node.left);
31747             }
31748             else {
31749                 bindAssignmentTargetFlow(node);
31750             }
31751         }
31752         function bindAssignmentTargetFlow(node) {
31753             if (isNarrowableReference(node)) {
31754                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
31755             }
31756             else if (node.kind === 192 /* ArrayLiteralExpression */) {
31757                 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
31758                     var e = _a[_i];
31759                     if (e.kind === 213 /* SpreadElement */) {
31760                         bindAssignmentTargetFlow(e.expression);
31761                     }
31762                     else {
31763                         bindDestructuringTargetFlow(e);
31764                     }
31765                 }
31766             }
31767             else if (node.kind === 193 /* ObjectLiteralExpression */) {
31768                 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
31769                     var p = _c[_b];
31770                     if (p.kind === 281 /* PropertyAssignment */) {
31771                         bindDestructuringTargetFlow(p.initializer);
31772                     }
31773                     else if (p.kind === 282 /* ShorthandPropertyAssignment */) {
31774                         bindAssignmentTargetFlow(p.name);
31775                     }
31776                     else if (p.kind === 283 /* SpreadAssignment */) {
31777                         bindAssignmentTargetFlow(p.expression);
31778                     }
31779                 }
31780             }
31781         }
31782         function bindLogicalExpression(node, trueTarget, falseTarget) {
31783             var preRightLabel = createBranchLabel();
31784             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
31785                 bindCondition(node.left, preRightLabel, falseTarget);
31786             }
31787             else {
31788                 bindCondition(node.left, trueTarget, preRightLabel);
31789             }
31790             currentFlow = finishFlowLabel(preRightLabel);
31791             bind(node.operatorToken);
31792             bindCondition(node.right, trueTarget, falseTarget);
31793         }
31794         function bindPrefixUnaryExpressionFlow(node) {
31795             if (node.operator === 53 /* ExclamationToken */) {
31796                 var saveTrueTarget = currentTrueTarget;
31797                 currentTrueTarget = currentFalseTarget;
31798                 currentFalseTarget = saveTrueTarget;
31799                 bindEachChild(node);
31800                 currentFalseTarget = currentTrueTarget;
31801                 currentTrueTarget = saveTrueTarget;
31802             }
31803             else {
31804                 bindEachChild(node);
31805                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31806                     bindAssignmentTargetFlow(node.operand);
31807                 }
31808             }
31809         }
31810         function bindPostfixUnaryExpressionFlow(node) {
31811             bindEachChild(node);
31812             if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31813                 bindAssignmentTargetFlow(node.operand);
31814             }
31815         }
31816         var BindBinaryExpressionFlowState;
31817         (function (BindBinaryExpressionFlowState) {
31818             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
31819             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
31820             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
31821             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
31822             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
31823         })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
31824         function bindBinaryExpressionFlow(node) {
31825             var workStacks = {
31826                 expr: [node],
31827                 state: [1 /* MaybeBindLeft */],
31828                 inStrictMode: [undefined],
31829                 parent: [undefined],
31830                 subtreeFlags: [undefined]
31831             };
31832             var stackIndex = 0;
31833             while (stackIndex >= 0) {
31834                 node = workStacks.expr[stackIndex];
31835                 switch (workStacks.state[stackIndex]) {
31836                     case 0 /* BindThenBindChildren */: {
31837                         // This state is used only when recuring, to emulate the work that `bind` does before
31838                         // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
31839                         node.parent = parent;
31840                         var saveInStrictMode = inStrictMode;
31841                         bindWorker(node);
31842                         var saveParent = parent;
31843                         parent = node;
31844                         var subtreeFlagsState = void 0;
31845                         // While this next part does the work of `bindChildren` before it descends into `bindChildrenWorker`
31846                         // and uses `subtreeFlagsState` to queue up the work that needs to be done once the node is bound.
31847                         if (skipTransformFlagAggregation) {
31848                             // do nothing extra
31849                         }
31850                         else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
31851                             skipTransformFlagAggregation = true;
31852                             subtreeFlagsState = -1;
31853                         }
31854                         else {
31855                             var savedSubtreeTransformFlags = subtreeTransformFlags;
31856                             subtreeTransformFlags = 0;
31857                             subtreeFlagsState = savedSubtreeTransformFlags;
31858                         }
31859                         advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent, subtreeFlagsState);
31860                         break;
31861                     }
31862                     case 1 /* MaybeBindLeft */: {
31863                         var operator = node.operatorToken.kind;
31864                         // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
31865                         // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
31866                         // For now, though, since the common cases are chained `+`, leaving it recursive is fine
31867                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
31868                             if (isTopLevelLogicalExpression(node)) {
31869                                 var postExpressionLabel = createBranchLabel();
31870                                 bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
31871                                 currentFlow = finishFlowLabel(postExpressionLabel);
31872                             }
31873                             else {
31874                                 bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
31875                             }
31876                             completeNode();
31877                         }
31878                         else {
31879                             advanceState(2 /* BindToken */);
31880                             maybeBind(node.left);
31881                         }
31882                         break;
31883                     }
31884                     case 2 /* BindToken */: {
31885                         advanceState(3 /* BindRight */);
31886                         maybeBind(node.operatorToken);
31887                         break;
31888                     }
31889                     case 3 /* BindRight */: {
31890                         advanceState(4 /* FinishBind */);
31891                         maybeBind(node.right);
31892                         break;
31893                     }
31894                     case 4 /* FinishBind */: {
31895                         var operator = node.operatorToken.kind;
31896                         if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
31897                             bindAssignmentTargetFlow(node.left);
31898                             if (operator === 62 /* EqualsToken */ && node.left.kind === 195 /* ElementAccessExpression */) {
31899                                 var elementAccess = node.left;
31900                                 if (isNarrowableOperand(elementAccess.expression)) {
31901                                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
31902                                 }
31903                             }
31904                         }
31905                         completeNode();
31906                         break;
31907                     }
31908                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
31909                 }
31910             }
31911             /**
31912              * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
31913              * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
31914              */
31915             function advanceState(state, isInStrictMode, parent, subtreeFlags) {
31916                 workStacks.state[stackIndex] = state;
31917                 if (isInStrictMode !== undefined) {
31918                     workStacks.inStrictMode[stackIndex] = isInStrictMode;
31919                 }
31920                 if (parent !== undefined) {
31921                     workStacks.parent[stackIndex] = parent;
31922                 }
31923                 if (subtreeFlags !== undefined) {
31924                     workStacks.subtreeFlags[stackIndex] = subtreeFlags;
31925                 }
31926             }
31927             function completeNode() {
31928                 if (workStacks.inStrictMode[stackIndex] !== undefined) {
31929                     if (workStacks.subtreeFlags[stackIndex] === -1) {
31930                         skipTransformFlagAggregation = false;
31931                         subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
31932                     }
31933                     else if (workStacks.subtreeFlags[stackIndex] !== undefined) {
31934                         subtreeTransformFlags = workStacks.subtreeFlags[stackIndex] | computeTransformFlagsForNode(node, subtreeTransformFlags);
31935                     }
31936                     inStrictMode = workStacks.inStrictMode[stackIndex];
31937                     parent = workStacks.parent[stackIndex];
31938                 }
31939                 stackIndex--;
31940             }
31941             /**
31942              * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
31943              */
31944             function maybeBind(node) {
31945                 if (node && ts.isBinaryExpression(node)) {
31946                     stackIndex++;
31947                     workStacks.expr[stackIndex] = node;
31948                     workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
31949                     workStacks.inStrictMode[stackIndex] = undefined;
31950                     workStacks.parent[stackIndex] = undefined;
31951                     workStacks.subtreeFlags[stackIndex] = undefined;
31952                 }
31953                 else {
31954                     bind(node);
31955                 }
31956             }
31957         }
31958         function bindDeleteExpressionFlow(node) {
31959             bindEachChild(node);
31960             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
31961                 bindAssignmentTargetFlow(node.expression);
31962             }
31963         }
31964         function bindConditionalExpressionFlow(node) {
31965             var trueLabel = createBranchLabel();
31966             var falseLabel = createBranchLabel();
31967             var postExpressionLabel = createBranchLabel();
31968             bindCondition(node.condition, trueLabel, falseLabel);
31969             currentFlow = finishFlowLabel(trueLabel);
31970             bind(node.questionToken);
31971             bind(node.whenTrue);
31972             addAntecedent(postExpressionLabel, currentFlow);
31973             currentFlow = finishFlowLabel(falseLabel);
31974             bind(node.colonToken);
31975             bind(node.whenFalse);
31976             addAntecedent(postExpressionLabel, currentFlow);
31977             currentFlow = finishFlowLabel(postExpressionLabel);
31978         }
31979         function bindInitializedVariableFlow(node) {
31980             var name = !ts.isOmittedExpression(node) ? node.name : undefined;
31981             if (ts.isBindingPattern(name)) {
31982                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
31983                     var child = _a[_i];
31984                     bindInitializedVariableFlow(child);
31985                 }
31986             }
31987             else {
31988                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
31989             }
31990         }
31991         function bindVariableDeclarationFlow(node) {
31992             bindEachChild(node);
31993             if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
31994                 bindInitializedVariableFlow(node);
31995             }
31996         }
31997         function bindJSDocTypeAlias(node) {
31998             node.tagName.parent = node;
31999             if (node.kind !== 316 /* JSDocEnumTag */ && node.fullName) {
32000                 setParentPointers(node, node.fullName);
32001             }
32002         }
32003         function bindJSDocClassTag(node) {
32004             bindEachChild(node);
32005             var host = ts.getHostSignatureFromJSDoc(node);
32006             if (host && host.kind !== 161 /* MethodDeclaration */) {
32007                 addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
32008             }
32009         }
32010         function bindOptionalExpression(node, trueTarget, falseTarget) {
32011             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
32012             if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
32013                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32014                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32015             }
32016         }
32017         function bindOptionalChainRest(node) {
32018             switch (node.kind) {
32019                 case 194 /* PropertyAccessExpression */:
32020                     bind(node.questionDotToken);
32021                     bind(node.name);
32022                     break;
32023                 case 195 /* ElementAccessExpression */:
32024                     bind(node.questionDotToken);
32025                     bind(node.argumentExpression);
32026                     break;
32027                 case 196 /* CallExpression */:
32028                     bind(node.questionDotToken);
32029                     bindEach(node.typeArguments);
32030                     bindEach(node.arguments);
32031                     break;
32032             }
32033         }
32034         function bindOptionalChain(node, trueTarget, falseTarget) {
32035             // For an optional chain, we emulate the behavior of a logical expression:
32036             //
32037             // a?.b         -> a && a.b
32038             // a?.b.c       -> a && a.b.c
32039             // a?.b?.c      -> a && a.b && a.b.c
32040             // a?.[x = 1]   -> a && a[x = 1]
32041             //
32042             // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
32043             // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
32044             // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
32045             // chain node. We then treat the entire node as the right side of the expression.
32046             var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
32047             bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
32048             if (preChainLabel) {
32049                 currentFlow = finishFlowLabel(preChainLabel);
32050             }
32051             doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
32052             if (ts.isOutermostOptionalChain(node)) {
32053                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32054                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32055             }
32056         }
32057         function bindOptionalChainFlow(node) {
32058             if (isTopLevelLogicalExpression(node)) {
32059                 var postExpressionLabel = createBranchLabel();
32060                 bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
32061                 currentFlow = finishFlowLabel(postExpressionLabel);
32062             }
32063             else {
32064                 bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
32065             }
32066         }
32067         function bindNonNullExpressionFlow(node) {
32068             if (ts.isOptionalChain(node)) {
32069                 bindOptionalChainFlow(node);
32070             }
32071             else {
32072                 bindEachChild(node);
32073             }
32074         }
32075         function bindAccessExpressionFlow(node) {
32076             if (ts.isOptionalChain(node)) {
32077                 bindOptionalChainFlow(node);
32078             }
32079             else {
32080                 bindEachChild(node);
32081             }
32082         }
32083         function bindCallExpressionFlow(node) {
32084             if (ts.isOptionalChain(node)) {
32085                 bindOptionalChainFlow(node);
32086             }
32087             else {
32088                 // If the target of the call expression is a function expression or arrow function we have
32089                 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
32090                 // the current control flow (which includes evaluation of the IIFE arguments).
32091                 var expr = ts.skipParentheses(node.expression);
32092                 if (expr.kind === 201 /* FunctionExpression */ || expr.kind === 202 /* ArrowFunction */) {
32093                     bindEach(node.typeArguments);
32094                     bindEach(node.arguments);
32095                     bind(node.expression);
32096                 }
32097                 else {
32098                     bindEachChild(node);
32099                 }
32100             }
32101             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
32102                 var propertyAccess = node.expression;
32103                 if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
32104                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
32105                 }
32106             }
32107         }
32108         function getContainerFlags(node) {
32109             switch (node.kind) {
32110                 case 214 /* ClassExpression */:
32111                 case 245 /* ClassDeclaration */:
32112                 case 248 /* EnumDeclaration */:
32113                 case 193 /* ObjectLiteralExpression */:
32114                 case 173 /* TypeLiteral */:
32115                 case 304 /* JSDocTypeLiteral */:
32116                 case 274 /* JsxAttributes */:
32117                     return 1 /* IsContainer */;
32118                 case 246 /* InterfaceDeclaration */:
32119                     return 1 /* IsContainer */ | 64 /* IsInterface */;
32120                 case 249 /* ModuleDeclaration */:
32121                 case 247 /* TypeAliasDeclaration */:
32122                 case 186 /* MappedType */:
32123                     return 1 /* IsContainer */ | 32 /* HasLocals */;
32124                 case 290 /* SourceFile */:
32125                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
32126                 case 161 /* MethodDeclaration */:
32127                     if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
32128                         return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
32129                     }
32130                 // falls through
32131                 case 162 /* Constructor */:
32132                 case 244 /* FunctionDeclaration */:
32133                 case 160 /* MethodSignature */:
32134                 case 163 /* GetAccessor */:
32135                 case 164 /* SetAccessor */:
32136                 case 165 /* CallSignature */:
32137                 case 305 /* JSDocSignature */:
32138                 case 300 /* JSDocFunctionType */:
32139                 case 170 /* FunctionType */:
32140                 case 166 /* ConstructSignature */:
32141                 case 167 /* IndexSignature */:
32142                 case 171 /* ConstructorType */:
32143                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
32144                 case 201 /* FunctionExpression */:
32145                 case 202 /* ArrowFunction */:
32146                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
32147                 case 250 /* ModuleBlock */:
32148                     return 4 /* IsControlFlowContainer */;
32149                 case 159 /* PropertyDeclaration */:
32150                     return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
32151                 case 280 /* CatchClause */:
32152                 case 230 /* ForStatement */:
32153                 case 231 /* ForInStatement */:
32154                 case 232 /* ForOfStatement */:
32155                 case 251 /* CaseBlock */:
32156                     return 2 /* IsBlockScopedContainer */;
32157                 case 223 /* Block */:
32158                     // do not treat blocks directly inside a function as a block-scoped-container.
32159                     // Locals that reside in this block should go to the function locals. Otherwise 'x'
32160                     // would not appear to be a redeclaration of a block scoped local in the following
32161                     // example:
32162                     //
32163                     //      function foo() {
32164                     //          var x;
32165                     //          let x;
32166                     //      }
32167                     //
32168                     // If we placed 'var x' into the function locals and 'let x' into the locals of
32169                     // the block, then there would be no collision.
32170                     //
32171                     // By not creating a new block-scoped-container here, we ensure that both 'var x'
32172                     // and 'let x' go into the Function-container's locals, and we do get a collision
32173                     // conflict.
32174                     return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
32175             }
32176             return 0 /* None */;
32177         }
32178         function addToContainerChain(next) {
32179             if (lastContainer) {
32180                 lastContainer.nextContainer = next;
32181             }
32182             lastContainer = next;
32183         }
32184         function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
32185             switch (container.kind) {
32186                 // Modules, source files, and classes need specialized handling for how their
32187                 // members are declared (for example, a member of a class will go into a specific
32188                 // symbol table depending on if it is static or not). We defer to specialized
32189                 // handlers to take care of declaring these child members.
32190                 case 249 /* ModuleDeclaration */:
32191                     return declareModuleMember(node, symbolFlags, symbolExcludes);
32192                 case 290 /* SourceFile */:
32193                     return declareSourceFileMember(node, symbolFlags, symbolExcludes);
32194                 case 214 /* ClassExpression */:
32195                 case 245 /* ClassDeclaration */:
32196                     return declareClassMember(node, symbolFlags, symbolExcludes);
32197                 case 248 /* EnumDeclaration */:
32198                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
32199                 case 173 /* TypeLiteral */:
32200                 case 304 /* JSDocTypeLiteral */:
32201                 case 193 /* ObjectLiteralExpression */:
32202                 case 246 /* InterfaceDeclaration */:
32203                 case 274 /* JsxAttributes */:
32204                     // Interface/Object-types always have their children added to the 'members' of
32205                     // their container. They are only accessible through an instance of their
32206                     // container, and are never in scope otherwise (even inside the body of the
32207                     // object / type / interface declaring them). An exception is type parameters,
32208                     // which are in scope without qualification (similar to 'locals').
32209                     return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32210                 case 170 /* FunctionType */:
32211                 case 171 /* ConstructorType */:
32212                 case 165 /* CallSignature */:
32213                 case 166 /* ConstructSignature */:
32214                 case 305 /* JSDocSignature */:
32215                 case 167 /* IndexSignature */:
32216                 case 161 /* MethodDeclaration */:
32217                 case 160 /* MethodSignature */:
32218                 case 162 /* Constructor */:
32219                 case 163 /* GetAccessor */:
32220                 case 164 /* SetAccessor */:
32221                 case 244 /* FunctionDeclaration */:
32222                 case 201 /* FunctionExpression */:
32223                 case 202 /* ArrowFunction */:
32224                 case 300 /* JSDocFunctionType */:
32225                 case 322 /* JSDocTypedefTag */:
32226                 case 315 /* JSDocCallbackTag */:
32227                 case 247 /* TypeAliasDeclaration */:
32228                 case 186 /* MappedType */:
32229                     // All the children of these container types are never visible through another
32230                     // symbol (i.e. through another symbol's 'exports' or 'members').  Instead,
32231                     // they're only accessed 'lexically' (i.e. from code that exists underneath
32232                     // their container in the tree). To accomplish this, we simply add their declared
32233                     // symbol to the 'locals' of the container.  These symbols can then be found as
32234                     // the type checker walks up the containers, checking them for matching names.
32235                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32236             }
32237         }
32238         function declareClassMember(node, symbolFlags, symbolExcludes) {
32239             return ts.hasModifier(node, 32 /* Static */)
32240                 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
32241                 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32242         }
32243         function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
32244             return ts.isExternalModule(file)
32245                 ? declareModuleMember(node, symbolFlags, symbolExcludes)
32246                 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32247         }
32248         function hasExportDeclarations(node) {
32249             var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
32250             return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
32251         }
32252         function setExportContextFlag(node) {
32253             // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
32254             // declarations with export modifiers) is an export context in which declarations are implicitly exported.
32255             if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
32256                 node.flags |= 64 /* ExportContext */;
32257             }
32258             else {
32259                 node.flags &= ~64 /* ExportContext */;
32260             }
32261         }
32262         function bindModuleDeclaration(node) {
32263             setExportContextFlag(node);
32264             if (ts.isAmbientModule(node)) {
32265                 if (ts.hasModifier(node, 1 /* Export */)) {
32266                     errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
32267                 }
32268                 if (ts.isModuleAugmentationExternal(node)) {
32269                     declareModuleSymbol(node);
32270                 }
32271                 else {
32272                     var pattern = void 0;
32273                     if (node.name.kind === 10 /* StringLiteral */) {
32274                         var text = node.name.text;
32275                         if (ts.hasZeroOrOneAsteriskCharacter(text)) {
32276                             pattern = ts.tryParsePattern(text);
32277                         }
32278                         else {
32279                             errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
32280                         }
32281                     }
32282                     var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
32283                     file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
32284                 }
32285             }
32286             else {
32287                 var state = declareModuleSymbol(node);
32288                 if (state !== 0 /* NonInstantiated */) {
32289                     var symbol = node.symbol;
32290                     // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
32291                     symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
32292                         // Current must be `const enum` only
32293                         && state === 2 /* ConstEnumOnly */
32294                         // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
32295                         && symbol.constEnumOnlyModule !== false;
32296                 }
32297             }
32298         }
32299         function declareModuleSymbol(node) {
32300             var state = getModuleInstanceState(node);
32301             var instantiated = state !== 0 /* NonInstantiated */;
32302             declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
32303             return state;
32304         }
32305         function bindFunctionOrConstructorType(node) {
32306             // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
32307             // to the one we would get for: { <...>(...): T }
32308             //
32309             // We do that by making an anonymous type literal symbol, and then setting the function
32310             // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
32311             // from an actual type literal symbol you would have gotten had you used the long form.
32312             var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
32313             addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
32314             var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
32315             addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
32316             typeLiteralSymbol.members = ts.createSymbolTable();
32317             typeLiteralSymbol.members.set(symbol.escapedName, symbol);
32318         }
32319         function bindObjectLiteralExpression(node) {
32320             var ElementKind;
32321             (function (ElementKind) {
32322                 ElementKind[ElementKind["Property"] = 1] = "Property";
32323                 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
32324             })(ElementKind || (ElementKind = {}));
32325             if (inStrictMode && !ts.isAssignmentTarget(node)) {
32326                 var seen = ts.createUnderscoreEscapedMap();
32327                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
32328                     var prop = _a[_i];
32329                     if (prop.kind === 283 /* SpreadAssignment */ || prop.name.kind !== 75 /* Identifier */) {
32330                         continue;
32331                     }
32332                     var identifier = prop.name;
32333                     // ECMA-262 11.1.5 Object Initializer
32334                     // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
32335                     // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
32336                     // IsDataDescriptor(propId.descriptor) is true.
32337                     //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
32338                     //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
32339                     //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
32340                     // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
32341                     var currentKind = prop.kind === 281 /* PropertyAssignment */ || prop.kind === 282 /* ShorthandPropertyAssignment */ || prop.kind === 161 /* MethodDeclaration */
32342                         ? 1 /* Property */
32343                         : 2 /* Accessor */;
32344                     var existingKind = seen.get(identifier.escapedText);
32345                     if (!existingKind) {
32346                         seen.set(identifier.escapedText, currentKind);
32347                         continue;
32348                     }
32349                     if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
32350                         var span = ts.getErrorSpanForNode(file, identifier);
32351                         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));
32352                     }
32353                 }
32354             }
32355             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
32356         }
32357         function bindJsxAttributes(node) {
32358             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
32359         }
32360         function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
32361             return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
32362         }
32363         function bindAnonymousDeclaration(node, symbolFlags, name) {
32364             var symbol = createSymbol(symbolFlags, name);
32365             if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
32366                 symbol.parent = container.symbol;
32367             }
32368             addDeclarationToSymbol(symbol, node, symbolFlags);
32369             return symbol;
32370         }
32371         function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
32372             switch (blockScopeContainer.kind) {
32373                 case 249 /* ModuleDeclaration */:
32374                     declareModuleMember(node, symbolFlags, symbolExcludes);
32375                     break;
32376                 case 290 /* SourceFile */:
32377                     if (ts.isExternalOrCommonJsModule(container)) {
32378                         declareModuleMember(node, symbolFlags, symbolExcludes);
32379                         break;
32380                     }
32381                 // falls through
32382                 default:
32383                     if (!blockScopeContainer.locals) {
32384                         blockScopeContainer.locals = ts.createSymbolTable();
32385                         addToContainerChain(blockScopeContainer);
32386                     }
32387                     declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32388             }
32389         }
32390         function delayedBindJSDocTypedefTag() {
32391             if (!delayedTypeAliases) {
32392                 return;
32393             }
32394             var saveContainer = container;
32395             var saveLastContainer = lastContainer;
32396             var saveBlockScopeContainer = blockScopeContainer;
32397             var saveParent = parent;
32398             var saveCurrentFlow = currentFlow;
32399             for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
32400                 var typeAlias = delayedTypeAliases_1[_i];
32401                 var host = ts.getJSDocHost(typeAlias);
32402                 container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
32403                 blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
32404                 currentFlow = initFlowNode({ flags: 2 /* Start */ });
32405                 parent = typeAlias;
32406                 bind(typeAlias.typeExpression);
32407                 var declName = ts.getNameOfDeclaration(typeAlias);
32408                 if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
32409                     // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
32410                     var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
32411                     if (isTopLevel) {
32412                         bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
32413                         var oldContainer = container;
32414                         switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
32415                             case 1 /* ExportsProperty */:
32416                             case 2 /* ModuleExports */:
32417                                 if (!ts.isExternalOrCommonJsModule(file)) {
32418                                     container = undefined;
32419                                 }
32420                                 else {
32421                                     container = file;
32422                                 }
32423                                 break;
32424                             case 4 /* ThisProperty */:
32425                                 container = declName.parent.expression;
32426                                 break;
32427                             case 3 /* PrototypeProperty */:
32428                                 container = declName.parent.expression.name;
32429                                 break;
32430                             case 5 /* Property */:
32431                                 container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
32432                                     : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
32433                                         : declName.parent.expression;
32434                                 break;
32435                             case 0 /* None */:
32436                                 return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
32437                         }
32438                         if (container) {
32439                             declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32440                         }
32441                         container = oldContainer;
32442                     }
32443                 }
32444                 else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 75 /* Identifier */) {
32445                     parent = typeAlias.parent;
32446                     bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32447                 }
32448                 else {
32449                     bind(typeAlias.fullName);
32450                 }
32451             }
32452             container = saveContainer;
32453             lastContainer = saveLastContainer;
32454             blockScopeContainer = saveBlockScopeContainer;
32455             parent = saveParent;
32456             currentFlow = saveCurrentFlow;
32457         }
32458         // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
32459         // check for reserved words used as identifiers in strict mode code.
32460         function checkStrictModeIdentifier(node) {
32461             if (inStrictMode &&
32462                 node.originalKeywordKind >= 113 /* FirstFutureReservedWord */ &&
32463                 node.originalKeywordKind <= 121 /* LastFutureReservedWord */ &&
32464                 !ts.isIdentifierName(node) &&
32465                 !(node.flags & 8388608 /* Ambient */) &&
32466                 !(node.flags & 4194304 /* JSDoc */)) {
32467                 // Report error only if there are no parse errors in file
32468                 if (!file.parseDiagnostics.length) {
32469                     file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
32470                 }
32471             }
32472         }
32473         function getStrictModeIdentifierMessage(node) {
32474             // Provide specialized messages to help the user understand why we think they're in
32475             // strict mode.
32476             if (ts.getContainingClass(node)) {
32477                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
32478             }
32479             if (file.externalModuleIndicator) {
32480                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
32481             }
32482             return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
32483         }
32484         // The binder visits every node, so this is a good place to check for
32485         // the reserved private name (there is only one)
32486         function checkPrivateIdentifier(node) {
32487             if (node.escapedText === "#constructor") {
32488                 // Report error only if there are no parse errors in file
32489                 if (!file.parseDiagnostics.length) {
32490                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
32491                 }
32492             }
32493         }
32494         function checkStrictModeBinaryExpression(node) {
32495             if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
32496                 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32497                 // Assignment operator(11.13) or of a PostfixExpression(11.3)
32498                 checkStrictModeEvalOrArguments(node, node.left);
32499             }
32500         }
32501         function checkStrictModeCatchClause(node) {
32502             // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
32503             // Catch production is eval or arguments
32504             if (inStrictMode && node.variableDeclaration) {
32505                 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
32506             }
32507         }
32508         function checkStrictModeDeleteExpression(node) {
32509             // Grammar checking
32510             if (inStrictMode && node.expression.kind === 75 /* Identifier */) {
32511                 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
32512                 // UnaryExpression is a direct reference to a variable, function argument, or function name
32513                 var span = ts.getErrorSpanForNode(file, node.expression);
32514                 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
32515             }
32516         }
32517         function isEvalOrArgumentsIdentifier(node) {
32518             return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
32519         }
32520         function checkStrictModeEvalOrArguments(contextNode, name) {
32521             if (name && name.kind === 75 /* Identifier */) {
32522                 var identifier = name;
32523                 if (isEvalOrArgumentsIdentifier(identifier)) {
32524                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32525                     // otherwise report generic error message.
32526                     var span = ts.getErrorSpanForNode(file, name);
32527                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
32528                 }
32529             }
32530         }
32531         function getStrictModeEvalOrArgumentsMessage(node) {
32532             // Provide specialized messages to help the user understand why we think they're in
32533             // strict mode.
32534             if (ts.getContainingClass(node)) {
32535                 return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
32536             }
32537             if (file.externalModuleIndicator) {
32538                 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
32539             }
32540             return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
32541         }
32542         function checkStrictModeFunctionName(node) {
32543             if (inStrictMode) {
32544                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
32545                 checkStrictModeEvalOrArguments(node, node.name);
32546             }
32547         }
32548         function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
32549             // Provide specialized messages to help the user understand why we think they're in
32550             // strict mode.
32551             if (ts.getContainingClass(node)) {
32552                 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;
32553             }
32554             if (file.externalModuleIndicator) {
32555                 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
32556             }
32557             return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
32558         }
32559         function checkStrictModeFunctionDeclaration(node) {
32560             if (languageVersion < 2 /* ES2015 */) {
32561                 // Report error if function is not top level function declaration
32562                 if (blockScopeContainer.kind !== 290 /* SourceFile */ &&
32563                     blockScopeContainer.kind !== 249 /* ModuleDeclaration */ &&
32564                     !ts.isFunctionLike(blockScopeContainer)) {
32565                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32566                     // otherwise report generic error message.
32567                     var errorSpan = ts.getErrorSpanForNode(file, node);
32568                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
32569                 }
32570             }
32571         }
32572         function checkStrictModeNumericLiteral(node) {
32573             if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
32574                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
32575             }
32576         }
32577         function checkStrictModePostfixUnaryExpression(node) {
32578             // Grammar checking
32579             // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32580             // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
32581             // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
32582             if (inStrictMode) {
32583                 checkStrictModeEvalOrArguments(node, node.operand);
32584             }
32585         }
32586         function checkStrictModePrefixUnaryExpression(node) {
32587             // Grammar checking
32588             if (inStrictMode) {
32589                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
32590                     checkStrictModeEvalOrArguments(node, node.operand);
32591                 }
32592             }
32593         }
32594         function checkStrictModeWithStatement(node) {
32595             // Grammar checking for withStatement
32596             if (inStrictMode) {
32597                 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
32598             }
32599         }
32600         function checkStrictModeLabeledStatement(node) {
32601             // Grammar checking for labeledStatement
32602             if (inStrictMode && options.target >= 2 /* ES2015 */) {
32603                 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
32604                     errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
32605                 }
32606             }
32607         }
32608         function errorOnFirstToken(node, message, arg0, arg1, arg2) {
32609             var span = ts.getSpanOfTokenAtPosition(file, node.pos);
32610             file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
32611         }
32612         function errorOrSuggestionOnNode(isError, node, message) {
32613             errorOrSuggestionOnRange(isError, node, node, message);
32614         }
32615         function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
32616             addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
32617         }
32618         function addErrorOrSuggestionDiagnostic(isError, range, message) {
32619             var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
32620             if (isError) {
32621                 file.bindDiagnostics.push(diag);
32622             }
32623             else {
32624                 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
32625             }
32626         }
32627         function bind(node) {
32628             if (!node) {
32629                 return;
32630             }
32631             node.parent = parent;
32632             var saveInStrictMode = inStrictMode;
32633             // Even though in the AST the jsdoc @typedef node belongs to the current node,
32634             // its symbol might be in the same scope with the current node's symbol. Consider:
32635             //
32636             //     /** @typedef {string | number} MyType */
32637             //     function foo();
32638             //
32639             // Here the current node is "foo", which is a container, but the scope of "MyType" should
32640             // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
32641             // and skip binding this tag later when binding all the other jsdoc tags.
32642             // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
32643             // and then potentially add the symbol to an appropriate symbol table. Possible
32644             // destination symbol tables are:
32645             //
32646             //  1) The 'exports' table of the current container's symbol.
32647             //  2) The 'members' table of the current container's symbol.
32648             //  3) The 'locals' table of the current container.
32649             //
32650             // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
32651             // (like TypeLiterals for example) will not be put in any table.
32652             bindWorker(node);
32653             // Then we recurse into the children of the node to bind them as well. For certain
32654             // symbols we do specialized work when we recurse. For example, we'll keep track of
32655             // the current 'container' node when it changes. This helps us know which symbol table
32656             // a local should go into for example. Since terminal nodes are known not to have
32657             // children, as an optimization we don't process those.
32658             if (node.kind > 152 /* LastToken */) {
32659                 var saveParent = parent;
32660                 parent = node;
32661                 var containerFlags = getContainerFlags(node);
32662                 if (containerFlags === 0 /* None */) {
32663                     bindChildren(node);
32664                 }
32665                 else {
32666                     bindContainer(node, containerFlags);
32667                 }
32668                 parent = saveParent;
32669             }
32670             else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
32671                 subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
32672                 var saveParent = parent;
32673                 if (node.kind === 1 /* EndOfFileToken */)
32674                     parent = node;
32675                 bindJSDoc(node);
32676                 parent = saveParent;
32677             }
32678             inStrictMode = saveInStrictMode;
32679         }
32680         function bindJSDoc(node) {
32681             if (ts.hasJSDocNodes(node)) {
32682                 if (ts.isInJSFile(node)) {
32683                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
32684                         var j = _a[_i];
32685                         bind(j);
32686                     }
32687                 }
32688                 else {
32689                     for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
32690                         var j = _c[_b];
32691                         setParentPointers(node, j);
32692                     }
32693                 }
32694             }
32695         }
32696         function updateStrictModeStatementList(statements) {
32697             if (!inStrictMode) {
32698                 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
32699                     var statement = statements_2[_i];
32700                     if (!ts.isPrologueDirective(statement)) {
32701                         return;
32702                     }
32703                     if (isUseStrictPrologueDirective(statement)) {
32704                         inStrictMode = true;
32705                         return;
32706                     }
32707                 }
32708             }
32709         }
32710         /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
32711         function isUseStrictPrologueDirective(node) {
32712             var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
32713             // Note: the node text must be exactly "use strict" or 'use strict'.  It is not ok for the
32714             // string to contain unicode escapes (as per ES5).
32715             return nodeText === '"use strict"' || nodeText === "'use strict'";
32716         }
32717         function bindWorker(node) {
32718             switch (node.kind) {
32719                 /* Strict mode checks */
32720                 case 75 /* Identifier */:
32721                     // for typedef type names with namespaces, bind the new jsdoc type symbol here
32722                     // because it requires all containing namespaces to be in effect, namely the
32723                     // current "blockScopeContainer" needs to be set to its immediate namespace parent.
32724                     if (node.isInJSDocNamespace) {
32725                         var parentNode = node.parent;
32726                         while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
32727                             parentNode = parentNode.parent;
32728                         }
32729                         bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32730                         break;
32731                     }
32732                 // falls through
32733                 case 104 /* ThisKeyword */:
32734                     if (currentFlow && (ts.isExpression(node) || parent.kind === 282 /* ShorthandPropertyAssignment */)) {
32735                         node.flowNode = currentFlow;
32736                     }
32737                     return checkStrictModeIdentifier(node);
32738                 case 76 /* PrivateIdentifier */:
32739                     return checkPrivateIdentifier(node);
32740                 case 194 /* PropertyAccessExpression */:
32741                 case 195 /* ElementAccessExpression */:
32742                     var expr = node;
32743                     if (currentFlow && isNarrowableReference(expr)) {
32744                         expr.flowNode = currentFlow;
32745                     }
32746                     if (ts.isSpecialPropertyDeclaration(expr)) {
32747                         bindSpecialPropertyDeclaration(expr);
32748                     }
32749                     if (ts.isInJSFile(expr) &&
32750                         file.commonJsModuleIndicator &&
32751                         ts.isModuleExportsAccessExpression(expr) &&
32752                         !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
32753                         declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
32754                     }
32755                     break;
32756                 case 209 /* BinaryExpression */:
32757                     var specialKind = ts.getAssignmentDeclarationKind(node);
32758                     switch (specialKind) {
32759                         case 1 /* ExportsProperty */:
32760                             bindExportsPropertyAssignment(node);
32761                             break;
32762                         case 2 /* ModuleExports */:
32763                             bindModuleExportsAssignment(node);
32764                             break;
32765                         case 3 /* PrototypeProperty */:
32766                             bindPrototypePropertyAssignment(node.left, node);
32767                             break;
32768                         case 6 /* Prototype */:
32769                             bindPrototypeAssignment(node);
32770                             break;
32771                         case 4 /* ThisProperty */:
32772                             bindThisPropertyAssignment(node);
32773                             break;
32774                         case 5 /* Property */:
32775                             bindSpecialPropertyAssignment(node);
32776                             break;
32777                         case 0 /* None */:
32778                             // Nothing to do
32779                             break;
32780                         default:
32781                             ts.Debug.fail("Unknown binary expression special property assignment kind");
32782                     }
32783                     return checkStrictModeBinaryExpression(node);
32784                 case 280 /* CatchClause */:
32785                     return checkStrictModeCatchClause(node);
32786                 case 203 /* DeleteExpression */:
32787                     return checkStrictModeDeleteExpression(node);
32788                 case 8 /* NumericLiteral */:
32789                     return checkStrictModeNumericLiteral(node);
32790                 case 208 /* PostfixUnaryExpression */:
32791                     return checkStrictModePostfixUnaryExpression(node);
32792                 case 207 /* PrefixUnaryExpression */:
32793                     return checkStrictModePrefixUnaryExpression(node);
32794                 case 236 /* WithStatement */:
32795                     return checkStrictModeWithStatement(node);
32796                 case 238 /* LabeledStatement */:
32797                     return checkStrictModeLabeledStatement(node);
32798                 case 183 /* ThisType */:
32799                     seenThisKeyword = true;
32800                     return;
32801                 case 168 /* TypePredicate */:
32802                     break; // Binding the children will handle everything
32803                 case 155 /* TypeParameter */:
32804                     return bindTypeParameter(node);
32805                 case 156 /* Parameter */:
32806                     return bindParameter(node);
32807                 case 242 /* VariableDeclaration */:
32808                     return bindVariableDeclarationOrBindingElement(node);
32809                 case 191 /* BindingElement */:
32810                     node.flowNode = currentFlow;
32811                     return bindVariableDeclarationOrBindingElement(node);
32812                 case 159 /* PropertyDeclaration */:
32813                 case 158 /* PropertySignature */:
32814                     return bindPropertyWorker(node);
32815                 case 281 /* PropertyAssignment */:
32816                 case 282 /* ShorthandPropertyAssignment */:
32817                     return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
32818                 case 284 /* EnumMember */:
32819                     return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
32820                 case 165 /* CallSignature */:
32821                 case 166 /* ConstructSignature */:
32822                 case 167 /* IndexSignature */:
32823                     return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
32824                 case 161 /* MethodDeclaration */:
32825                 case 160 /* MethodSignature */:
32826                     // If this is an ObjectLiteralExpression method, then it sits in the same space
32827                     // as other properties in the object literal.  So we use SymbolFlags.PropertyExcludes
32828                     // so that it will conflict with any other object literal members with the same
32829                     // name.
32830                     return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
32831                 case 244 /* FunctionDeclaration */:
32832                     return bindFunctionDeclaration(node);
32833                 case 162 /* Constructor */:
32834                     return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
32835                 case 163 /* GetAccessor */:
32836                     return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
32837                 case 164 /* SetAccessor */:
32838                     return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
32839                 case 170 /* FunctionType */:
32840                 case 300 /* JSDocFunctionType */:
32841                 case 305 /* JSDocSignature */:
32842                 case 171 /* ConstructorType */:
32843                     return bindFunctionOrConstructorType(node);
32844                 case 173 /* TypeLiteral */:
32845                 case 304 /* JSDocTypeLiteral */:
32846                 case 186 /* MappedType */:
32847                     return bindAnonymousTypeWorker(node);
32848                 case 310 /* JSDocClassTag */:
32849                     return bindJSDocClassTag(node);
32850                 case 193 /* ObjectLiteralExpression */:
32851                     return bindObjectLiteralExpression(node);
32852                 case 201 /* FunctionExpression */:
32853                 case 202 /* ArrowFunction */:
32854                     return bindFunctionExpression(node);
32855                 case 196 /* CallExpression */:
32856                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
32857                     switch (assignmentKind) {
32858                         case 7 /* ObjectDefinePropertyValue */:
32859                             return bindObjectDefinePropertyAssignment(node);
32860                         case 8 /* ObjectDefinePropertyExports */:
32861                             return bindObjectDefinePropertyExport(node);
32862                         case 9 /* ObjectDefinePrototypeProperty */:
32863                             return bindObjectDefinePrototypeProperty(node);
32864                         case 0 /* None */:
32865                             break; // Nothing to do
32866                         default:
32867                             return ts.Debug.fail("Unknown call expression assignment declaration kind");
32868                     }
32869                     if (ts.isInJSFile(node)) {
32870                         bindCallExpression(node);
32871                     }
32872                     break;
32873                 // Members of classes, interfaces, and modules
32874                 case 214 /* ClassExpression */:
32875                 case 245 /* ClassDeclaration */:
32876                     // All classes are automatically in strict mode in ES6.
32877                     inStrictMode = true;
32878                     return bindClassLikeDeclaration(node);
32879                 case 246 /* InterfaceDeclaration */:
32880                     return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
32881                 case 247 /* TypeAliasDeclaration */:
32882                     return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32883                 case 248 /* EnumDeclaration */:
32884                     return bindEnumDeclaration(node);
32885                 case 249 /* ModuleDeclaration */:
32886                     return bindModuleDeclaration(node);
32887                 // Jsx-attributes
32888                 case 274 /* JsxAttributes */:
32889                     return bindJsxAttributes(node);
32890                 case 273 /* JsxAttribute */:
32891                     return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
32892                 // Imports and exports
32893                 case 253 /* ImportEqualsDeclaration */:
32894                 case 256 /* NamespaceImport */:
32895                 case 258 /* ImportSpecifier */:
32896                 case 263 /* ExportSpecifier */:
32897                     return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
32898                 case 252 /* NamespaceExportDeclaration */:
32899                     return bindNamespaceExportDeclaration(node);
32900                 case 255 /* ImportClause */:
32901                     return bindImportClause(node);
32902                 case 260 /* ExportDeclaration */:
32903                     return bindExportDeclaration(node);
32904                 case 259 /* ExportAssignment */:
32905                     return bindExportAssignment(node);
32906                 case 290 /* SourceFile */:
32907                     updateStrictModeStatementList(node.statements);
32908                     return bindSourceFileIfExternalModule();
32909                 case 223 /* Block */:
32910                     if (!ts.isFunctionLike(node.parent)) {
32911                         return;
32912                     }
32913                 // falls through
32914                 case 250 /* ModuleBlock */:
32915                     return updateStrictModeStatementList(node.statements);
32916                 case 317 /* JSDocParameterTag */:
32917                     if (node.parent.kind === 305 /* JSDocSignature */) {
32918                         return bindParameter(node);
32919                     }
32920                     if (node.parent.kind !== 304 /* JSDocTypeLiteral */) {
32921                         break;
32922                     }
32923                 // falls through
32924                 case 323 /* JSDocPropertyTag */:
32925                     var propTag = node;
32926                     var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 299 /* JSDocOptionalType */ ?
32927                         4 /* Property */ | 16777216 /* Optional */ :
32928                         4 /* Property */;
32929                     return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
32930                 case 322 /* JSDocTypedefTag */:
32931                 case 315 /* JSDocCallbackTag */:
32932                 case 316 /* JSDocEnumTag */:
32933                     return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
32934             }
32935         }
32936         function bindPropertyWorker(node) {
32937             return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
32938         }
32939         function bindAnonymousTypeWorker(node) {
32940             return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
32941         }
32942         function bindSourceFileIfExternalModule() {
32943             setExportContextFlag(file);
32944             if (ts.isExternalModule(file)) {
32945                 bindSourceFileAsExternalModule();
32946             }
32947             else if (ts.isJsonSourceFile(file)) {
32948                 bindSourceFileAsExternalModule();
32949                 // Create symbol equivalent for the module.exports = {}
32950                 var originalSymbol = file.symbol;
32951                 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
32952                 file.symbol = originalSymbol;
32953             }
32954         }
32955         function bindSourceFileAsExternalModule() {
32956             bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
32957         }
32958         function bindExportAssignment(node) {
32959             if (!container.symbol || !container.symbol.exports) {
32960                 // Export assignment in some sort of block construct
32961                 bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
32962             }
32963             else {
32964                 var flags = ts.exportAssignmentIsAlias(node)
32965                     // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
32966                     ? 2097152 /* Alias */
32967                     // An export default clause with any other expression exports a value
32968                     : 4 /* Property */;
32969                 // If there is an `export default x;` alias declaration, can't `export default` anything else.
32970                 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
32971                 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
32972                 if (node.isExportEquals) {
32973                     // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
32974                     ts.setValueDeclaration(symbol, node);
32975                 }
32976             }
32977         }
32978         function bindNamespaceExportDeclaration(node) {
32979             if (node.modifiers && node.modifiers.length) {
32980                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
32981             }
32982             var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
32983                 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
32984                     : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
32985                         : undefined;
32986             if (diag) {
32987                 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
32988             }
32989             else {
32990                 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
32991                 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
32992             }
32993         }
32994         function bindExportDeclaration(node) {
32995             if (!container.symbol || !container.symbol.exports) {
32996                 // Export * in some sort of block construct
32997                 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
32998             }
32999             else if (!node.exportClause) {
33000                 // All export * declarations are collected in an __export symbol
33001                 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
33002             }
33003             else if (ts.isNamespaceExport(node.exportClause)) {
33004                 // declareSymbol walks up parents to find name text, parent _must_ be set
33005                 // but won't be set by the normal binder walk until `bindChildren` later on.
33006                 node.exportClause.parent = node;
33007                 declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33008             }
33009         }
33010         function bindImportClause(node) {
33011             if (node.name) {
33012                 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33013             }
33014         }
33015         function setCommonJsModuleIndicator(node) {
33016             if (file.externalModuleIndicator) {
33017                 return false;
33018             }
33019             if (!file.commonJsModuleIndicator) {
33020                 file.commonJsModuleIndicator = node;
33021                 bindSourceFileAsExternalModule();
33022             }
33023             return true;
33024         }
33025         function bindObjectDefinePropertyExport(node) {
33026             if (!setCommonJsModuleIndicator(node)) {
33027                 return;
33028             }
33029             var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
33030                 if (symbol) {
33031                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33032                 }
33033                 return symbol;
33034             });
33035             if (symbol) {
33036                 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
33037                 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
33038             }
33039         }
33040         function bindExportsPropertyAssignment(node) {
33041             // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
33042             // expression is the declaration
33043             if (!setCommonJsModuleIndicator(node)) {
33044                 return;
33045             }
33046             var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
33047                 if (symbol) {
33048                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33049                 }
33050                 return symbol;
33051             });
33052             if (symbol) {
33053                 var flags = ts.isClassExpression(node.right) ?
33054                     4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ :
33055                     4 /* Property */ | 1048576 /* ExportValue */;
33056                 declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
33057             }
33058         }
33059         function bindModuleExportsAssignment(node) {
33060             // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
33061             // is still pointing to 'module.exports'.
33062             // We do not want to consider this as 'export=' since a module can have only one of these.
33063             // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
33064             if (!setCommonJsModuleIndicator(node)) {
33065                 return;
33066             }
33067             var assignedExpression = ts.getRightMostAssignedExpression(node.right);
33068             if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
33069                 return;
33070             }
33071             // 'module.exports = expr' assignment
33072             var flags = ts.exportAssignmentIsAlias(node)
33073                 ? 2097152 /* Alias */
33074                 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
33075             var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
33076             ts.setValueDeclaration(symbol, node);
33077         }
33078         function bindThisPropertyAssignment(node) {
33079             ts.Debug.assert(ts.isInJSFile(node));
33080             // private identifiers *must* be declared (even in JS files)
33081             var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
33082                 || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
33083             if (hasPrivateIdentifier) {
33084                 return;
33085             }
33086             var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
33087             switch (thisContainer.kind) {
33088                 case 244 /* FunctionDeclaration */:
33089                 case 201 /* FunctionExpression */:
33090                     var constructorSymbol = thisContainer.symbol;
33091                     // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
33092                     if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
33093                         var l = thisContainer.parent.left;
33094                         if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
33095                             constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
33096                         }
33097                     }
33098                     if (constructorSymbol && constructorSymbol.valueDeclaration) {
33099                         // Declare a 'member' if the container is an ES5 class or ES6 constructor
33100                         constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
33101                         // It's acceptable for multiple 'this' assignments of the same identifier to occur
33102                         if (ts.hasDynamicName(node)) {
33103                             bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
33104                         }
33105                         else {
33106                             declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
33107                         }
33108                         addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
33109                     }
33110                     break;
33111                 case 162 /* Constructor */:
33112                 case 159 /* PropertyDeclaration */:
33113                 case 161 /* MethodDeclaration */:
33114                 case 163 /* GetAccessor */:
33115                 case 164 /* SetAccessor */:
33116                     // this.foo assignment in a JavaScript class
33117                     // Bind this property to the containing class
33118                     var containingClass = thisContainer.parent;
33119                     var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
33120                     if (ts.hasDynamicName(node)) {
33121                         bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
33122                     }
33123                     else {
33124                         declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
33125                     }
33126                     break;
33127                 case 290 /* SourceFile */:
33128                     // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
33129                     if (ts.hasDynamicName(node)) {
33130                         break;
33131                     }
33132                     else if (thisContainer.commonJsModuleIndicator) {
33133                         declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
33134                     }
33135                     else {
33136                         declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33137                     }
33138                     break;
33139                 default:
33140                     ts.Debug.failBadSyntaxKind(thisContainer);
33141             }
33142         }
33143         function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
33144             bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
33145             addLateBoundAssignmentDeclarationToSymbol(node, symbol);
33146         }
33147         function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
33148             if (symbol) {
33149                 var members = symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = ts.createMap());
33150                 members.set("" + ts.getNodeId(node), node);
33151             }
33152         }
33153         function bindSpecialPropertyDeclaration(node) {
33154             if (node.expression.kind === 104 /* ThisKeyword */) {
33155                 bindThisPropertyAssignment(node);
33156             }
33157             else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 290 /* SourceFile */) {
33158                 if (ts.isPrototypeAccess(node.expression)) {
33159                     bindPrototypePropertyAssignment(node, node.parent);
33160                 }
33161                 else {
33162                     bindStaticPropertyAssignment(node);
33163                 }
33164             }
33165         }
33166         /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
33167         function bindPrototypeAssignment(node) {
33168             node.left.parent = node;
33169             node.right.parent = node;
33170             bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
33171         }
33172         function bindObjectDefinePrototypeProperty(node) {
33173             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
33174             if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
33175                 // Ensure the namespace symbol becomes class-like
33176                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33177             }
33178             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
33179         }
33180         /**
33181          * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
33182          * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
33183          */
33184         function bindPrototypePropertyAssignment(lhs, parent) {
33185             // Look up the function in the local scope, since prototype assignments should
33186             // follow the function declaration
33187             var classPrototype = lhs.expression;
33188             var constructorFunction = classPrototype.expression;
33189             // Fix up parent pointers since we're going to use these nodes before we bind into them
33190             lhs.parent = parent;
33191             constructorFunction.parent = classPrototype;
33192             classPrototype.parent = lhs;
33193             bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
33194         }
33195         function bindObjectDefinePropertyAssignment(node) {
33196             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
33197             var isToplevel = node.parent.parent.kind === 290 /* SourceFile */;
33198             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33199             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
33200         }
33201         function bindSpecialPropertyAssignment(node) {
33202             // Class declarations in Typescript do not allow property declarations
33203             var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression);
33204             if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
33205                 return;
33206             }
33207             // Fix up parent pointers since we're going to use these nodes before we bind into them
33208             node.left.parent = node;
33209             node.right.parent = node;
33210             if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
33211                 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
33212                 //    var util = module.exports;
33213                 //    util.property = function ...
33214                 bindExportsPropertyAssignment(node);
33215             }
33216             else if (ts.hasDynamicName(node)) {
33217                 bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
33218                 var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
33219                 addLateBoundAssignmentDeclarationToSymbol(node, sym);
33220             }
33221             else {
33222                 bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
33223             }
33224         }
33225         /**
33226          * 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.
33227          * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
33228          */
33229         function bindStaticPropertyAssignment(node) {
33230             ts.Debug.assert(!ts.isIdentifier(node));
33231             node.expression.parent = node;
33232             bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33233         }
33234         function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
33235             if (isToplevel && !isPrototypeProperty) {
33236                 // make symbols or add declarations for intermediate containers
33237                 var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */;
33238                 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
33239                 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
33240                     if (symbol) {
33241                         addDeclarationToSymbol(symbol, id, flags_1);
33242                         return symbol;
33243                     }
33244                     else {
33245                         var table = parent ? parent.exports :
33246                             file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
33247                         return declareSymbol(table, parent, id, flags_1, excludeFlags_1);
33248                     }
33249                 });
33250             }
33251             if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
33252                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33253             }
33254             return namespaceSymbol;
33255         }
33256         function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
33257             if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
33258                 return;
33259             }
33260             // Set up the members collection if it doesn't exist already
33261             var symbolTable = isPrototypeProperty ?
33262                 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
33263                 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
33264             var includes = 0 /* None */;
33265             var excludes = 0 /* None */;
33266             // Method-like
33267             if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
33268                 includes = 8192 /* Method */;
33269                 excludes = 103359 /* MethodExcludes */;
33270             }
33271             // Maybe accessor-like
33272             else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
33273                 if (ts.some(declaration.arguments[2].properties, function (p) {
33274                     var id = ts.getNameOfDeclaration(p);
33275                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
33276                 })) {
33277                     // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
33278                     // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
33279                     includes |= 65536 /* SetAccessor */ | 4 /* Property */;
33280                     excludes |= 78783 /* SetAccessorExcludes */;
33281                 }
33282                 if (ts.some(declaration.arguments[2].properties, function (p) {
33283                     var id = ts.getNameOfDeclaration(p);
33284                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
33285                 })) {
33286                     includes |= 32768 /* GetAccessor */ | 4 /* Property */;
33287                     excludes |= 46015 /* GetAccessorExcludes */;
33288                 }
33289             }
33290             if (includes === 0 /* None */) {
33291                 includes = 4 /* Property */;
33292                 excludes = 0 /* PropertyExcludes */;
33293             }
33294             declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
33295         }
33296         function isTopLevelNamespaceAssignment(propertyAccess) {
33297             return ts.isBinaryExpression(propertyAccess.parent)
33298                 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 290 /* SourceFile */
33299                 : propertyAccess.parent.parent.kind === 290 /* SourceFile */;
33300         }
33301         function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
33302             var namespaceSymbol = lookupSymbolForPropertyAccess(name);
33303             var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
33304             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
33305             bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
33306         }
33307         /**
33308          * Javascript expando values are:
33309          * - Functions
33310          * - classes
33311          * - namespaces
33312          * - variables initialized with function expressions
33313          * -                       with class expressions
33314          * -                       with empty object literals
33315          * -                       with non-empty object literals if assigned to the prototype property
33316          */
33317         function isExpandoSymbol(symbol) {
33318             if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
33319                 return true;
33320             }
33321             var node = symbol.valueDeclaration;
33322             if (node && ts.isCallExpression(node)) {
33323                 return !!ts.getAssignedExpandoInitializer(node);
33324             }
33325             var init = !node ? undefined :
33326                 ts.isVariableDeclaration(node) ? node.initializer :
33327                     ts.isBinaryExpression(node) ? node.right :
33328                         ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
33329                             undefined;
33330             init = init && ts.getRightMostAssignedExpression(init);
33331             if (init) {
33332                 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
33333                 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
33334             }
33335             return false;
33336         }
33337         function getParentOfBinaryExpression(expr) {
33338             while (ts.isBinaryExpression(expr.parent)) {
33339                 expr = expr.parent;
33340             }
33341             return expr.parent;
33342         }
33343         function lookupSymbolForPropertyAccess(node, lookupContainer) {
33344             if (lookupContainer === void 0) { lookupContainer = container; }
33345             if (ts.isIdentifier(node)) {
33346                 return lookupSymbolForNameWorker(lookupContainer, node.escapedText);
33347             }
33348             else {
33349                 var symbol = lookupSymbolForPropertyAccess(node.expression);
33350                 return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
33351             }
33352         }
33353         function forEachIdentifierInEntityName(e, parent, action) {
33354             if (isExportsOrModuleExportsOrAlias(file, e)) {
33355                 return file.symbol;
33356             }
33357             else if (ts.isIdentifier(e)) {
33358                 return action(e, lookupSymbolForPropertyAccess(e), parent);
33359             }
33360             else {
33361                 var s = forEachIdentifierInEntityName(e.expression, parent, action);
33362                 var name = ts.getNameOrArgument(e);
33363                 // unreachable
33364                 if (ts.isPrivateIdentifier(name)) {
33365                     ts.Debug.fail("unexpected PrivateIdentifier");
33366                 }
33367                 return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
33368             }
33369         }
33370         function bindCallExpression(node) {
33371             // We're only inspecting call expressions to detect CommonJS modules, so we can skip
33372             // this check if we've already seen the module indicator
33373             if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
33374                 setCommonJsModuleIndicator(node);
33375             }
33376         }
33377         function bindClassLikeDeclaration(node) {
33378             if (node.kind === 245 /* ClassDeclaration */) {
33379                 bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
33380             }
33381             else {
33382                 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
33383                 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
33384                 // Add name of class expression into the map for semantic classifier
33385                 if (node.name) {
33386                     classifiableNames.set(node.name.escapedText, true);
33387                 }
33388             }
33389             var symbol = node.symbol;
33390             // TypeScript 1.0 spec (April 2014): 8.4
33391             // Every class automatically contains a static property member named 'prototype', the
33392             // type of which is an instantiation of the class type with type Any supplied as a type
33393             // argument for each type parameter. It is an error to explicitly declare a static
33394             // property member with the name 'prototype'.
33395             //
33396             // Note: we check for this here because this class may be merging into a module.  The
33397             // module might have an exported variable called 'prototype'.  We can't allow that as
33398             // that would clash with the built-in 'prototype' for the class.
33399             var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
33400             var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
33401             if (symbolExport) {
33402                 if (node.name) {
33403                     node.name.parent = node;
33404                 }
33405                 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
33406             }
33407             symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
33408             prototypeSymbol.parent = symbol;
33409         }
33410         function bindEnumDeclaration(node) {
33411             return ts.isEnumConst(node)
33412                 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
33413                 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
33414         }
33415         function bindVariableDeclarationOrBindingElement(node) {
33416             if (inStrictMode) {
33417                 checkStrictModeEvalOrArguments(node, node.name);
33418             }
33419             if (!ts.isBindingPattern(node.name)) {
33420                 if (ts.isBlockOrCatchScoped(node)) {
33421                     bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
33422                 }
33423                 else if (ts.isParameterDeclaration(node)) {
33424                     // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
33425                     // because its parent chain has already been set up, since parents are set before descending into children.
33426                     //
33427                     // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
33428                     // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
33429                     // For example:
33430                     //      function foo([a,a]) {} // Duplicate Identifier error
33431                     //      function bar(a,a) {}   // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
33432                     //                             // which correctly set excluded symbols
33433                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33434                 }
33435                 else {
33436                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33437                 }
33438             }
33439         }
33440         function bindParameter(node) {
33441             if (node.kind === 317 /* JSDocParameterTag */ && container.kind !== 305 /* JSDocSignature */) {
33442                 return;
33443             }
33444             if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
33445                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
33446                 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
33447                 checkStrictModeEvalOrArguments(node, node.name);
33448             }
33449             if (ts.isBindingPattern(node.name)) {
33450                 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
33451             }
33452             else {
33453                 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33454             }
33455             // If this is a property-parameter, then also declare the property symbol into the
33456             // containing class.
33457             if (ts.isParameterPropertyDeclaration(node, node.parent)) {
33458                 var classDeclaration = node.parent.parent;
33459                 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
33460             }
33461         }
33462         function bindFunctionDeclaration(node) {
33463             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33464                 if (ts.isAsyncFunction(node)) {
33465                     emitFlags |= 2048 /* HasAsyncFunctions */;
33466                 }
33467             }
33468             checkStrictModeFunctionName(node);
33469             if (inStrictMode) {
33470                 checkStrictModeFunctionDeclaration(node);
33471                 bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33472             }
33473             else {
33474                 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33475             }
33476         }
33477         function bindFunctionExpression(node) {
33478             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33479                 if (ts.isAsyncFunction(node)) {
33480                     emitFlags |= 2048 /* HasAsyncFunctions */;
33481                 }
33482             }
33483             if (currentFlow) {
33484                 node.flowNode = currentFlow;
33485             }
33486             checkStrictModeFunctionName(node);
33487             var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
33488             return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
33489         }
33490         function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
33491             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
33492                 emitFlags |= 2048 /* HasAsyncFunctions */;
33493             }
33494             if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
33495                 node.flowNode = currentFlow;
33496             }
33497             return ts.hasDynamicName(node)
33498                 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
33499                 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
33500         }
33501         function getInferTypeContainer(node) {
33502             var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
33503             return extendsType && extendsType.parent;
33504         }
33505         function bindTypeParameter(node) {
33506             if (ts.isJSDocTemplateTag(node.parent)) {
33507                 var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
33508                 if (container_1) {
33509                     if (!container_1.locals) {
33510                         container_1.locals = ts.createSymbolTable();
33511                     }
33512                     declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33513                 }
33514                 else {
33515                     declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33516                 }
33517             }
33518             else if (node.parent.kind === 181 /* InferType */) {
33519                 var container_2 = getInferTypeContainer(node.parent);
33520                 if (container_2) {
33521                     if (!container_2.locals) {
33522                         container_2.locals = ts.createSymbolTable();
33523                     }
33524                     declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33525                 }
33526                 else {
33527                     bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
33528                 }
33529             }
33530             else {
33531                 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33532             }
33533         }
33534         // reachability checks
33535         function shouldReportErrorOnModuleDeclaration(node) {
33536             var instanceState = getModuleInstanceState(node);
33537             return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
33538         }
33539         function checkUnreachable(node) {
33540             if (!(currentFlow.flags & 1 /* Unreachable */)) {
33541                 return false;
33542             }
33543             if (currentFlow === unreachableFlow) {
33544                 var reportError = 
33545                 // report error on all statements except empty ones
33546                 (ts.isStatementButNotDeclaration(node) && node.kind !== 224 /* EmptyStatement */) ||
33547                     // report error on class declarations
33548                     node.kind === 245 /* ClassDeclaration */ ||
33549                     // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
33550                     (node.kind === 249 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
33551                 if (reportError) {
33552                     currentFlow = reportedUnreachableFlow;
33553                     if (!options.allowUnreachableCode) {
33554                         // unreachable code is reported if
33555                         // - user has explicitly asked about it AND
33556                         // - statement is in not ambient context (statements in ambient context is already an error
33557                         //   so we should not report extras) AND
33558                         //   - node is not variable statement OR
33559                         //   - node is block scoped variable statement OR
33560                         //   - node is not block scoped variable statement and at least one variable declaration has initializer
33561                         //   Rationale: we don't want to report errors on non-initialized var's since they are hoisted
33562                         //   On the other side we do want to report errors on non-initialized 'lets' because of TDZ
33563                         var isError_1 = ts.unreachableCodeIsError(options) &&
33564                             !(node.flags & 8388608 /* Ambient */) &&
33565                             (!ts.isVariableStatement(node) ||
33566                                 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
33567                                 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
33568                         eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
33569                     }
33570                 }
33571             }
33572             return true;
33573         }
33574     }
33575     function eachUnreachableRange(node, cb) {
33576         if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
33577             var statements = node.parent.statements;
33578             var slice_1 = ts.sliceAfter(statements, node);
33579             ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
33580         }
33581         else {
33582             cb(node, node);
33583         }
33584     }
33585     // As opposed to a pure declaration like an `interface`
33586     function isExecutableStatement(s) {
33587         // Don't remove statements that can validly be used before they appear.
33588         return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
33589             // `var x;` may declare a variable used above
33590             !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
33591     }
33592     function isPurelyTypeDeclaration(s) {
33593         switch (s.kind) {
33594             case 246 /* InterfaceDeclaration */:
33595             case 247 /* TypeAliasDeclaration */:
33596                 return true;
33597             case 249 /* ModuleDeclaration */:
33598                 return getModuleInstanceState(s) !== 1 /* Instantiated */;
33599             case 248 /* EnumDeclaration */:
33600                 return ts.hasModifier(s, 2048 /* Const */);
33601             default:
33602                 return false;
33603         }
33604     }
33605     function isExportsOrModuleExportsOrAlias(sourceFile, node) {
33606         var i = 0;
33607         var q = [node];
33608         while (q.length && i < 100) {
33609             i++;
33610             node = q.shift();
33611             if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
33612                 return true;
33613             }
33614             else if (ts.isIdentifier(node)) {
33615                 var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
33616                 if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
33617                     var init = symbol.valueDeclaration.initializer;
33618                     q.push(init);
33619                     if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
33620                         q.push(init.left);
33621                         q.push(init.right);
33622                     }
33623                 }
33624             }
33625         }
33626         return false;
33627     }
33628     ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
33629     function lookupSymbolForNameWorker(container, name) {
33630         var local = container.locals && container.locals.get(name);
33631         if (local) {
33632             return local.exportSymbol || local;
33633         }
33634         if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
33635             return container.jsGlobalAugmentations.get(name);
33636         }
33637         return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
33638     }
33639     /**
33640      * Computes the transform flags for a node, given the transform flags of its subtree
33641      *
33642      * @param node The node to analyze
33643      * @param subtreeFlags Transform flags computed for this node's subtree
33644      */
33645     function computeTransformFlagsForNode(node, subtreeFlags) {
33646         var kind = node.kind;
33647         switch (kind) {
33648             case 196 /* CallExpression */:
33649                 return computeCallExpression(node, subtreeFlags);
33650             case 197 /* NewExpression */:
33651                 return computeNewExpression(node, subtreeFlags);
33652             case 249 /* ModuleDeclaration */:
33653                 return computeModuleDeclaration(node, subtreeFlags);
33654             case 200 /* ParenthesizedExpression */:
33655                 return computeParenthesizedExpression(node, subtreeFlags);
33656             case 209 /* BinaryExpression */:
33657                 return computeBinaryExpression(node, subtreeFlags);
33658             case 226 /* ExpressionStatement */:
33659                 return computeExpressionStatement(node, subtreeFlags);
33660             case 156 /* Parameter */:
33661                 return computeParameter(node, subtreeFlags);
33662             case 202 /* ArrowFunction */:
33663                 return computeArrowFunction(node, subtreeFlags);
33664             case 201 /* FunctionExpression */:
33665                 return computeFunctionExpression(node, subtreeFlags);
33666             case 244 /* FunctionDeclaration */:
33667                 return computeFunctionDeclaration(node, subtreeFlags);
33668             case 242 /* VariableDeclaration */:
33669                 return computeVariableDeclaration(node, subtreeFlags);
33670             case 243 /* VariableDeclarationList */:
33671                 return computeVariableDeclarationList(node, subtreeFlags);
33672             case 225 /* VariableStatement */:
33673                 return computeVariableStatement(node, subtreeFlags);
33674             case 238 /* LabeledStatement */:
33675                 return computeLabeledStatement(node, subtreeFlags);
33676             case 245 /* ClassDeclaration */:
33677                 return computeClassDeclaration(node, subtreeFlags);
33678             case 214 /* ClassExpression */:
33679                 return computeClassExpression(node, subtreeFlags);
33680             case 279 /* HeritageClause */:
33681                 return computeHeritageClause(node, subtreeFlags);
33682             case 280 /* CatchClause */:
33683                 return computeCatchClause(node, subtreeFlags);
33684             case 216 /* ExpressionWithTypeArguments */:
33685                 return computeExpressionWithTypeArguments(node, subtreeFlags);
33686             case 162 /* Constructor */:
33687                 return computeConstructor(node, subtreeFlags);
33688             case 159 /* PropertyDeclaration */:
33689                 return computePropertyDeclaration(node, subtreeFlags);
33690             case 161 /* MethodDeclaration */:
33691                 return computeMethod(node, subtreeFlags);
33692             case 163 /* GetAccessor */:
33693             case 164 /* SetAccessor */:
33694                 return computeAccessor(node, subtreeFlags);
33695             case 253 /* ImportEqualsDeclaration */:
33696                 return computeImportEquals(node, subtreeFlags);
33697             case 194 /* PropertyAccessExpression */:
33698                 return computePropertyAccess(node, subtreeFlags);
33699             case 195 /* ElementAccessExpression */:
33700                 return computeElementAccess(node, subtreeFlags);
33701             case 267 /* JsxSelfClosingElement */:
33702             case 268 /* JsxOpeningElement */:
33703                 return computeJsxOpeningLikeElement(node, subtreeFlags);
33704             default:
33705                 return computeOther(node, kind, subtreeFlags);
33706         }
33707     }
33708     ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
33709     function computeCallExpression(node, subtreeFlags) {
33710         var transformFlags = subtreeFlags;
33711         var callee = ts.skipOuterExpressions(node.expression);
33712         var expression = node.expression;
33713         if (node.flags & 32 /* OptionalChain */) {
33714             transformFlags |= 8 /* ContainsES2020 */;
33715         }
33716         if (node.typeArguments) {
33717             transformFlags |= 1 /* AssertTypeScript */;
33718         }
33719         if (subtreeFlags & 8192 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
33720             // If the this node contains a SpreadExpression, or is a super call, then it is an ES6
33721             // node.
33722             transformFlags |= 256 /* AssertES2015 */;
33723             if (ts.isSuperProperty(callee)) {
33724                 transformFlags |= 4096 /* ContainsLexicalThis */;
33725             }
33726         }
33727         if (expression.kind === 96 /* ImportKeyword */) {
33728             transformFlags |= 2097152 /* ContainsDynamicImport */;
33729         }
33730         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33731         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33732     }
33733     function computeNewExpression(node, subtreeFlags) {
33734         var transformFlags = subtreeFlags;
33735         if (node.typeArguments) {
33736             transformFlags |= 1 /* AssertTypeScript */;
33737         }
33738         if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
33739             // If the this node contains a SpreadElementExpression then it is an ES6
33740             // node.
33741             transformFlags |= 256 /* AssertES2015 */;
33742         }
33743         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33744         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33745     }
33746     function computeJsxOpeningLikeElement(node, subtreeFlags) {
33747         var transformFlags = subtreeFlags | 2 /* AssertJsx */;
33748         if (node.typeArguments) {
33749             transformFlags |= 1 /* AssertTypeScript */;
33750         }
33751         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33752         return transformFlags & ~536870912 /* NodeExcludes */;
33753     }
33754     function computeBinaryExpression(node, subtreeFlags) {
33755         var transformFlags = subtreeFlags;
33756         var operatorTokenKind = node.operatorToken.kind;
33757         var leftKind = node.left.kind;
33758         if (operatorTokenKind === 60 /* QuestionQuestionToken */) {
33759             transformFlags |= 8 /* AssertES2020 */;
33760         }
33761         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 193 /* ObjectLiteralExpression */) {
33762             // Destructuring object assignments with are ES2015 syntax
33763             // and possibly ES2018 if they contain rest
33764             transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33765         }
33766         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 192 /* ArrayLiteralExpression */) {
33767             // Destructuring assignments are ES2015 syntax.
33768             transformFlags |= 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33769         }
33770         else if (operatorTokenKind === 42 /* AsteriskAsteriskToken */
33771             || operatorTokenKind === 66 /* AsteriskAsteriskEqualsToken */) {
33772             // Exponentiation is ES2016 syntax.
33773             transformFlags |= 128 /* AssertES2016 */;
33774         }
33775         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33776         return transformFlags & ~536870912 /* NodeExcludes */;
33777     }
33778     function computeParameter(node, subtreeFlags) {
33779         var transformFlags = subtreeFlags;
33780         var name = node.name;
33781         var initializer = node.initializer;
33782         var dotDotDotToken = node.dotDotDotToken;
33783         // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
33784         // syntax.
33785         if (node.questionToken
33786             || node.type
33787             || (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
33788             || ts.isThisIdentifier(name)) {
33789             transformFlags |= 1 /* AssertTypeScript */;
33790         }
33791         // If a parameter has an accessibility modifier, then it is TypeScript syntax.
33792         if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
33793             transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
33794         }
33795         // parameters with object rest destructuring are ES2018 syntax
33796         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33797             transformFlags |= 32 /* AssertES2018 */;
33798         }
33799         // If a parameter has an initializer, a binding pattern or a dotDotDot token, then
33800         // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
33801         if (subtreeFlags & 131072 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
33802             transformFlags |= 256 /* AssertES2015 */;
33803         }
33804         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33805         return transformFlags & ~536870912 /* ParameterExcludes */;
33806     }
33807     function computeParenthesizedExpression(node, subtreeFlags) {
33808         var transformFlags = subtreeFlags;
33809         var expression = node.expression;
33810         var expressionKind = expression.kind;
33811         // If the node is synthesized, it means the emitter put the parentheses there,
33812         // not the user. If we didn't want them, the emitter would not have put them
33813         // there.
33814         if (expressionKind === 217 /* AsExpression */
33815             || expressionKind === 199 /* TypeAssertionExpression */) {
33816             transformFlags |= 1 /* AssertTypeScript */;
33817         }
33818         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33819         return transformFlags & ~536870912 /* OuterExpressionExcludes */;
33820     }
33821     function computeClassDeclaration(node, subtreeFlags) {
33822         var transformFlags;
33823         if (ts.hasModifier(node, 2 /* Ambient */)) {
33824             // An ambient declaration is TypeScript syntax.
33825             transformFlags = 1 /* AssertTypeScript */;
33826         }
33827         else {
33828             // A ClassDeclaration is ES6 syntax.
33829             transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33830             // A class with a parameter property assignment or decorator is TypeScript syntax.
33831             // An exported declaration may be TypeScript syntax, but is handled by the visitor
33832             // for a namespace declaration.
33833             if ((subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */)
33834                 || node.typeParameters) {
33835                 transformFlags |= 1 /* AssertTypeScript */;
33836             }
33837         }
33838         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33839         return transformFlags & ~536905728 /* ClassExcludes */;
33840     }
33841     function computeClassExpression(node, subtreeFlags) {
33842         // A ClassExpression is ES6 syntax.
33843         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33844         // A class with a parameter property assignment or decorator is TypeScript syntax.
33845         if (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */
33846             || node.typeParameters) {
33847             transformFlags |= 1 /* AssertTypeScript */;
33848         }
33849         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33850         return transformFlags & ~536905728 /* ClassExcludes */;
33851     }
33852     function computeHeritageClause(node, subtreeFlags) {
33853         var transformFlags = subtreeFlags;
33854         switch (node.token) {
33855             case 90 /* ExtendsKeyword */:
33856                 // An `extends` HeritageClause is ES6 syntax.
33857                 transformFlags |= 256 /* AssertES2015 */;
33858                 break;
33859             case 113 /* ImplementsKeyword */:
33860                 // An `implements` HeritageClause is TypeScript syntax.
33861                 transformFlags |= 1 /* AssertTypeScript */;
33862                 break;
33863             default:
33864                 ts.Debug.fail("Unexpected token for heritage clause");
33865                 break;
33866         }
33867         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33868         return transformFlags & ~536870912 /* NodeExcludes */;
33869     }
33870     function computeCatchClause(node, subtreeFlags) {
33871         var transformFlags = subtreeFlags;
33872         if (!node.variableDeclaration) {
33873             transformFlags |= 16 /* AssertES2019 */;
33874         }
33875         else if (ts.isBindingPattern(node.variableDeclaration.name)) {
33876             transformFlags |= 256 /* AssertES2015 */;
33877         }
33878         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33879         return transformFlags & ~536887296 /* CatchClauseExcludes */;
33880     }
33881     function computeExpressionWithTypeArguments(node, subtreeFlags) {
33882         // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
33883         // extends clause of a class.
33884         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33885         // If an ExpressionWithTypeArguments contains type arguments, then it
33886         // is TypeScript syntax.
33887         if (node.typeArguments) {
33888             transformFlags |= 1 /* AssertTypeScript */;
33889         }
33890         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33891         return transformFlags & ~536870912 /* NodeExcludes */;
33892     }
33893     function computeConstructor(node, subtreeFlags) {
33894         var transformFlags = subtreeFlags;
33895         // TypeScript-specific modifiers and overloads are TypeScript syntax
33896         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33897             || !node.body) {
33898             transformFlags |= 1 /* AssertTypeScript */;
33899         }
33900         // function declarations with object rest destructuring are ES2018 syntax
33901         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33902             transformFlags |= 32 /* AssertES2018 */;
33903         }
33904         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33905         return transformFlags & ~538923008 /* ConstructorExcludes */;
33906     }
33907     function computeMethod(node, subtreeFlags) {
33908         // A MethodDeclaration is ES6 syntax.
33909         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33910         // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
33911         // overloads are TypeScript syntax.
33912         if (node.decorators
33913             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33914             || node.typeParameters
33915             || node.type
33916             || !node.body
33917             || node.questionToken) {
33918             transformFlags |= 1 /* AssertTypeScript */;
33919         }
33920         // function declarations with object rest destructuring are ES2018 syntax
33921         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33922             transformFlags |= 32 /* AssertES2018 */;
33923         }
33924         // An async method declaration is ES2017 syntax.
33925         if (ts.hasModifier(node, 256 /* Async */)) {
33926             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
33927         }
33928         if (node.asteriskToken) {
33929             transformFlags |= 512 /* AssertGenerator */;
33930         }
33931         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33932         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
33933     }
33934     function computeAccessor(node, subtreeFlags) {
33935         var transformFlags = subtreeFlags;
33936         // Decorators, TypeScript-specific modifiers, type annotations, and overloads are
33937         // TypeScript syntax.
33938         if (node.decorators
33939             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33940             || node.type
33941             || !node.body) {
33942             transformFlags |= 1 /* AssertTypeScript */;
33943         }
33944         // function declarations with object rest destructuring are ES2018 syntax
33945         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33946             transformFlags |= 32 /* AssertES2018 */;
33947         }
33948         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33949         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
33950     }
33951     function computePropertyDeclaration(node, subtreeFlags) {
33952         var transformFlags = subtreeFlags | 4194304 /* ContainsClassFields */;
33953         // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax.
33954         if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken || node.exclamationToken) {
33955             transformFlags |= 1 /* AssertTypeScript */;
33956         }
33957         // Hoisted variables related to class properties should live within the TypeScript class wrapper.
33958         if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
33959             transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
33960         }
33961         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33962         return propagatePropertyNameFlags(node.name, transformFlags & ~536875008 /* PropertyExcludes */);
33963     }
33964     function computeFunctionDeclaration(node, subtreeFlags) {
33965         var transformFlags;
33966         var modifierFlags = ts.getModifierFlags(node);
33967         var body = node.body;
33968         if (!body || (modifierFlags & 2 /* Ambient */)) {
33969             // An ambient declaration is TypeScript syntax.
33970             // A FunctionDeclaration without a body is an overload and is TypeScript syntax.
33971             transformFlags = 1 /* AssertTypeScript */;
33972         }
33973         else {
33974             transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
33975             // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
33976             // syntax.
33977             if (modifierFlags & 2270 /* TypeScriptModifier */
33978                 || node.typeParameters
33979                 || node.type) {
33980                 transformFlags |= 1 /* AssertTypeScript */;
33981             }
33982             // An async function declaration is ES2017 syntax.
33983             if (modifierFlags & 256 /* Async */) {
33984                 transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
33985             }
33986             // function declarations with object rest destructuring are ES2018 syntax
33987             if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33988                 transformFlags |= 32 /* AssertES2018 */;
33989             }
33990             // If a FunctionDeclaration is generator function and is the body of a
33991             // transformed async function, then this node can be transformed to a
33992             // down-level generator.
33993             // Currently we do not support transforming any other generator functions
33994             // down level.
33995             if (node.asteriskToken) {
33996                 transformFlags |= 512 /* AssertGenerator */;
33997             }
33998         }
33999         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34000         return transformFlags & ~538925056 /* FunctionExcludes */;
34001     }
34002     function computeFunctionExpression(node, subtreeFlags) {
34003         var transformFlags = subtreeFlags;
34004         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34005         // syntax.
34006         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34007             || node.typeParameters
34008             || node.type) {
34009             transformFlags |= 1 /* AssertTypeScript */;
34010         }
34011         // An async function expression is ES2017 syntax.
34012         if (ts.hasModifier(node, 256 /* Async */)) {
34013             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
34014         }
34015         // function expressions with object rest destructuring are ES2018 syntax
34016         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34017             transformFlags |= 32 /* AssertES2018 */;
34018         }
34019         // If a FunctionExpression is generator function and is the body of a
34020         // transformed async function, then this node can be transformed to a
34021         // down-level generator.
34022         if (node.asteriskToken) {
34023             transformFlags |= 512 /* AssertGenerator */;
34024         }
34025         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34026         return transformFlags & ~538925056 /* FunctionExcludes */;
34027     }
34028     function computeArrowFunction(node, subtreeFlags) {
34029         // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
34030         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
34031         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34032         // syntax.
34033         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34034             || node.typeParameters
34035             || node.type) {
34036             transformFlags |= 1 /* AssertTypeScript */;
34037         }
34038         // An async arrow function is ES2017 syntax.
34039         if (ts.hasModifier(node, 256 /* Async */)) {
34040             transformFlags |= 64 /* AssertES2017 */;
34041         }
34042         // arrow functions with object rest destructuring are ES2018 syntax
34043         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34044             transformFlags |= 32 /* AssertES2018 */;
34045         }
34046         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34047         return transformFlags & ~538920960 /* ArrowFunctionExcludes */;
34048     }
34049     function computePropertyAccess(node, subtreeFlags) {
34050         var transformFlags = subtreeFlags;
34051         if (node.flags & 32 /* OptionalChain */) {
34052             transformFlags |= 8 /* ContainsES2020 */;
34053         }
34054         // If a PropertyAccessExpression starts with a super keyword, then it is
34055         // ES6 syntax, and requires a lexical `this` binding.
34056         if (node.expression.kind === 102 /* SuperKeyword */) {
34057             // super inside of an async function requires hoisting the super access (ES2017).
34058             // same for super inside of an async generator, which is ES2018.
34059             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34060         }
34061         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34062         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34063     }
34064     function computeElementAccess(node, subtreeFlags) {
34065         var transformFlags = subtreeFlags;
34066         if (node.flags & 32 /* OptionalChain */) {
34067             transformFlags |= 8 /* ContainsES2020 */;
34068         }
34069         // If an ElementAccessExpression starts with a super keyword, then it is
34070         // ES6 syntax, and requires a lexical `this` binding.
34071         if (node.expression.kind === 102 /* SuperKeyword */) {
34072             // super inside of an async function requires hoisting the super access (ES2017).
34073             // same for super inside of an async generator, which is ES2018.
34074             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34075         }
34076         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34077         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34078     }
34079     function computeVariableDeclaration(node, subtreeFlags) {
34080         var transformFlags = subtreeFlags;
34081         transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
34082         // A VariableDeclaration containing ObjectRest is ES2018 syntax
34083         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34084             transformFlags |= 32 /* AssertES2018 */;
34085         }
34086         // Type annotations are TypeScript syntax.
34087         if (node.type || node.exclamationToken) {
34088             transformFlags |= 1 /* AssertTypeScript */;
34089         }
34090         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34091         return transformFlags & ~536870912 /* NodeExcludes */;
34092     }
34093     function computeVariableStatement(node, subtreeFlags) {
34094         var transformFlags;
34095         var declarationListTransformFlags = node.declarationList.transformFlags;
34096         // An ambient declaration is TypeScript syntax.
34097         if (ts.hasModifier(node, 2 /* Ambient */)) {
34098             transformFlags = 1 /* AssertTypeScript */;
34099         }
34100         else {
34101             transformFlags = subtreeFlags;
34102             if (declarationListTransformFlags & 131072 /* ContainsBindingPattern */) {
34103                 transformFlags |= 256 /* AssertES2015 */;
34104             }
34105         }
34106         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34107         return transformFlags & ~536870912 /* NodeExcludes */;
34108     }
34109     function computeLabeledStatement(node, subtreeFlags) {
34110         var transformFlags = subtreeFlags;
34111         // A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
34112         if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */
34113             && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
34114             transformFlags |= 256 /* AssertES2015 */;
34115         }
34116         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34117         return transformFlags & ~536870912 /* NodeExcludes */;
34118     }
34119     function computeImportEquals(node, subtreeFlags) {
34120         var transformFlags = subtreeFlags;
34121         // An ImportEqualsDeclaration with a namespace reference is TypeScript.
34122         if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
34123             transformFlags |= 1 /* AssertTypeScript */;
34124         }
34125         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34126         return transformFlags & ~536870912 /* NodeExcludes */;
34127     }
34128     function computeExpressionStatement(node, subtreeFlags) {
34129         var transformFlags = subtreeFlags;
34130         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34131         return transformFlags & ~536870912 /* NodeExcludes */;
34132     }
34133     function computeModuleDeclaration(node, subtreeFlags) {
34134         var transformFlags = 1 /* AssertTypeScript */;
34135         var modifierFlags = ts.getModifierFlags(node);
34136         if ((modifierFlags & 2 /* Ambient */) === 0) {
34137             transformFlags |= subtreeFlags;
34138         }
34139         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34140         return transformFlags & ~537991168 /* ModuleExcludes */;
34141     }
34142     function computeVariableDeclarationList(node, subtreeFlags) {
34143         var transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34144         if (subtreeFlags & 131072 /* ContainsBindingPattern */) {
34145             transformFlags |= 256 /* AssertES2015 */;
34146         }
34147         // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
34148         if (node.flags & 3 /* BlockScoped */) {
34149             transformFlags |= 256 /* AssertES2015 */ | 65536 /* ContainsBlockScopedBinding */;
34150         }
34151         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34152         return transformFlags & ~537018368 /* VariableDeclarationListExcludes */;
34153     }
34154     function computeOther(node, kind, subtreeFlags) {
34155         // Mark transformations needed for each node
34156         var transformFlags = subtreeFlags;
34157         var excludeFlags = 536870912 /* NodeExcludes */;
34158         switch (kind) {
34159             case 126 /* AsyncKeyword */:
34160                 // async is ES2017 syntax, but may be ES2018 syntax (for async generators)
34161                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */;
34162                 break;
34163             case 206 /* AwaitExpression */:
34164                 // await is ES2017 syntax, but may be ES2018 syntax (for async generators)
34165                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */ | 524288 /* ContainsAwait */;
34166                 break;
34167             case 199 /* TypeAssertionExpression */:
34168             case 217 /* AsExpression */:
34169             case 326 /* PartiallyEmittedExpression */:
34170                 // These nodes are TypeScript syntax.
34171                 transformFlags |= 1 /* AssertTypeScript */;
34172                 excludeFlags = 536870912 /* OuterExpressionExcludes */;
34173                 break;
34174             case 119 /* PublicKeyword */:
34175             case 117 /* PrivateKeyword */:
34176             case 118 /* ProtectedKeyword */:
34177             case 122 /* AbstractKeyword */:
34178             case 130 /* DeclareKeyword */:
34179             case 81 /* ConstKeyword */:
34180             case 248 /* EnumDeclaration */:
34181             case 284 /* EnumMember */:
34182             case 218 /* NonNullExpression */:
34183             case 138 /* ReadonlyKeyword */:
34184                 // These nodes are TypeScript syntax.
34185                 transformFlags |= 1 /* AssertTypeScript */;
34186                 break;
34187             case 266 /* JsxElement */:
34188             case 11 /* JsxText */:
34189             case 269 /* JsxClosingElement */:
34190             case 270 /* JsxFragment */:
34191             case 271 /* JsxOpeningFragment */:
34192             case 272 /* JsxClosingFragment */:
34193             case 273 /* JsxAttribute */:
34194             case 274 /* JsxAttributes */:
34195             case 275 /* JsxSpreadAttribute */:
34196             case 276 /* JsxExpression */:
34197                 // These nodes are Jsx syntax.
34198                 transformFlags |= 2 /* AssertJsx */;
34199                 break;
34200             case 14 /* NoSubstitutionTemplateLiteral */:
34201             case 15 /* TemplateHead */:
34202             case 16 /* TemplateMiddle */:
34203             case 17 /* TemplateTail */:
34204                 if (node.templateFlags) {
34205                     transformFlags |= 32 /* AssertES2018 */;
34206                     break;
34207                 }
34208             // falls through
34209             case 198 /* TaggedTemplateExpression */:
34210                 if (ts.hasInvalidEscape(node.template)) {
34211                     transformFlags |= 32 /* AssertES2018 */;
34212                     break;
34213                 }
34214             // falls through
34215             case 211 /* TemplateExpression */:
34216             case 282 /* ShorthandPropertyAssignment */:
34217             case 120 /* StaticKeyword */:
34218             case 219 /* MetaProperty */:
34219                 // These nodes are ES6 syntax.
34220                 transformFlags |= 256 /* AssertES2015 */;
34221                 break;
34222             case 10 /* StringLiteral */:
34223                 if (node.hasExtendedUnicodeEscape) {
34224                     transformFlags |= 256 /* AssertES2015 */;
34225                 }
34226                 break;
34227             case 8 /* NumericLiteral */:
34228                 if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
34229                     transformFlags |= 256 /* AssertES2015 */;
34230                 }
34231                 break;
34232             case 9 /* BigIntLiteral */:
34233                 transformFlags |= 4 /* AssertESNext */;
34234                 break;
34235             case 232 /* ForOfStatement */:
34236                 // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
34237                 if (node.awaitModifier) {
34238                     transformFlags |= 32 /* AssertES2018 */;
34239                 }
34240                 transformFlags |= 256 /* AssertES2015 */;
34241                 break;
34242             case 212 /* YieldExpression */:
34243                 // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
34244                 // generator).
34245                 transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 262144 /* ContainsYield */;
34246                 break;
34247             case 125 /* AnyKeyword */:
34248             case 140 /* NumberKeyword */:
34249             case 151 /* BigIntKeyword */:
34250             case 137 /* NeverKeyword */:
34251             case 141 /* ObjectKeyword */:
34252             case 143 /* StringKeyword */:
34253             case 128 /* BooleanKeyword */:
34254             case 144 /* SymbolKeyword */:
34255             case 110 /* VoidKeyword */:
34256             case 155 /* TypeParameter */:
34257             case 158 /* PropertySignature */:
34258             case 160 /* MethodSignature */:
34259             case 165 /* CallSignature */:
34260             case 166 /* ConstructSignature */:
34261             case 167 /* IndexSignature */:
34262             case 168 /* TypePredicate */:
34263             case 169 /* TypeReference */:
34264             case 170 /* FunctionType */:
34265             case 171 /* ConstructorType */:
34266             case 172 /* TypeQuery */:
34267             case 173 /* TypeLiteral */:
34268             case 174 /* ArrayType */:
34269             case 175 /* TupleType */:
34270             case 176 /* OptionalType */:
34271             case 177 /* RestType */:
34272             case 178 /* UnionType */:
34273             case 179 /* IntersectionType */:
34274             case 180 /* ConditionalType */:
34275             case 181 /* InferType */:
34276             case 182 /* ParenthesizedType */:
34277             case 246 /* InterfaceDeclaration */:
34278             case 247 /* TypeAliasDeclaration */:
34279             case 183 /* ThisType */:
34280             case 184 /* TypeOperator */:
34281             case 185 /* IndexedAccessType */:
34282             case 186 /* MappedType */:
34283             case 187 /* LiteralType */:
34284             case 252 /* NamespaceExportDeclaration */:
34285                 // Types and signatures are TypeScript syntax, and exclude all other facts.
34286                 transformFlags = 1 /* AssertTypeScript */;
34287                 excludeFlags = -2 /* TypeExcludes */;
34288                 break;
34289             case 154 /* ComputedPropertyName */:
34290                 // Even though computed property names are ES6, we don't treat them as such.
34291                 // This is so that they can flow through PropertyName transforms unaffected.
34292                 // Instead, we mark the container as ES6, so that it can properly handle the transform.
34293                 transformFlags |= 32768 /* ContainsComputedPropertyName */;
34294                 break;
34295             case 213 /* SpreadElement */:
34296                 transformFlags |= 256 /* AssertES2015 */ | 8192 /* ContainsRestOrSpread */;
34297                 break;
34298             case 283 /* SpreadAssignment */:
34299                 transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34300                 break;
34301             case 102 /* SuperKeyword */:
34302                 // This node is ES6 syntax.
34303                 transformFlags |= 256 /* AssertES2015 */;
34304                 excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
34305                 break;
34306             case 104 /* ThisKeyword */:
34307                 // Mark this node and its ancestors as containing a lexical `this` keyword.
34308                 transformFlags |= 4096 /* ContainsLexicalThis */;
34309                 break;
34310             case 189 /* ObjectBindingPattern */:
34311                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34312                 if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
34313                     transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34314                 }
34315                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34316                 break;
34317             case 190 /* ArrayBindingPattern */:
34318                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34319                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34320                 break;
34321             case 191 /* BindingElement */:
34322                 transformFlags |= 256 /* AssertES2015 */;
34323                 if (node.dotDotDotToken) {
34324                     transformFlags |= 8192 /* ContainsRestOrSpread */;
34325                 }
34326                 break;
34327             case 157 /* Decorator */:
34328                 // This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
34329                 transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
34330                 break;
34331             case 193 /* ObjectLiteralExpression */:
34332                 excludeFlags = 536922112 /* ObjectLiteralExcludes */;
34333                 if (subtreeFlags & 32768 /* ContainsComputedPropertyName */) {
34334                     // If an ObjectLiteralExpression contains a ComputedPropertyName, then it
34335                     // is an ES6 node.
34336                     transformFlags |= 256 /* AssertES2015 */;
34337                 }
34338                 if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34339                     // If an ObjectLiteralExpression contains a spread element, then it
34340                     // is an ES2018 node.
34341                     transformFlags |= 32 /* AssertES2018 */;
34342                 }
34343                 break;
34344             case 192 /* ArrayLiteralExpression */:
34345                 excludeFlags = 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34346                 break;
34347             case 228 /* DoStatement */:
34348             case 229 /* WhileStatement */:
34349             case 230 /* ForStatement */:
34350             case 231 /* ForInStatement */:
34351                 // A loop containing a block scoped binding *may* need to be transformed from ES6.
34352                 if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */) {
34353                     transformFlags |= 256 /* AssertES2015 */;
34354                 }
34355                 break;
34356             case 290 /* SourceFile */:
34357                 break;
34358             case 262 /* NamespaceExport */:
34359                 transformFlags |= 4 /* AssertESNext */;
34360                 break;
34361             case 235 /* ReturnStatement */:
34362                 // Return statements may require an `await` in ES2018.
34363                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */ | 32 /* AssertES2018 */;
34364                 break;
34365             case 233 /* ContinueStatement */:
34366             case 234 /* BreakStatement */:
34367                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34368                 break;
34369             case 76 /* PrivateIdentifier */:
34370                 transformFlags |= 4194304 /* ContainsClassFields */;
34371                 break;
34372         }
34373         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34374         return transformFlags & ~excludeFlags;
34375     }
34376     function propagatePropertyNameFlags(node, transformFlags) {
34377         return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
34378     }
34379     /**
34380      * Gets the transform flags to exclude when unioning the transform flags of a subtree.
34381      *
34382      * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
34383      *       For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
34384      *       than calling this function.
34385      */
34386     function getTransformFlagsSubtreeExclusions(kind) {
34387         if (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */) {
34388             return -2 /* TypeExcludes */;
34389         }
34390         switch (kind) {
34391             case 196 /* CallExpression */:
34392             case 197 /* NewExpression */:
34393             case 192 /* ArrayLiteralExpression */:
34394                 return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34395             case 249 /* ModuleDeclaration */:
34396                 return 537991168 /* ModuleExcludes */;
34397             case 156 /* Parameter */:
34398                 return 536870912 /* ParameterExcludes */;
34399             case 202 /* ArrowFunction */:
34400                 return 538920960 /* ArrowFunctionExcludes */;
34401             case 201 /* FunctionExpression */:
34402             case 244 /* FunctionDeclaration */:
34403                 return 538925056 /* FunctionExcludes */;
34404             case 243 /* VariableDeclarationList */:
34405                 return 537018368 /* VariableDeclarationListExcludes */;
34406             case 245 /* ClassDeclaration */:
34407             case 214 /* ClassExpression */:
34408                 return 536905728 /* ClassExcludes */;
34409             case 162 /* Constructor */:
34410                 return 538923008 /* ConstructorExcludes */;
34411             case 161 /* MethodDeclaration */:
34412             case 163 /* GetAccessor */:
34413             case 164 /* SetAccessor */:
34414                 return 538923008 /* MethodOrAccessorExcludes */;
34415             case 125 /* AnyKeyword */:
34416             case 140 /* NumberKeyword */:
34417             case 151 /* BigIntKeyword */:
34418             case 137 /* NeverKeyword */:
34419             case 143 /* StringKeyword */:
34420             case 141 /* ObjectKeyword */:
34421             case 128 /* BooleanKeyword */:
34422             case 144 /* SymbolKeyword */:
34423             case 110 /* VoidKeyword */:
34424             case 155 /* TypeParameter */:
34425             case 158 /* PropertySignature */:
34426             case 160 /* MethodSignature */:
34427             case 165 /* CallSignature */:
34428             case 166 /* ConstructSignature */:
34429             case 167 /* IndexSignature */:
34430             case 246 /* InterfaceDeclaration */:
34431             case 247 /* TypeAliasDeclaration */:
34432                 return -2 /* TypeExcludes */;
34433             case 193 /* ObjectLiteralExpression */:
34434                 return 536922112 /* ObjectLiteralExcludes */;
34435             case 280 /* CatchClause */:
34436                 return 536887296 /* CatchClauseExcludes */;
34437             case 189 /* ObjectBindingPattern */:
34438             case 190 /* ArrayBindingPattern */:
34439                 return 536879104 /* BindingPatternExcludes */;
34440             case 199 /* TypeAssertionExpression */:
34441             case 217 /* AsExpression */:
34442             case 326 /* PartiallyEmittedExpression */:
34443             case 200 /* ParenthesizedExpression */:
34444             case 102 /* SuperKeyword */:
34445                 return 536870912 /* OuterExpressionExcludes */;
34446             case 194 /* PropertyAccessExpression */:
34447             case 195 /* ElementAccessExpression */:
34448                 return 536870912 /* PropertyAccessExcludes */;
34449             default:
34450                 return 536870912 /* NodeExcludes */;
34451         }
34452     }
34453     ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
34454     /**
34455      * "Binds" JSDoc nodes in TypeScript code.
34456      * Since we will never create symbols for JSDoc, we just set parent pointers instead.
34457      */
34458     function setParentPointers(parent, child) {
34459         child.parent = parent;
34460         ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
34461     }
34462 })(ts || (ts = {}));
34463 /** @internal */
34464 var ts;
34465 (function (ts) {
34466     function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
34467         return getSymbolWalker;
34468         function getSymbolWalker(accept) {
34469             if (accept === void 0) { accept = function () { return true; }; }
34470             var visitedTypes = []; // Sparse array from id to type
34471             var visitedSymbols = []; // Sparse array from id to symbol
34472             return {
34473                 walkType: function (type) {
34474                     try {
34475                         visitType(type);
34476                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34477                     }
34478                     finally {
34479                         ts.clear(visitedTypes);
34480                         ts.clear(visitedSymbols);
34481                     }
34482                 },
34483                 walkSymbol: function (symbol) {
34484                     try {
34485                         visitSymbol(symbol);
34486                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34487                     }
34488                     finally {
34489                         ts.clear(visitedTypes);
34490                         ts.clear(visitedSymbols);
34491                     }
34492                 },
34493             };
34494             function visitType(type) {
34495                 if (!type) {
34496                     return;
34497                 }
34498                 if (visitedTypes[type.id]) {
34499                     return;
34500                 }
34501                 visitedTypes[type.id] = type;
34502                 // Reuse visitSymbol to visit the type's symbol,
34503                 //  but be sure to bail on recuring into the type if accept declines the symbol.
34504                 var shouldBail = visitSymbol(type.symbol);
34505                 if (shouldBail)
34506                     return;
34507                 // Visit the type's related types, if any
34508                 if (type.flags & 524288 /* Object */) {
34509                     var objectType = type;
34510                     var objectFlags = objectType.objectFlags;
34511                     if (objectFlags & 4 /* Reference */) {
34512                         visitTypeReference(type);
34513                     }
34514                     if (objectFlags & 32 /* Mapped */) {
34515                         visitMappedType(type);
34516                     }
34517                     if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
34518                         visitInterfaceType(type);
34519                     }
34520                     if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
34521                         visitObjectType(objectType);
34522                     }
34523                 }
34524                 if (type.flags & 262144 /* TypeParameter */) {
34525                     visitTypeParameter(type);
34526                 }
34527                 if (type.flags & 3145728 /* UnionOrIntersection */) {
34528                     visitUnionOrIntersectionType(type);
34529                 }
34530                 if (type.flags & 4194304 /* Index */) {
34531                     visitIndexType(type);
34532                 }
34533                 if (type.flags & 8388608 /* IndexedAccess */) {
34534                     visitIndexedAccessType(type);
34535                 }
34536             }
34537             function visitTypeReference(type) {
34538                 visitType(type.target);
34539                 ts.forEach(getTypeArguments(type), visitType);
34540             }
34541             function visitTypeParameter(type) {
34542                 visitType(getConstraintOfTypeParameter(type));
34543             }
34544             function visitUnionOrIntersectionType(type) {
34545                 ts.forEach(type.types, visitType);
34546             }
34547             function visitIndexType(type) {
34548                 visitType(type.type);
34549             }
34550             function visitIndexedAccessType(type) {
34551                 visitType(type.objectType);
34552                 visitType(type.indexType);
34553                 visitType(type.constraint);
34554             }
34555             function visitMappedType(type) {
34556                 visitType(type.typeParameter);
34557                 visitType(type.constraintType);
34558                 visitType(type.templateType);
34559                 visitType(type.modifiersType);
34560             }
34561             function visitSignature(signature) {
34562                 var typePredicate = getTypePredicateOfSignature(signature);
34563                 if (typePredicate) {
34564                     visitType(typePredicate.type);
34565                 }
34566                 ts.forEach(signature.typeParameters, visitType);
34567                 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
34568                     var parameter = _a[_i];
34569                     visitSymbol(parameter);
34570                 }
34571                 visitType(getRestTypeOfSignature(signature));
34572                 visitType(getReturnTypeOfSignature(signature));
34573             }
34574             function visitInterfaceType(interfaceT) {
34575                 visitObjectType(interfaceT);
34576                 ts.forEach(interfaceT.typeParameters, visitType);
34577                 ts.forEach(getBaseTypes(interfaceT), visitType);
34578                 visitType(interfaceT.thisType);
34579             }
34580             function visitObjectType(type) {
34581                 var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
34582                 visitType(stringIndexType);
34583                 var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
34584                 visitType(numberIndexType);
34585                 // The two checks above *should* have already resolved the type (if needed), so this should be cached
34586                 var resolved = resolveStructuredTypeMembers(type);
34587                 for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
34588                     var signature = _a[_i];
34589                     visitSignature(signature);
34590                 }
34591                 for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
34592                     var signature = _c[_b];
34593                     visitSignature(signature);
34594                 }
34595                 for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
34596                     var p = _e[_d];
34597                     visitSymbol(p);
34598                 }
34599             }
34600             function visitSymbol(symbol) {
34601                 if (!symbol) {
34602                     return false;
34603                 }
34604                 var symbolId = ts.getSymbolId(symbol);
34605                 if (visitedSymbols[symbolId]) {
34606                     return false;
34607                 }
34608                 visitedSymbols[symbolId] = symbol;
34609                 if (!accept(symbol)) {
34610                     return true;
34611                 }
34612                 var t = getTypeOfSymbol(symbol);
34613                 visitType(t); // Should handle members on classes and such
34614                 if (symbol.exports) {
34615                     symbol.exports.forEach(visitSymbol);
34616                 }
34617                 ts.forEach(symbol.declarations, function (d) {
34618                     // Type queries are too far resolved when we just visit the symbol's type
34619                     //  (their type resolved directly to the member deeply referenced)
34620                     // So to get the intervening symbols, we need to check if there's a type
34621                     // query node on any of the symbol's declarations and get symbols there
34622                     if (d.type && d.type.kind === 172 /* TypeQuery */) {
34623                         var query = d.type;
34624                         var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
34625                         visitSymbol(entity);
34626                     }
34627                 });
34628                 return false;
34629             }
34630         }
34631     }
34632     ts.createGetSymbolWalker = createGetSymbolWalker;
34633 })(ts || (ts = {}));
34634 /* @internal */
34635 var ts;
34636 (function (ts) {
34637     var ambientModuleSymbolRegex = /^".+"$/;
34638     var anon = "(anonymous)";
34639     var nextSymbolId = 1;
34640     var nextNodeId = 1;
34641     var nextMergeId = 1;
34642     var nextFlowId = 1;
34643     var IterationUse;
34644     (function (IterationUse) {
34645         IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
34646         IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
34647         IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
34648         IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
34649         IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
34650         IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
34651         IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
34652         // Spread, Destructuring, Array element assignment
34653         IterationUse[IterationUse["Element"] = 1] = "Element";
34654         IterationUse[IterationUse["Spread"] = 33] = "Spread";
34655         IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
34656         IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
34657         IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
34658         IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
34659         IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
34660         IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
34661         IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
34662     })(IterationUse || (IterationUse = {}));
34663     var IterationTypeKind;
34664     (function (IterationTypeKind) {
34665         IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
34666         IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
34667         IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
34668     })(IterationTypeKind || (IterationTypeKind = {}));
34669     var WideningKind;
34670     (function (WideningKind) {
34671         WideningKind[WideningKind["Normal"] = 0] = "Normal";
34672         WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
34673         WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
34674         WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
34675     })(WideningKind || (WideningKind = {}));
34676     var TypeFacts;
34677     (function (TypeFacts) {
34678         TypeFacts[TypeFacts["None"] = 0] = "None";
34679         TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
34680         TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
34681         TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
34682         TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
34683         TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
34684         TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
34685         TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
34686         TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
34687         TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
34688         TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
34689         TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
34690         TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
34691         TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
34692         TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
34693         TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
34694         TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
34695         TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
34696         TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
34697         TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
34698         TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
34699         TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
34700         TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
34701         TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
34702         TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
34703         TypeFacts[TypeFacts["All"] = 16777215] = "All";
34704         // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
34705         // The presence of a particular fact means that the given test is true for some (and possibly all) values
34706         // of that kind of type.
34707         TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
34708         TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
34709         TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
34710         TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
34711         TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
34712         TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
34713         TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
34714         TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
34715         TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
34716         TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
34717         TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
34718         TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
34719         TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
34720         TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
34721         TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
34722         TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
34723         TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
34724         TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
34725         TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
34726         TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
34727         TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
34728         TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
34729         TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
34730         TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
34731         TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
34732         TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
34733         TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
34734         TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
34735         TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
34736         TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
34737         TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
34738         TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
34739         TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
34740         TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
34741         TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
34742         TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
34743         TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
34744         TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
34745         TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
34746         TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
34747         TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
34748         TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
34749     })(TypeFacts || (TypeFacts = {}));
34750     var typeofEQFacts = ts.createMapFromTemplate({
34751         string: 1 /* TypeofEQString */,
34752         number: 2 /* TypeofEQNumber */,
34753         bigint: 4 /* TypeofEQBigInt */,
34754         boolean: 8 /* TypeofEQBoolean */,
34755         symbol: 16 /* TypeofEQSymbol */,
34756         undefined: 65536 /* EQUndefined */,
34757         object: 32 /* TypeofEQObject */,
34758         function: 64 /* TypeofEQFunction */
34759     });
34760     var typeofNEFacts = ts.createMapFromTemplate({
34761         string: 256 /* TypeofNEString */,
34762         number: 512 /* TypeofNENumber */,
34763         bigint: 1024 /* TypeofNEBigInt */,
34764         boolean: 2048 /* TypeofNEBoolean */,
34765         symbol: 4096 /* TypeofNESymbol */,
34766         undefined: 524288 /* NEUndefined */,
34767         object: 8192 /* TypeofNEObject */,
34768         function: 16384 /* TypeofNEFunction */
34769     });
34770     var TypeSystemPropertyName;
34771     (function (TypeSystemPropertyName) {
34772         TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
34773         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
34774         TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
34775         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
34776         TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
34777         TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
34778         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
34779     })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
34780     var CheckMode;
34781     (function (CheckMode) {
34782         CheckMode[CheckMode["Normal"] = 0] = "Normal";
34783         CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
34784         CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
34785         CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
34786         CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
34787         CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
34788     })(CheckMode || (CheckMode = {}));
34789     var AccessFlags;
34790     (function (AccessFlags) {
34791         AccessFlags[AccessFlags["None"] = 0] = "None";
34792         AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
34793         AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
34794         AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
34795         AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
34796     })(AccessFlags || (AccessFlags = {}));
34797     var SignatureCheckMode;
34798     (function (SignatureCheckMode) {
34799         SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
34800         SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
34801         SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
34802         SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
34803         SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
34804     })(SignatureCheckMode || (SignatureCheckMode = {}));
34805     var IntersectionState;
34806     (function (IntersectionState) {
34807         IntersectionState[IntersectionState["None"] = 0] = "None";
34808         IntersectionState[IntersectionState["Source"] = 1] = "Source";
34809         IntersectionState[IntersectionState["Target"] = 2] = "Target";
34810         IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
34811         IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
34812     })(IntersectionState || (IntersectionState = {}));
34813     var MappedTypeModifiers;
34814     (function (MappedTypeModifiers) {
34815         MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
34816         MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
34817         MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
34818         MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
34819     })(MappedTypeModifiers || (MappedTypeModifiers = {}));
34820     var ExpandingFlags;
34821     (function (ExpandingFlags) {
34822         ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
34823         ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
34824         ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
34825         ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
34826     })(ExpandingFlags || (ExpandingFlags = {}));
34827     var MembersOrExportsResolutionKind;
34828     (function (MembersOrExportsResolutionKind) {
34829         MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
34830         MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
34831     })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
34832     var UnusedKind;
34833     (function (UnusedKind) {
34834         UnusedKind[UnusedKind["Local"] = 0] = "Local";
34835         UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
34836     })(UnusedKind || (UnusedKind = {}));
34837     var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
34838     var DeclarationMeaning;
34839     (function (DeclarationMeaning) {
34840         DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
34841         DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
34842         DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
34843         DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
34844         DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
34845         DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
34846     })(DeclarationMeaning || (DeclarationMeaning = {}));
34847     var DeclarationSpaces;
34848     (function (DeclarationSpaces) {
34849         DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
34850         DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
34851         DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
34852         DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
34853     })(DeclarationSpaces || (DeclarationSpaces = {}));
34854     function SymbolLinks() {
34855     }
34856     function NodeLinks() {
34857         this.flags = 0;
34858     }
34859     function getNodeId(node) {
34860         if (!node.id) {
34861             node.id = nextNodeId;
34862             nextNodeId++;
34863         }
34864         return node.id;
34865     }
34866     ts.getNodeId = getNodeId;
34867     function getSymbolId(symbol) {
34868         if (!symbol.id) {
34869             symbol.id = nextSymbolId;
34870             nextSymbolId++;
34871         }
34872         return symbol.id;
34873     }
34874     ts.getSymbolId = getSymbolId;
34875     function isInstantiatedModule(node, preserveConstEnums) {
34876         var moduleState = ts.getModuleInstanceState(node);
34877         return moduleState === 1 /* Instantiated */ ||
34878             (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
34879     }
34880     ts.isInstantiatedModule = isInstantiatedModule;
34881     function createTypeChecker(host, produceDiagnostics) {
34882         var getPackagesSet = ts.memoize(function () {
34883             var set = ts.createMap();
34884             host.getSourceFiles().forEach(function (sf) {
34885                 if (!sf.resolvedModules)
34886                     return;
34887                 ts.forEachEntry(sf.resolvedModules, function (r) {
34888                     if (r && r.packageId)
34889                         set.set(r.packageId.name, true);
34890                 });
34891             });
34892             return set;
34893         });
34894         // Cancellation that controls whether or not we can cancel in the middle of type checking.
34895         // In general cancelling is *not* safe for the type checker.  We might be in the middle of
34896         // computing something, and we will leave our internals in an inconsistent state.  Callers
34897         // who set the cancellation token should catch if a cancellation exception occurs, and
34898         // should throw away and create a new TypeChecker.
34899         //
34900         // Currently we only support setting the cancellation token when getting diagnostics.  This
34901         // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
34902         // they no longer need the information (for example, if the user started editing again).
34903         var cancellationToken;
34904         var requestedExternalEmitHelpers;
34905         var externalHelpersModule;
34906         var Symbol = ts.objectAllocator.getSymbolConstructor();
34907         var Type = ts.objectAllocator.getTypeConstructor();
34908         var Signature = ts.objectAllocator.getSignatureConstructor();
34909         var typeCount = 0;
34910         var symbolCount = 0;
34911         var enumCount = 0;
34912         var totalInstantiationCount = 0;
34913         var instantiationCount = 0;
34914         var instantiationDepth = 0;
34915         var constraintDepth = 0;
34916         var currentNode;
34917         var emptySymbols = ts.createSymbolTable();
34918         var arrayVariances = [1 /* Covariant */];
34919         var compilerOptions = host.getCompilerOptions();
34920         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
34921         var moduleKind = ts.getEmitModuleKind(compilerOptions);
34922         var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
34923         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
34924         var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
34925         var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
34926         var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
34927         var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
34928         var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
34929         var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
34930         var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
34931         var emitResolver = createResolver();
34932         var nodeBuilder = createNodeBuilder();
34933         var globals = ts.createSymbolTable();
34934         var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
34935         undefinedSymbol.declarations = [];
34936         var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
34937         globalThisSymbol.exports = globals;
34938         globalThisSymbol.declarations = [];
34939         globals.set(globalThisSymbol.escapedName, globalThisSymbol);
34940         var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
34941         var requireSymbol = createSymbol(4 /* Property */, "require");
34942         /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
34943         var apparentArgumentCount;
34944         // for public members that accept a Node or one of its subtypes, we must guard against
34945         // synthetic nodes created during transformations by calling `getParseTreeNode`.
34946         // for most of these, we perform the guard only on `checker` to avoid any possible
34947         // extra cost of calling `getParseTreeNode` when calling these functions from inside the
34948         // checker.
34949         var checker = {
34950             getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
34951             getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
34952             getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
34953             getTypeCount: function () { return typeCount; },
34954             getInstantiationCount: function () { return totalInstantiationCount; },
34955             getRelationCacheSizes: function () { return ({
34956                 assignable: assignableRelation.size,
34957                 identity: identityRelation.size,
34958                 subtype: subtypeRelation.size,
34959                 strictSubtype: strictSubtypeRelation.size,
34960             }); },
34961             isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
34962             isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
34963             isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
34964             getMergedSymbol: getMergedSymbol,
34965             getDiagnostics: getDiagnostics,
34966             getGlobalDiagnostics: getGlobalDiagnostics,
34967             getTypeOfSymbolAtLocation: function (symbol, location) {
34968                 location = ts.getParseTreeNode(location);
34969                 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
34970             },
34971             getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
34972                 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
34973                 if (parameter === undefined)
34974                     return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
34975                 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
34976             },
34977             getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
34978             getPropertiesOfType: getPropertiesOfType,
34979             getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
34980             getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
34981                 var node = ts.getParseTreeNode(location);
34982                 if (!node) {
34983                     return undefined;
34984                 }
34985                 var propName = ts.escapeLeadingUnderscores(name);
34986                 var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
34987                 return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
34988             },
34989             getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
34990             getIndexInfoOfType: getIndexInfoOfType,
34991             getSignaturesOfType: getSignaturesOfType,
34992             getIndexTypeOfType: getIndexTypeOfType,
34993             getBaseTypes: getBaseTypes,
34994             getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
34995             getWidenedType: getWidenedType,
34996             getTypeFromTypeNode: function (nodeIn) {
34997                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
34998                 return node ? getTypeFromTypeNode(node) : errorType;
34999             },
35000             getParameterType: getTypeAtPosition,
35001             getPromisedTypeOfPromise: getPromisedTypeOfPromise,
35002             getReturnTypeOfSignature: getReturnTypeOfSignature,
35003             isNullableType: isNullableType,
35004             getNullableType: getNullableType,
35005             getNonNullableType: getNonNullableType,
35006             getNonOptionalType: removeOptionalTypeMarker,
35007             getTypeArguments: getTypeArguments,
35008             typeToTypeNode: nodeBuilder.typeToTypeNode,
35009             indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
35010             signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
35011             symbolToEntityName: nodeBuilder.symbolToEntityName,
35012             symbolToExpression: nodeBuilder.symbolToExpression,
35013             symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
35014             symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
35015             typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
35016             getSymbolsInScope: function (location, meaning) {
35017                 location = ts.getParseTreeNode(location);
35018                 return location ? getSymbolsInScope(location, meaning) : [];
35019             },
35020             getSymbolAtLocation: function (node) {
35021                 node = ts.getParseTreeNode(node);
35022                 // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
35023                 return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
35024             },
35025             getShorthandAssignmentValueSymbol: function (node) {
35026                 node = ts.getParseTreeNode(node);
35027                 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
35028             },
35029             getExportSpecifierLocalTargetSymbol: function (nodeIn) {
35030                 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
35031                 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
35032             },
35033             getExportSymbolOfSymbol: function (symbol) {
35034                 return getMergedSymbol(symbol.exportSymbol || symbol);
35035             },
35036             getTypeAtLocation: function (node) {
35037                 node = ts.getParseTreeNode(node);
35038                 return node ? getTypeOfNode(node) : errorType;
35039             },
35040             getTypeOfAssignmentPattern: function (nodeIn) {
35041                 var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
35042                 return node && getTypeOfAssignmentPattern(node) || errorType;
35043             },
35044             getPropertySymbolOfDestructuringAssignment: function (locationIn) {
35045                 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
35046                 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
35047             },
35048             signatureToString: function (signature, enclosingDeclaration, flags, kind) {
35049                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
35050             },
35051             typeToString: function (type, enclosingDeclaration, flags) {
35052                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
35053             },
35054             symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
35055                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
35056             },
35057             typePredicateToString: function (predicate, enclosingDeclaration, flags) {
35058                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
35059             },
35060             writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
35061                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
35062             },
35063             writeType: function (type, enclosingDeclaration, flags, writer) {
35064                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35065             },
35066             writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
35067                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
35068             },
35069             writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
35070                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35071             },
35072             getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
35073             getRootSymbols: getRootSymbols,
35074             getContextualType: function (nodeIn, contextFlags) {
35075                 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
35076                 if (!node) {
35077                     return undefined;
35078                 }
35079                 var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
35080                 var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
35081                 if (contextFlags & 4 /* Completions */ && containingCall) {
35082                     var toMarkSkip = node;
35083                     do {
35084                         getNodeLinks(toMarkSkip).skipDirectInference = true;
35085                         toMarkSkip = toMarkSkip.parent;
35086                     } while (toMarkSkip && toMarkSkip !== containingCall);
35087                     getNodeLinks(containingCall).resolvedSignature = undefined;
35088                 }
35089                 var result = getContextualType(node, contextFlags);
35090                 if (contextFlags & 4 /* Completions */ && containingCall) {
35091                     var toMarkSkip = node;
35092                     do {
35093                         getNodeLinks(toMarkSkip).skipDirectInference = undefined;
35094                         toMarkSkip = toMarkSkip.parent;
35095                     } while (toMarkSkip && toMarkSkip !== containingCall);
35096                     getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
35097                 }
35098                 return result;
35099             },
35100             getContextualTypeForObjectLiteralElement: function (nodeIn) {
35101                 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
35102                 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
35103             },
35104             getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
35105                 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35106                 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
35107             },
35108             getContextualTypeForJsxAttribute: function (nodeIn) {
35109                 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
35110                 return node && getContextualTypeForJsxAttribute(node);
35111             },
35112             isContextSensitive: isContextSensitive,
35113             getFullyQualifiedName: getFullyQualifiedName,
35114             getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
35115                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
35116             },
35117             getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
35118                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
35119             },
35120             getExpandedParameters: getExpandedParameters,
35121             hasEffectiveRestParameter: hasEffectiveRestParameter,
35122             getConstantValue: function (nodeIn) {
35123                 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
35124                 return node ? getConstantValue(node) : undefined;
35125             },
35126             isValidPropertyAccess: function (nodeIn, propertyName) {
35127                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
35128                 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
35129             },
35130             isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
35131                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
35132                 return !!node && isValidPropertyAccessForCompletions(node, type, property);
35133             },
35134             getSignatureFromDeclaration: function (declarationIn) {
35135                 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
35136                 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
35137             },
35138             isImplementationOfOverload: function (node) {
35139                 var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
35140                 return parsed ? isImplementationOfOverload(parsed) : undefined;
35141             },
35142             getImmediateAliasedSymbol: getImmediateAliasedSymbol,
35143             getAliasedSymbol: resolveAlias,
35144             getEmitResolver: getEmitResolver,
35145             getExportsOfModule: getExportsOfModuleAsArray,
35146             getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
35147             getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
35148             getAmbientModules: getAmbientModules,
35149             getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
35150             isOptionalParameter: function (nodeIn) {
35151                 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
35152                 return node ? isOptionalParameter(node) : false;
35153             },
35154             tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
35155             tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
35156             tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
35157                 // we deliberately exclude augmentations
35158                 // since we are only interested in declarations of the module itself
35159                 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
35160             },
35161             getApparentType: getApparentType,
35162             getUnionType: getUnionType,
35163             isTypeAssignableTo: isTypeAssignableTo,
35164             createAnonymousType: createAnonymousType,
35165             createSignature: createSignature,
35166             createSymbol: createSymbol,
35167             createIndexInfo: createIndexInfo,
35168             getAnyType: function () { return anyType; },
35169             getStringType: function () { return stringType; },
35170             getNumberType: function () { return numberType; },
35171             createPromiseType: createPromiseType,
35172             createArrayType: createArrayType,
35173             getElementTypeOfArrayType: getElementTypeOfArrayType,
35174             getBooleanType: function () { return booleanType; },
35175             getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
35176             getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
35177             getVoidType: function () { return voidType; },
35178             getUndefinedType: function () { return undefinedType; },
35179             getNullType: function () { return nullType; },
35180             getESSymbolType: function () { return esSymbolType; },
35181             getNeverType: function () { return neverType; },
35182             getOptionalType: function () { return optionalType; },
35183             isSymbolAccessible: isSymbolAccessible,
35184             isArrayType: isArrayType,
35185             isTupleType: isTupleType,
35186             isArrayLikeType: isArrayLikeType,
35187             isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
35188             getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
35189             getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
35190             getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
35191             getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35192             getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35193             getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
35194             getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
35195             getBaseConstraintOfType: getBaseConstraintOfType,
35196             getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
35197             resolveName: function (name, location, meaning, excludeGlobals) {
35198                 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
35199             },
35200             getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
35201             getAccessibleSymbolChain: getAccessibleSymbolChain,
35202             getTypePredicateOfSignature: getTypePredicateOfSignature,
35203             resolveExternalModuleName: function (moduleSpecifier) {
35204                 return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
35205             },
35206             resolveExternalModuleSymbol: resolveExternalModuleSymbol,
35207             tryGetThisTypeAt: function (node, includeGlobalThis) {
35208                 node = ts.getParseTreeNode(node);
35209                 return node && tryGetThisTypeAt(node, includeGlobalThis);
35210             },
35211             getTypeArgumentConstraint: function (nodeIn) {
35212                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
35213                 return node && getTypeArgumentConstraint(node);
35214             },
35215             getSuggestionDiagnostics: function (file, ct) {
35216                 if (ts.skipTypeChecking(file, compilerOptions, host)) {
35217                     return ts.emptyArray;
35218                 }
35219                 var diagnostics;
35220                 try {
35221                     // Record the cancellation token so it can be checked later on during checkSourceElement.
35222                     // Do this in a finally block so we can ensure that it gets reset back to nothing after
35223                     // this call is done.
35224                     cancellationToken = ct;
35225                     // Ensure file is type checked
35226                     checkSourceFile(file);
35227                     ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
35228                     diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
35229                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
35230                         if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
35231                             (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
35232                         }
35233                     });
35234                     return diagnostics || ts.emptyArray;
35235                 }
35236                 finally {
35237                     cancellationToken = undefined;
35238                 }
35239             },
35240             runWithCancellationToken: function (token, callback) {
35241                 try {
35242                     cancellationToken = token;
35243                     return callback(checker);
35244                 }
35245                 finally {
35246                     cancellationToken = undefined;
35247                 }
35248             },
35249             getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
35250             isDeclarationVisible: isDeclarationVisible,
35251         };
35252         function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
35253             var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35254             apparentArgumentCount = argumentCount;
35255             var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
35256             apparentArgumentCount = undefined;
35257             return res;
35258         }
35259         var tupleTypes = ts.createMap();
35260         var unionTypes = ts.createMap();
35261         var intersectionTypes = ts.createMap();
35262         var literalTypes = ts.createMap();
35263         var indexedAccessTypes = ts.createMap();
35264         var substitutionTypes = ts.createMap();
35265         var evolvingArrayTypes = [];
35266         var undefinedProperties = ts.createMap();
35267         var unknownSymbol = createSymbol(4 /* Property */, "unknown");
35268         var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
35269         var anyType = createIntrinsicType(1 /* Any */, "any");
35270         var autoType = createIntrinsicType(1 /* Any */, "any");
35271         var wildcardType = createIntrinsicType(1 /* Any */, "any");
35272         var errorType = createIntrinsicType(1 /* Any */, "error");
35273         var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
35274         var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
35275         var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
35276         var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
35277         var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
35278         var nullType = createIntrinsicType(65536 /* Null */, "null");
35279         var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
35280         var stringType = createIntrinsicType(4 /* String */, "string");
35281         var numberType = createIntrinsicType(8 /* Number */, "number");
35282         var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
35283         var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35284         var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35285         var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35286         var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35287         trueType.regularType = regularTrueType;
35288         trueType.freshType = trueType;
35289         regularTrueType.regularType = regularTrueType;
35290         regularTrueType.freshType = trueType;
35291         falseType.regularType = regularFalseType;
35292         falseType.freshType = falseType;
35293         regularFalseType.regularType = regularFalseType;
35294         regularFalseType.freshType = falseType;
35295         var booleanType = createBooleanType([regularFalseType, regularTrueType]);
35296         // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
35297         // (The union is cached, so simply doing the marking here is sufficient)
35298         createBooleanType([regularFalseType, trueType]);
35299         createBooleanType([falseType, regularTrueType]);
35300         createBooleanType([falseType, trueType]);
35301         var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
35302         var voidType = createIntrinsicType(16384 /* Void */, "void");
35303         var neverType = createIntrinsicType(131072 /* Never */, "never");
35304         var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
35305         var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
35306         var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
35307         var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
35308         var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
35309         var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
35310         var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
35311         var numberOrBigIntType = getUnionType([numberType, bigintType]);
35312         var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
35313         var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
35314         var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35315         var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35316         emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
35317         var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
35318         emptyTypeLiteralSymbol.members = ts.createSymbolTable();
35319         var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35320         var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35321         emptyGenericType.instantiations = ts.createMap();
35322         var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35323         // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
35324         // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
35325         anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
35326         var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35327         var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35328         var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35329         var markerSuperType = createTypeParameter();
35330         var markerSubType = createTypeParameter();
35331         markerSubType.constraint = markerSuperType;
35332         var markerOtherType = createTypeParameter();
35333         var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
35334         var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35335         var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35336         var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35337         var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35338         var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
35339         var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances
35340         var noIterationTypes = {
35341             get yieldType() { return ts.Debug.fail("Not supported"); },
35342             get returnType() { return ts.Debug.fail("Not supported"); },
35343             get nextType() { return ts.Debug.fail("Not supported"); },
35344         };
35345         var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
35346         var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
35347         var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
35348         var asyncIterationTypesResolver = {
35349             iterableCacheKey: "iterationTypesOfAsyncIterable",
35350             iteratorCacheKey: "iterationTypesOfAsyncIterator",
35351             iteratorSymbolName: "asyncIterator",
35352             getGlobalIteratorType: getGlobalAsyncIteratorType,
35353             getGlobalIterableType: getGlobalAsyncIterableType,
35354             getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
35355             getGlobalGeneratorType: getGlobalAsyncGeneratorType,
35356             resolveIterationType: getAwaitedType,
35357             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
35358             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
35359             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,
35360         };
35361         var syncIterationTypesResolver = {
35362             iterableCacheKey: "iterationTypesOfIterable",
35363             iteratorCacheKey: "iterationTypesOfIterator",
35364             iteratorSymbolName: "iterator",
35365             getGlobalIteratorType: getGlobalIteratorType,
35366             getGlobalIterableType: getGlobalIterableType,
35367             getGlobalIterableIteratorType: getGlobalIterableIteratorType,
35368             getGlobalGeneratorType: getGlobalGeneratorType,
35369             resolveIterationType: function (type, _errorNode) { return type; },
35370             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
35371             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
35372             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
35373         };
35374         /** Key is "/path/to/a.ts|/path/to/b.ts". */
35375         var amalgamatedDuplicates;
35376         var reverseMappedCache = ts.createMap();
35377         var ambientModulesCache;
35378         /**
35379          * List of every ambient module with a "*" wildcard.
35380          * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
35381          * This is only used if there is no exact match.
35382          */
35383         var patternAmbientModules;
35384         var patternAmbientModuleAugmentations;
35385         var globalObjectType;
35386         var globalFunctionType;
35387         var globalCallableFunctionType;
35388         var globalNewableFunctionType;
35389         var globalArrayType;
35390         var globalReadonlyArrayType;
35391         var globalStringType;
35392         var globalNumberType;
35393         var globalBooleanType;
35394         var globalRegExpType;
35395         var globalThisType;
35396         var anyArrayType;
35397         var autoArrayType;
35398         var anyReadonlyArrayType;
35399         var deferredGlobalNonNullableTypeAlias;
35400         // The library files are only loaded when the feature is used.
35401         // This allows users to just specify library files they want to used through --lib
35402         // and they will not get an error from not having unrelated library files
35403         var deferredGlobalESSymbolConstructorSymbol;
35404         var deferredGlobalESSymbolType;
35405         var deferredGlobalTypedPropertyDescriptorType;
35406         var deferredGlobalPromiseType;
35407         var deferredGlobalPromiseLikeType;
35408         var deferredGlobalPromiseConstructorSymbol;
35409         var deferredGlobalPromiseConstructorLikeType;
35410         var deferredGlobalIterableType;
35411         var deferredGlobalIteratorType;
35412         var deferredGlobalIterableIteratorType;
35413         var deferredGlobalGeneratorType;
35414         var deferredGlobalIteratorYieldResultType;
35415         var deferredGlobalIteratorReturnResultType;
35416         var deferredGlobalAsyncIterableType;
35417         var deferredGlobalAsyncIteratorType;
35418         var deferredGlobalAsyncIterableIteratorType;
35419         var deferredGlobalAsyncGeneratorType;
35420         var deferredGlobalTemplateStringsArrayType;
35421         var deferredGlobalImportMetaType;
35422         var deferredGlobalExtractSymbol;
35423         var deferredGlobalOmitSymbol;
35424         var deferredGlobalBigIntType;
35425         var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
35426         var flowLoopStart = 0;
35427         var flowLoopCount = 0;
35428         var sharedFlowCount = 0;
35429         var flowAnalysisDisabled = false;
35430         var flowInvocationCount = 0;
35431         var lastFlowNode;
35432         var lastFlowNodeReachable;
35433         var flowTypeCache;
35434         var emptyStringType = getLiteralType("");
35435         var zeroType = getLiteralType(0);
35436         var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
35437         var resolutionTargets = [];
35438         var resolutionResults = [];
35439         var resolutionPropertyNames = [];
35440         var suggestionCount = 0;
35441         var maximumSuggestionCount = 10;
35442         var mergedSymbols = [];
35443         var symbolLinks = [];
35444         var nodeLinks = [];
35445         var flowLoopCaches = [];
35446         var flowLoopNodes = [];
35447         var flowLoopKeys = [];
35448         var flowLoopTypes = [];
35449         var sharedFlowNodes = [];
35450         var sharedFlowTypes = [];
35451         var flowNodeReachable = [];
35452         var potentialThisCollisions = [];
35453         var potentialNewTargetCollisions = [];
35454         var potentialWeakMapCollisions = [];
35455         var awaitedTypeStack = [];
35456         var diagnostics = ts.createDiagnosticCollection();
35457         var suggestionDiagnostics = ts.createDiagnosticCollection();
35458         var typeofTypesByName = ts.createMapFromTemplate({
35459             string: stringType,
35460             number: numberType,
35461             bigint: bigintType,
35462             boolean: booleanType,
35463             symbol: esSymbolType,
35464             undefined: undefinedType
35465         });
35466         var typeofType = createTypeofType();
35467         var _jsxNamespace;
35468         var _jsxFactoryEntity;
35469         var outofbandVarianceMarkerHandler;
35470         var subtypeRelation = ts.createMap();
35471         var strictSubtypeRelation = ts.createMap();
35472         var assignableRelation = ts.createMap();
35473         var comparableRelation = ts.createMap();
35474         var identityRelation = ts.createMap();
35475         var enumRelation = ts.createMap();
35476         var builtinGlobals = ts.createSymbolTable();
35477         builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
35478         initializeTypeChecker();
35479         return checker;
35480         function getJsxNamespace(location) {
35481             if (location) {
35482                 var file = ts.getSourceFileOfNode(location);
35483                 if (file) {
35484                     if (file.localJsxNamespace) {
35485                         return file.localJsxNamespace;
35486                     }
35487                     var jsxPragma = file.pragmas.get("jsx");
35488                     if (jsxPragma) {
35489                         var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
35490                         file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
35491                         ts.visitNode(file.localJsxFactory, markAsSynthetic);
35492                         if (file.localJsxFactory) {
35493                             return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
35494                         }
35495                     }
35496                 }
35497             }
35498             if (!_jsxNamespace) {
35499                 _jsxNamespace = "React";
35500                 if (compilerOptions.jsxFactory) {
35501                     _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
35502                     ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
35503                     if (_jsxFactoryEntity) {
35504                         _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
35505                     }
35506                 }
35507                 else if (compilerOptions.reactNamespace) {
35508                     _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
35509                 }
35510             }
35511             if (!_jsxFactoryEntity) {
35512                 _jsxFactoryEntity = ts.createQualifiedName(ts.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
35513             }
35514             return _jsxNamespace;
35515             function markAsSynthetic(node) {
35516                 node.pos = -1;
35517                 node.end = -1;
35518                 return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
35519             }
35520         }
35521         function getEmitResolver(sourceFile, cancellationToken) {
35522             // Ensure we have all the type information in place for this file so that all the
35523             // emitter questions of this resolver will return the right information.
35524             getDiagnostics(sourceFile, cancellationToken);
35525             return emitResolver;
35526         }
35527         function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
35528             var diagnostic = location
35529                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35530                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35531             var existing = diagnostics.lookup(diagnostic);
35532             if (existing) {
35533                 return existing;
35534             }
35535             else {
35536                 diagnostics.add(diagnostic);
35537                 return diagnostic;
35538             }
35539         }
35540         function error(location, message, arg0, arg1, arg2, arg3) {
35541             var diagnostic = location
35542                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35543                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35544             diagnostics.add(diagnostic);
35545             return diagnostic;
35546         }
35547         function addErrorOrSuggestion(isError, diagnostic) {
35548             if (isError) {
35549                 diagnostics.add(diagnostic);
35550             }
35551             else {
35552                 suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
35553             }
35554         }
35555         function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
35556             addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
35557         }
35558         function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
35559             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
35560             if (maybeMissingAwait) {
35561                 var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
35562                 ts.addRelatedInfo(diagnostic, related);
35563             }
35564             return diagnostic;
35565         }
35566         function createSymbol(flags, name, checkFlags) {
35567             symbolCount++;
35568             var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
35569             symbol.checkFlags = checkFlags || 0;
35570             return symbol;
35571         }
35572         function getExcludedSymbolFlags(flags) {
35573             var result = 0;
35574             if (flags & 2 /* BlockScopedVariable */)
35575                 result |= 111551 /* BlockScopedVariableExcludes */;
35576             if (flags & 1 /* FunctionScopedVariable */)
35577                 result |= 111550 /* FunctionScopedVariableExcludes */;
35578             if (flags & 4 /* Property */)
35579                 result |= 0 /* PropertyExcludes */;
35580             if (flags & 8 /* EnumMember */)
35581                 result |= 900095 /* EnumMemberExcludes */;
35582             if (flags & 16 /* Function */)
35583                 result |= 110991 /* FunctionExcludes */;
35584             if (flags & 32 /* Class */)
35585                 result |= 899503 /* ClassExcludes */;
35586             if (flags & 64 /* Interface */)
35587                 result |= 788872 /* InterfaceExcludes */;
35588             if (flags & 256 /* RegularEnum */)
35589                 result |= 899327 /* RegularEnumExcludes */;
35590             if (flags & 128 /* ConstEnum */)
35591                 result |= 899967 /* ConstEnumExcludes */;
35592             if (flags & 512 /* ValueModule */)
35593                 result |= 110735 /* ValueModuleExcludes */;
35594             if (flags & 8192 /* Method */)
35595                 result |= 103359 /* MethodExcludes */;
35596             if (flags & 32768 /* GetAccessor */)
35597                 result |= 46015 /* GetAccessorExcludes */;
35598             if (flags & 65536 /* SetAccessor */)
35599                 result |= 78783 /* SetAccessorExcludes */;
35600             if (flags & 262144 /* TypeParameter */)
35601                 result |= 526824 /* TypeParameterExcludes */;
35602             if (flags & 524288 /* TypeAlias */)
35603                 result |= 788968 /* TypeAliasExcludes */;
35604             if (flags & 2097152 /* Alias */)
35605                 result |= 2097152 /* AliasExcludes */;
35606             return result;
35607         }
35608         function recordMergedSymbol(target, source) {
35609             if (!source.mergeId) {
35610                 source.mergeId = nextMergeId;
35611                 nextMergeId++;
35612             }
35613             mergedSymbols[source.mergeId] = target;
35614         }
35615         function cloneSymbol(symbol) {
35616             var result = createSymbol(symbol.flags, symbol.escapedName);
35617             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
35618             result.parent = symbol.parent;
35619             if (symbol.valueDeclaration)
35620                 result.valueDeclaration = symbol.valueDeclaration;
35621             if (symbol.constEnumOnlyModule)
35622                 result.constEnumOnlyModule = true;
35623             if (symbol.members)
35624                 result.members = ts.cloneMap(symbol.members);
35625             if (symbol.exports)
35626                 result.exports = ts.cloneMap(symbol.exports);
35627             recordMergedSymbol(result, symbol);
35628             return result;
35629         }
35630         /**
35631          * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
35632          * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
35633          */
35634         function mergeSymbol(target, source, unidirectional) {
35635             if (unidirectional === void 0) { unidirectional = false; }
35636             if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
35637                 (source.flags | target.flags) & 67108864 /* Assignment */) {
35638                 if (source === target) {
35639                     // This can happen when an export assigned namespace exports something also erroneously exported at the top level
35640                     // See `declarationFileNoCrashOnExtraExportModifier` for an example
35641                     return target;
35642                 }
35643                 if (!(target.flags & 33554432 /* Transient */)) {
35644                     var resolvedTarget = resolveSymbol(target);
35645                     if (resolvedTarget === unknownSymbol) {
35646                         return source;
35647                     }
35648                     target = cloneSymbol(resolvedTarget);
35649                 }
35650                 // Javascript static-property-assignment declarations always merge, even though they are also values
35651                 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
35652                     // reset flag when merging instantiated module into value module that has only const enums
35653                     target.constEnumOnlyModule = false;
35654                 }
35655                 target.flags |= source.flags;
35656                 if (source.valueDeclaration) {
35657                     ts.setValueDeclaration(target, source.valueDeclaration);
35658                 }
35659                 ts.addRange(target.declarations, source.declarations);
35660                 if (source.members) {
35661                     if (!target.members)
35662                         target.members = ts.createSymbolTable();
35663                     mergeSymbolTable(target.members, source.members, unidirectional);
35664                 }
35665                 if (source.exports) {
35666                     if (!target.exports)
35667                         target.exports = ts.createSymbolTable();
35668                     mergeSymbolTable(target.exports, source.exports, unidirectional);
35669                 }
35670                 if (!unidirectional) {
35671                     recordMergedSymbol(target, source);
35672                 }
35673             }
35674             else if (target.flags & 1024 /* NamespaceModule */) {
35675                 // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
35676                 // as we will already report a "Declaration name conflicts..." error, and this error
35677                 // won't make much sense.
35678                 if (target !== globalThisSymbol) {
35679                     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));
35680                 }
35681             }
35682             else { // error
35683                 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
35684                 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
35685                 var message = isEitherEnum
35686                     ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
35687                     : isEitherBlockScoped_1
35688                         ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
35689                         : ts.Diagnostics.Duplicate_identifier_0;
35690                 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
35691                 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
35692                 var symbolName_1 = symbolToString(source);
35693                 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
35694                 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
35695                     var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
35696                     var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
35697                     var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
35698                         return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() });
35699                     });
35700                     var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
35701                         return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
35702                     });
35703                     addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
35704                     addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
35705                 }
35706                 else {
35707                     addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
35708                     addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
35709                 }
35710             }
35711             return target;
35712             function addDuplicateLocations(locs, symbol) {
35713                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
35714                     var decl = _a[_i];
35715                     ts.pushIfUnique(locs, decl);
35716                 }
35717             }
35718         }
35719         function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
35720             ts.forEach(target.declarations, function (node) {
35721                 addDuplicateDeclarationError(node, message, symbolName, source.declarations);
35722             });
35723         }
35724         function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
35725             var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
35726             var err = lookupOrIssueError(errorNode, message, symbolName);
35727             var _loop_6 = function (relatedNode) {
35728                 var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
35729                 if (adjustedNode === errorNode)
35730                     return "continue";
35731                 err.relatedInformation = err.relatedInformation || [];
35732                 var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
35733                 var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
35734                 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 */; }))
35735                     return "continue";
35736                 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
35737             };
35738             for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
35739                 var relatedNode = _a[_i];
35740                 _loop_6(relatedNode);
35741             }
35742         }
35743         function combineSymbolTables(first, second) {
35744             if (!ts.hasEntries(first))
35745                 return second;
35746             if (!ts.hasEntries(second))
35747                 return first;
35748             var combined = ts.createSymbolTable();
35749             mergeSymbolTable(combined, first);
35750             mergeSymbolTable(combined, second);
35751             return combined;
35752         }
35753         function mergeSymbolTable(target, source, unidirectional) {
35754             if (unidirectional === void 0) { unidirectional = false; }
35755             source.forEach(function (sourceSymbol, id) {
35756                 var targetSymbol = target.get(id);
35757                 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
35758             });
35759         }
35760         function mergeModuleAugmentation(moduleName) {
35761             var _a, _b;
35762             var moduleAugmentation = moduleName.parent;
35763             if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
35764                 // this is a combined symbol for multiple augmentations within the same file.
35765                 // its symbol already has accumulated information for all declarations
35766                 // so we need to add it just once - do the work only for first declaration
35767                 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
35768                 return;
35769             }
35770             if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
35771                 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
35772             }
35773             else {
35774                 // find a module that about to be augmented
35775                 // do not validate names of augmentations that are defined in ambient context
35776                 var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
35777                     ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
35778                     : undefined;
35779                 var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
35780                 if (!mainModule_1) {
35781                     return;
35782                 }
35783                 // obtain item referenced by 'export='
35784                 mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
35785                 if (mainModule_1.flags & 1920 /* Namespace */) {
35786                     // If we're merging an augmentation to a pattern ambient module, we want to
35787                     // perform the merge unidirectionally from the augmentation ('a.foo') to
35788                     // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
35789                     // all the exports both from the pattern and from the augmentation, but
35790                     // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
35791                     if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
35792                         var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
35793                         if (!patternAmbientModuleAugmentations) {
35794                             patternAmbientModuleAugmentations = ts.createMap();
35795                         }
35796                         // moduleName will be a StringLiteral since this is not `declare global`.
35797                         patternAmbientModuleAugmentations.set(moduleName.text, merged);
35798                     }
35799                     else {
35800                         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)) {
35801                             // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
35802                             var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
35803                             for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) {
35804                                 var _d = _c[_i], key = _d[0], value = _d[1];
35805                                 if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
35806                                     mergeSymbol(resolvedExports.get(key), value);
35807                                 }
35808                             }
35809                         }
35810                         mergeSymbol(mainModule_1, moduleAugmentation.symbol);
35811                     }
35812                 }
35813                 else {
35814                     // moduleName will be a StringLiteral since this is not `declare global`.
35815                     error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
35816                 }
35817             }
35818         }
35819         function addToSymbolTable(target, source, message) {
35820             source.forEach(function (sourceSymbol, id) {
35821                 var targetSymbol = target.get(id);
35822                 if (targetSymbol) {
35823                     // Error on redeclarations
35824                     ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
35825                 }
35826                 else {
35827                     target.set(id, sourceSymbol);
35828                 }
35829             });
35830             function addDeclarationDiagnostic(id, message) {
35831                 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
35832             }
35833         }
35834         function getSymbolLinks(symbol) {
35835             if (symbol.flags & 33554432 /* Transient */)
35836                 return symbol;
35837             var id = getSymbolId(symbol);
35838             return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
35839         }
35840         function getNodeLinks(node) {
35841             var nodeId = getNodeId(node);
35842             return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
35843         }
35844         function isGlobalSourceFile(node) {
35845             return node.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
35846         }
35847         function getSymbol(symbols, name, meaning) {
35848             if (meaning) {
35849                 var symbol = getMergedSymbol(symbols.get(name));
35850                 if (symbol) {
35851                     ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
35852                     if (symbol.flags & meaning) {
35853                         return symbol;
35854                     }
35855                     if (symbol.flags & 2097152 /* Alias */) {
35856                         var target = resolveAlias(symbol);
35857                         // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
35858                         if (target === unknownSymbol || target.flags & meaning) {
35859                             return symbol;
35860                         }
35861                     }
35862                 }
35863             }
35864             // return undefined if we can't find a symbol.
35865         }
35866         /**
35867          * Get symbols that represent parameter-property-declaration as parameter and as property declaration
35868          * @param parameter a parameterDeclaration node
35869          * @param parameterName a name of the parameter to get the symbols for.
35870          * @return a tuple of two symbols
35871          */
35872         function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
35873             var constructorDeclaration = parameter.parent;
35874             var classDeclaration = parameter.parent.parent;
35875             var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
35876             var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
35877             if (parameterSymbol && propertySymbol) {
35878                 return [parameterSymbol, propertySymbol];
35879             }
35880             return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
35881         }
35882         function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
35883             var declarationFile = ts.getSourceFileOfNode(declaration);
35884             var useFile = ts.getSourceFileOfNode(usage);
35885             var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
35886             if (declarationFile !== useFile) {
35887                 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
35888                     (!compilerOptions.outFile && !compilerOptions.out) ||
35889                     isInTypeQuery(usage) ||
35890                     declaration.flags & 8388608 /* Ambient */) {
35891                     // nodes are in different files and order cannot be determined
35892                     return true;
35893                 }
35894                 // declaration is after usage
35895                 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
35896                 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
35897                     return true;
35898                 }
35899                 var sourceFiles = host.getSourceFiles();
35900                 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
35901             }
35902             if (declaration.pos <= usage.pos) {
35903                 // declaration is before usage
35904                 if (declaration.kind === 191 /* BindingElement */) {
35905                     // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
35906                     var errorBindingElement = ts.getAncestor(usage, 191 /* BindingElement */);
35907                     if (errorBindingElement) {
35908                         return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
35909                             declaration.pos < errorBindingElement.pos;
35910                     }
35911                     // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
35912                     return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 242 /* VariableDeclaration */), usage);
35913                 }
35914                 else if (declaration.kind === 242 /* VariableDeclaration */) {
35915                     // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
35916                     return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
35917                 }
35918                 else if (ts.isClassDeclaration(declaration)) {
35919                     // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
35920                     return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
35921                 }
35922                 else if (ts.isPropertyDeclaration(declaration)) {
35923                     // still might be illegal if a self-referencing property initializer (eg private x = this.x)
35924                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
35925                 }
35926                 else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
35927                     // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
35928                     return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
35929                         && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
35930                         && isUsedInFunctionOrInstanceProperty(usage, declaration));
35931                 }
35932                 return true;
35933             }
35934             // declaration is after usage, but it can still be legal if usage is deferred:
35935             // 1. inside an export specifier
35936             // 2. inside a function
35937             // 3. inside an instance property initializer, a reference to a non-instance property
35938             //    (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
35939             // 4. inside a static property initializer, a reference to a static method in the same class
35940             // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
35941             // or if usage is in a type context:
35942             // 1. inside a type query (typeof in type position)
35943             // 2. inside a jsdoc comment
35944             if (usage.parent.kind === 263 /* ExportSpecifier */ || (usage.parent.kind === 259 /* ExportAssignment */ && usage.parent.isExportEquals)) {
35945                 // export specifiers do not use the variable, they only make it available for use
35946                 return true;
35947             }
35948             // When resolving symbols for exports, the `usage` location passed in can be the export site directly
35949             if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) {
35950                 return true;
35951             }
35952             if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
35953                 return true;
35954             }
35955             if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
35956                 if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
35957                     && ts.getContainingClass(declaration)
35958                     && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
35959                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
35960                 }
35961                 else {
35962                     return true;
35963                 }
35964             }
35965             return false;
35966             function usageInTypeDeclaration() {
35967                 return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
35968             }
35969             function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
35970                 switch (declaration.parent.parent.kind) {
35971                     case 225 /* VariableStatement */:
35972                     case 230 /* ForStatement */:
35973                     case 232 /* ForOfStatement */:
35974                         // variable statement/for/for-of statement case,
35975                         // use site should not be inside variable declaration (initializer of declaration or binding element)
35976                         if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
35977                             return true;
35978                         }
35979                         break;
35980                 }
35981                 // ForIn/ForOf case - use site should not be used in expression part
35982                 var grandparent = declaration.parent.parent;
35983                 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
35984             }
35985             function isUsedInFunctionOrInstanceProperty(usage, declaration) {
35986                 return !!ts.findAncestor(usage, function (current) {
35987                     if (current === declContainer) {
35988                         return "quit";
35989                     }
35990                     if (ts.isFunctionLike(current)) {
35991                         return true;
35992                     }
35993                     var initializerOfProperty = current.parent &&
35994                         current.parent.kind === 159 /* PropertyDeclaration */ &&
35995                         current.parent.initializer === current;
35996                     if (initializerOfProperty) {
35997                         if (ts.hasModifier(current.parent, 32 /* Static */)) {
35998                             if (declaration.kind === 161 /* MethodDeclaration */) {
35999                                 return true;
36000                             }
36001                         }
36002                         else {
36003                             var isDeclarationInstanceProperty = declaration.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */);
36004                             if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
36005                                 return true;
36006                             }
36007                         }
36008                     }
36009                     return false;
36010                 });
36011             }
36012             /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
36013             function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
36014                 // always legal if usage is after declaration
36015                 if (usage.end > declaration.end) {
36016                     return false;
36017                 }
36018                 // still might be legal if usage is deferred (e.g. x: any = () => this.x)
36019                 // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
36020                 var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
36021                     if (node === declaration) {
36022                         return "quit";
36023                     }
36024                     switch (node.kind) {
36025                         case 202 /* ArrowFunction */:
36026                             return true;
36027                         case 159 /* PropertyDeclaration */:
36028                             // even when stopping at any property declaration, they need to come from the same class
36029                             return stopAtAnyPropertyDeclaration &&
36030                                 (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
36031                                     || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
36032                                 ? "quit" : true;
36033                         case 223 /* Block */:
36034                             switch (node.parent.kind) {
36035                                 case 163 /* GetAccessor */:
36036                                 case 161 /* MethodDeclaration */:
36037                                 case 164 /* SetAccessor */:
36038                                     return true;
36039                                 default:
36040                                     return false;
36041                             }
36042                         default:
36043                             return false;
36044                     }
36045                 });
36046                 return ancestorChangingReferenceScope === undefined;
36047             }
36048         }
36049         function useOuterVariableScopeInParameter(result, location, lastLocation) {
36050             var target = ts.getEmitScriptTarget(compilerOptions);
36051             var functionLocation = location;
36052             if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
36053                 // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
36054                 // - static field in a class expression
36055                 // - optional chaining pre-es2020
36056                 // - nullish coalesce pre-es2020
36057                 // - spread assignment in binding pattern pre-es2017
36058                 if (target >= 2 /* ES2015 */) {
36059                     var links = getNodeLinks(functionLocation);
36060                     if (links.declarationRequiresScopeChange === undefined) {
36061                         links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
36062                     }
36063                     return !links.declarationRequiresScopeChange;
36064                 }
36065             }
36066             return false;
36067             function requiresScopeChange(node) {
36068                 return requiresScopeChangeWorker(node.name)
36069                     || !!node.initializer && requiresScopeChangeWorker(node.initializer);
36070             }
36071             function requiresScopeChangeWorker(node) {
36072                 switch (node.kind) {
36073                     case 202 /* ArrowFunction */:
36074                     case 201 /* FunctionExpression */:
36075                     case 244 /* FunctionDeclaration */:
36076                     case 162 /* Constructor */:
36077                         // do not descend into these
36078                         return false;
36079                     case 161 /* MethodDeclaration */:
36080                     case 163 /* GetAccessor */:
36081                     case 164 /* SetAccessor */:
36082                     case 281 /* PropertyAssignment */:
36083                         return requiresScopeChangeWorker(node.name);
36084                     case 159 /* PropertyDeclaration */:
36085                         // static properties in classes introduce temporary variables
36086                         if (ts.hasStaticModifier(node)) {
36087                             return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields;
36088                         }
36089                         return requiresScopeChangeWorker(node.name);
36090                     default:
36091                         // null coalesce and optional chain pre-es2020 produce temporary variables
36092                         if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
36093                             return target < 7 /* ES2020 */;
36094                         }
36095                         if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
36096                             return target < 4 /* ES2017 */;
36097                         }
36098                         if (ts.isTypeNode(node))
36099                             return false;
36100                         return ts.forEachChild(node, requiresScopeChangeWorker) || false;
36101                 }
36102             }
36103         }
36104         /**
36105          * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
36106          * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
36107          * the given name can be found.
36108          *
36109          * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
36110          */
36111         function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
36112             if (excludeGlobals === void 0) { excludeGlobals = false; }
36113             return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
36114         }
36115         function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
36116             var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
36117             var result;
36118             var lastLocation;
36119             var lastSelfReferenceLocation;
36120             var propertyWithInvalidInitializer;
36121             var associatedDeclarationForContainingInitializerOrBindingName;
36122             var withinDeferredContext = false;
36123             var errorLocation = location;
36124             var grandparent;
36125             var isInExternalModule = false;
36126             loop: while (location) {
36127                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
36128                 if (location.locals && !isGlobalSourceFile(location)) {
36129                     if (result = lookup(location.locals, name, meaning)) {
36130                         var useResult = true;
36131                         if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
36132                             // symbol lookup restrictions for function-like declarations
36133                             // - Type parameters of a function are in scope in the entire function declaration, including the parameter
36134                             //   list and return type. However, local types are only in scope in the function body.
36135                             // - parameters are only in the scope of function body
36136                             // This restriction does not apply to JSDoc comment types because they are parented
36137                             // at a higher level than type parameters would normally be
36138                             if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 303 /* JSDocComment */) {
36139                                 useResult = result.flags & 262144 /* TypeParameter */
36140                                     // type parameters are visible in parameter list, return type and type parameter list
36141                                     ? lastLocation === location.type ||
36142                                         lastLocation.kind === 156 /* Parameter */ ||
36143                                         lastLocation.kind === 155 /* TypeParameter */
36144                                     // local types not visible outside the function body
36145                                     : false;
36146                             }
36147                             if (meaning & result.flags & 3 /* Variable */) {
36148                                 // expression inside parameter will lookup as normal variable scope when targeting es2015+
36149                                 if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
36150                                     useResult = false;
36151                                 }
36152                                 else if (result.flags & 1 /* FunctionScopedVariable */) {
36153                                     // parameters are visible only inside function body, parameter list and return type
36154                                     // technically for parameter list case here we might mix parameters and variables declared in function,
36155                                     // however it is detected separately when checking initializers of parameters
36156                                     // to make sure that they reference no variables declared after them.
36157                                     useResult =
36158                                         lastLocation.kind === 156 /* Parameter */ ||
36159                                             (lastLocation === location.type &&
36160                                                 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
36161                                 }
36162                             }
36163                         }
36164                         else if (location.kind === 180 /* ConditionalType */) {
36165                             // A type parameter declared using 'infer T' in a conditional type is visible only in
36166                             // the true branch of the conditional type.
36167                             useResult = lastLocation === location.trueType;
36168                         }
36169                         if (useResult) {
36170                             break loop;
36171                         }
36172                         else {
36173                             result = undefined;
36174                         }
36175                     }
36176                 }
36177                 withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
36178                 switch (location.kind) {
36179                     case 290 /* SourceFile */:
36180                         if (!ts.isExternalOrCommonJsModule(location))
36181                             break;
36182                         isInExternalModule = true;
36183                     // falls through
36184                     case 249 /* ModuleDeclaration */:
36185                         var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
36186                         if (location.kind === 290 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
36187                             // It's an external module. First see if the module has an export default and if the local
36188                             // name of that export default matches.
36189                             if (result = moduleExports.get("default" /* Default */)) {
36190                                 var localSymbol = ts.getLocalSymbolForExportDefault(result);
36191                                 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
36192                                     break loop;
36193                                 }
36194                                 result = undefined;
36195                             }
36196                             // Because of module/namespace merging, a module's exports are in scope,
36197                             // yet we never want to treat an export specifier as putting a member in scope.
36198                             // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
36199                             // Two things to note about this:
36200                             //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
36201                             //        on an export specifier is that it might find the export specifier itself, and try to
36202                             //        resolve it as an alias. This will cause the checker to consider the export specifier
36203                             //        a circular alias reference when it might not be.
36204                             //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
36205                             //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
36206                             //        which is not the desired behavior.
36207                             var moduleExport = moduleExports.get(name);
36208                             if (moduleExport &&
36209                                 moduleExport.flags === 2097152 /* Alias */ &&
36210                                 (ts.getDeclarationOfKind(moduleExport, 263 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 262 /* NamespaceExport */))) {
36211                                 break;
36212                             }
36213                         }
36214                         // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
36215                         if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
36216                             if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
36217                                 result = undefined;
36218                             }
36219                             else {
36220                                 break loop;
36221                             }
36222                         }
36223                         break;
36224                     case 248 /* EnumDeclaration */:
36225                         if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
36226                             break loop;
36227                         }
36228                         break;
36229                     case 159 /* PropertyDeclaration */:
36230                         // TypeScript 1.0 spec (April 2014): 8.4.1
36231                         // Initializer expressions for instance member variables are evaluated in the scope
36232                         // of the class constructor body but are not permitted to reference parameters or
36233                         // local variables of the constructor. This effectively means that entities from outer scopes
36234                         // by the same name as a constructor parameter or local variable are inaccessible
36235                         // in initializer expressions for instance member variables.
36236                         if (!ts.hasModifier(location, 32 /* Static */)) {
36237                             var ctor = findConstructorDeclaration(location.parent);
36238                             if (ctor && ctor.locals) {
36239                                 if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
36240                                     // Remember the property node, it will be used later to report appropriate error
36241                                     propertyWithInvalidInitializer = location;
36242                                 }
36243                             }
36244                         }
36245                         break;
36246                     case 245 /* ClassDeclaration */:
36247                     case 214 /* ClassExpression */:
36248                     case 246 /* InterfaceDeclaration */:
36249                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
36250                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
36251                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
36252                         if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
36253                             if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
36254                                 // ignore type parameters not declared in this container
36255                                 result = undefined;
36256                                 break;
36257                             }
36258                             if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) {
36259                                 // TypeScript 1.0 spec (April 2014): 3.4.1
36260                                 // The scope of a type parameter extends over the entire declaration with which the type
36261                                 // parameter list is associated, with the exception of static member declarations in classes.
36262                                 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
36263                                 return undefined;
36264                             }
36265                             break loop;
36266                         }
36267                         if (location.kind === 214 /* ClassExpression */ && meaning & 32 /* Class */) {
36268                             var className = location.name;
36269                             if (className && name === className.escapedText) {
36270                                 result = location.symbol;
36271                                 break loop;
36272                             }
36273                         }
36274                         break;
36275                     case 216 /* ExpressionWithTypeArguments */:
36276                         // The type parameters of a class are not in scope in the base class expression.
36277                         if (lastLocation === location.expression && location.parent.token === 90 /* ExtendsKeyword */) {
36278                             var container = location.parent.parent;
36279                             if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
36280                                 if (nameNotFoundMessage) {
36281                                     error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
36282                                 }
36283                                 return undefined;
36284                             }
36285                         }
36286                         break;
36287                     // It is not legal to reference a class's own type parameters from a computed property name that
36288                     // belongs to the class. For example:
36289                     //
36290                     //   function foo<T>() { return '' }
36291                     //   class C<T> { // <-- Class's own type parameter T
36292                     //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
36293                     //   }
36294                     //
36295                     case 154 /* ComputedPropertyName */:
36296                         grandparent = location.parent.parent;
36297                         if (ts.isClassLike(grandparent) || grandparent.kind === 246 /* InterfaceDeclaration */) {
36298                             // A reference to this grandparent's type parameters would be an error
36299                             if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
36300                                 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
36301                                 return undefined;
36302                             }
36303                         }
36304                         break;
36305                     case 202 /* ArrowFunction */:
36306                         // when targeting ES6 or higher there is no 'arguments' in an arrow function
36307                         // for lower compile targets the resolved symbol is used to emit an error
36308                         if (compilerOptions.target >= 2 /* ES2015 */) {
36309                             break;
36310                         }
36311                     // falls through
36312                     case 161 /* MethodDeclaration */:
36313                     case 162 /* Constructor */:
36314                     case 163 /* GetAccessor */:
36315                     case 164 /* SetAccessor */:
36316                     case 244 /* FunctionDeclaration */:
36317                         if (meaning & 3 /* Variable */ && name === "arguments") {
36318                             result = argumentsSymbol;
36319                             break loop;
36320                         }
36321                         break;
36322                     case 201 /* FunctionExpression */:
36323                         if (meaning & 3 /* Variable */ && name === "arguments") {
36324                             result = argumentsSymbol;
36325                             break loop;
36326                         }
36327                         if (meaning & 16 /* Function */) {
36328                             var functionName = location.name;
36329                             if (functionName && name === functionName.escapedText) {
36330                                 result = location.symbol;
36331                                 break loop;
36332                             }
36333                         }
36334                         break;
36335                     case 157 /* Decorator */:
36336                         // Decorators are resolved at the class declaration. Resolving at the parameter
36337                         // or member would result in looking up locals in the method.
36338                         //
36339                         //   function y() {}
36340                         //   class C {
36341                         //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
36342                         //   }
36343                         //
36344                         if (location.parent && location.parent.kind === 156 /* Parameter */) {
36345                             location = location.parent;
36346                         }
36347                         //
36348                         //   function y() {}
36349                         //   class C {
36350                         //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
36351                         //   }
36352                         //
36353                         // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
36354                         //
36355                         //   type T = number;
36356                         //   declare function y(x: T): any;
36357                         //   @param(1 as T) // <-- T should resolve to the type alias outside of class C
36358                         //   class C<T> {}
36359                         if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 245 /* ClassDeclaration */)) {
36360                             location = location.parent;
36361                         }
36362                         break;
36363                     case 322 /* JSDocTypedefTag */:
36364                     case 315 /* JSDocCallbackTag */:
36365                     case 316 /* JSDocEnumTag */:
36366                         // js type aliases do not resolve names from their host, so skip past it
36367                         location = ts.getJSDocHost(location);
36368                         break;
36369                     case 156 /* Parameter */:
36370                         if (lastLocation && (lastLocation === location.initializer ||
36371                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36372                             if (!associatedDeclarationForContainingInitializerOrBindingName) {
36373                                 associatedDeclarationForContainingInitializerOrBindingName = location;
36374                             }
36375                         }
36376                         break;
36377                     case 191 /* BindingElement */:
36378                         if (lastLocation && (lastLocation === location.initializer ||
36379                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36380                             var root = ts.getRootDeclaration(location);
36381                             if (root.kind === 156 /* Parameter */) {
36382                                 if (!associatedDeclarationForContainingInitializerOrBindingName) {
36383                                     associatedDeclarationForContainingInitializerOrBindingName = location;
36384                                 }
36385                             }
36386                         }
36387                         break;
36388                 }
36389                 if (isSelfReferenceLocation(location)) {
36390                     lastSelfReferenceLocation = location;
36391                 }
36392                 lastLocation = location;
36393                 location = location.parent;
36394             }
36395             // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
36396             // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
36397             // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
36398             if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
36399                 result.isReferenced |= meaning;
36400             }
36401             if (!result) {
36402                 if (lastLocation) {
36403                     ts.Debug.assert(lastLocation.kind === 290 /* SourceFile */);
36404                     if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
36405                         return lastLocation.symbol;
36406                     }
36407                 }
36408                 if (!excludeGlobals) {
36409                     result = lookup(globals, name, meaning);
36410                 }
36411             }
36412             if (!result) {
36413                 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
36414                     if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
36415                         return requireSymbol;
36416                     }
36417                 }
36418             }
36419             if (!result) {
36420                 if (nameNotFoundMessage) {
36421                     if (!errorLocation ||
36422                         !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
36423                             !checkAndReportErrorForExtendingInterface(errorLocation) &&
36424                             !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
36425                             !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
36426                             !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
36427                             !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
36428                             !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
36429                         var suggestion = void 0;
36430                         if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
36431                             suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
36432                             if (suggestion) {
36433                                 var suggestionName = symbolToString(suggestion);
36434                                 var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
36435                                 if (suggestion.valueDeclaration) {
36436                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
36437                                 }
36438                             }
36439                         }
36440                         if (!suggestion) {
36441                             error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
36442                         }
36443                         suggestionCount++;
36444                     }
36445                 }
36446                 return undefined;
36447             }
36448             // Perform extra checks only if error reporting was requested
36449             if (nameNotFoundMessage) {
36450                 if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
36451                     // We have a match, but the reference occurred within a property initializer and the identifier also binds
36452                     // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
36453                     // with ESNext+useDefineForClassFields because the scope semantics are different.
36454                     var propertyName = propertyWithInvalidInitializer.name;
36455                     error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
36456                     return undefined;
36457                 }
36458                 // Only check for block-scoped variable if we have an error location and are looking for the
36459                 // name with variable meaning
36460                 //      For example,
36461                 //          declare module foo {
36462                 //              interface bar {}
36463                 //          }
36464                 //      const foo/*1*/: foo/*2*/.bar;
36465                 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
36466                 // block-scoped variable and namespace module. However, only when we
36467                 // try to resolve name in /*1*/ which is used in variable position,
36468                 // we want to check for block-scoped
36469                 if (errorLocation &&
36470                     (meaning & 2 /* BlockScopedVariable */ ||
36471                         ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
36472                     var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
36473                     if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
36474                         checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
36475                     }
36476                 }
36477                 // If we're in an external module, we can't reference value symbols created from UMD export declarations
36478                 if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
36479                     var merged = getMergedSymbol(result);
36480                     if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
36481                         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));
36482                     }
36483                 }
36484                 // 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
36485                 if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
36486                     var candidate = getMergedSymbol(getLateBoundSymbol(result));
36487                     var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
36488                     // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
36489                     if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
36490                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
36491                     }
36492                     // And it cannot refer to any declarations which come after it
36493                     else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
36494                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
36495                     }
36496                 }
36497                 if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
36498                     checkSymbolUsageInExpressionContext(result, name, errorLocation);
36499                 }
36500             }
36501             return result;
36502         }
36503         function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
36504             if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
36505                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
36506                 if (typeOnlyDeclaration) {
36507                     var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36508                     var message = isExport
36509                         ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
36510                         : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
36511                     var relatedMessage = isExport
36512                         ? ts.Diagnostics._0_was_exported_here
36513                         : ts.Diagnostics._0_was_imported_here;
36514                     var unescapedName = ts.unescapeLeadingUnderscores(name);
36515                     ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
36516                 }
36517             }
36518         }
36519         function getIsDeferredContext(location, lastLocation) {
36520             if (location.kind !== 202 /* ArrowFunction */ && location.kind !== 201 /* FunctionExpression */) {
36521                 // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
36522                 return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
36523                     (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
36524             }
36525             if (lastLocation && lastLocation === location.name) {
36526                 return false;
36527             }
36528             // generator functions and async functions are not inlined in control flow when immediately invoked
36529             if (location.asteriskToken || ts.hasModifier(location, 256 /* Async */)) {
36530                 return true;
36531             }
36532             return !ts.getImmediatelyInvokedFunctionExpression(location);
36533         }
36534         function isSelfReferenceLocation(node) {
36535             switch (node.kind) {
36536                 case 244 /* FunctionDeclaration */:
36537                 case 245 /* ClassDeclaration */:
36538                 case 246 /* InterfaceDeclaration */:
36539                 case 248 /* EnumDeclaration */:
36540                 case 247 /* TypeAliasDeclaration */:
36541                 case 249 /* ModuleDeclaration */: // For `namespace N { N; }`
36542                     return true;
36543                 default:
36544                     return false;
36545             }
36546         }
36547         function diagnosticName(nameArg) {
36548             return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
36549         }
36550         function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
36551             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
36552                 var decl = _a[_i];
36553                 if (decl.kind === 155 /* TypeParameter */) {
36554                     var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
36555                     if (parent === container) {
36556                         return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
36557                     }
36558                 }
36559             }
36560             return false;
36561         }
36562         function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
36563             if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
36564                 return false;
36565             }
36566             var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
36567             var location = container;
36568             while (location) {
36569                 if (ts.isClassLike(location.parent)) {
36570                     var classSymbol = getSymbolOfNode(location.parent);
36571                     if (!classSymbol) {
36572                         break;
36573                     }
36574                     // Check to see if a static member exists.
36575                     var constructorType = getTypeOfSymbol(classSymbol);
36576                     if (getPropertyOfType(constructorType, name)) {
36577                         error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
36578                         return true;
36579                     }
36580                     // No static member is present.
36581                     // Check if we're in an instance method and look for a relevant instance member.
36582                     if (location === container && !ts.hasModifier(location, 32 /* Static */)) {
36583                         var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
36584                         if (getPropertyOfType(instanceType, name)) {
36585                             error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
36586                             return true;
36587                         }
36588                     }
36589                 }
36590                 location = location.parent;
36591             }
36592             return false;
36593         }
36594         function checkAndReportErrorForExtendingInterface(errorLocation) {
36595             var expression = getEntityNameForExtendingInterface(errorLocation);
36596             if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
36597                 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
36598                 return true;
36599             }
36600             return false;
36601         }
36602         /**
36603          * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
36604          * but returns undefined if that expression is not an EntityNameExpression.
36605          */
36606         function getEntityNameForExtendingInterface(node) {
36607             switch (node.kind) {
36608                 case 75 /* Identifier */:
36609                 case 194 /* PropertyAccessExpression */:
36610                     return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
36611                 case 216 /* ExpressionWithTypeArguments */:
36612                     if (ts.isEntityNameExpression(node.expression)) {
36613                         return node.expression;
36614                     }
36615                 // falls through
36616                 default:
36617                     return undefined;
36618             }
36619         }
36620         function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
36621             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
36622             if (meaning === namespaceMeaning) {
36623                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36624                 var parent = errorLocation.parent;
36625                 if (symbol) {
36626                     if (ts.isQualifiedName(parent)) {
36627                         ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
36628                         var propName = parent.right.escapedText;
36629                         var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
36630                         if (propType) {
36631                             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));
36632                             return true;
36633                         }
36634                     }
36635                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
36636                     return true;
36637                 }
36638             }
36639             return false;
36640         }
36641         function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
36642             if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
36643                 var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36644                 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
36645                     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));
36646                     return true;
36647                 }
36648             }
36649             return false;
36650         }
36651         function isPrimitiveTypeName(name) {
36652             return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
36653         }
36654         function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
36655             if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 263 /* ExportSpecifier */) {
36656                 error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
36657                 return true;
36658             }
36659             return false;
36660         }
36661         function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
36662             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
36663                 if (isPrimitiveTypeName(name)) {
36664                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
36665                     return true;
36666                 }
36667                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36668                 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
36669                     var message = isES2015OrLaterConstructorName(name)
36670                         ? 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
36671                         : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
36672                     error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
36673                     return true;
36674                 }
36675             }
36676             return false;
36677         }
36678         function isES2015OrLaterConstructorName(n) {
36679             switch (n) {
36680                 case "Promise":
36681                 case "Symbol":
36682                 case "Map":
36683                 case "WeakMap":
36684                 case "Set":
36685                 case "WeakSet":
36686                     return true;
36687             }
36688             return false;
36689         }
36690         function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
36691             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
36692                 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36693                 if (symbol) {
36694                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
36695                     return true;
36696                 }
36697             }
36698             else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
36699                 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36700                 if (symbol) {
36701                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
36702                     return true;
36703                 }
36704             }
36705             return false;
36706         }
36707         function checkResolvedBlockScopedVariable(result, errorLocation) {
36708             ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
36709             if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
36710                 // constructor functions aren't block scoped
36711                 return;
36712             }
36713             // Block-scoped variables cannot be used before their definition
36714             var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 248 /* EnumDeclaration */); });
36715             if (declaration === undefined)
36716                 return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
36717             if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
36718                 var diagnosticMessage = void 0;
36719                 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
36720                 if (result.flags & 2 /* BlockScopedVariable */) {
36721                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
36722                 }
36723                 else if (result.flags & 32 /* Class */) {
36724                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36725                 }
36726                 else if (result.flags & 256 /* RegularEnum */) {
36727                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
36728                 }
36729                 else {
36730                     ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
36731                     if (compilerOptions.preserveConstEnums) {
36732                         diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36733                     }
36734                 }
36735                 if (diagnosticMessage) {
36736                     ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
36737                 }
36738             }
36739         }
36740         /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
36741          * If at any point current node is equal to 'parent' node - return true.
36742          * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
36743          */
36744         function isSameScopeDescendentOf(initial, parent, stopAt) {
36745             return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
36746         }
36747         function getAnyImportSyntax(node) {
36748             switch (node.kind) {
36749                 case 253 /* ImportEqualsDeclaration */:
36750                     return node;
36751                 case 255 /* ImportClause */:
36752                     return node.parent;
36753                 case 256 /* NamespaceImport */:
36754                     return node.parent.parent;
36755                 case 258 /* ImportSpecifier */:
36756                     return node.parent.parent.parent;
36757                 default:
36758                     return undefined;
36759             }
36760         }
36761         function getDeclarationOfAliasSymbol(symbol) {
36762             return ts.find(symbol.declarations, isAliasSymbolDeclaration);
36763         }
36764         /**
36765          * An alias symbol is created by one of the following declarations:
36766          * import <symbol> = ...
36767          * import <symbol> from ...
36768          * import * as <symbol> from ...
36769          * import { x as <symbol> } from ...
36770          * export { x as <symbol> } from ...
36771          * export * as ns <symbol> from ...
36772          * export = <EntityNameExpression>
36773          * export default <EntityNameExpression>
36774          * module.exports = <EntityNameExpression>
36775          * {<Identifier>}
36776          * {name: <EntityNameExpression>}
36777          */
36778         function isAliasSymbolDeclaration(node) {
36779             return node.kind === 253 /* ImportEqualsDeclaration */ ||
36780                 node.kind === 252 /* NamespaceExportDeclaration */ ||
36781                 node.kind === 255 /* ImportClause */ && !!node.name ||
36782                 node.kind === 256 /* NamespaceImport */ ||
36783                 node.kind === 262 /* NamespaceExport */ ||
36784                 node.kind === 258 /* ImportSpecifier */ ||
36785                 node.kind === 263 /* ExportSpecifier */ ||
36786                 node.kind === 259 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ||
36787                 ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) ||
36788                 ts.isPropertyAccessExpression(node)
36789                     && ts.isBinaryExpression(node.parent)
36790                     && node.parent.left === node
36791                     && node.parent.operatorToken.kind === 62 /* EqualsToken */
36792                     && isAliasableOrJsExpression(node.parent.right) ||
36793                 node.kind === 282 /* ShorthandPropertyAssignment */ ||
36794                 node.kind === 281 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer);
36795         }
36796         function isAliasableOrJsExpression(e) {
36797             return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
36798         }
36799         function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
36800             if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
36801                 var immediate = resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node));
36802                 var resolved_4 = resolveExternalModuleSymbol(immediate);
36803                 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
36804                 return resolved_4;
36805             }
36806             var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
36807             checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
36808             return resolved;
36809         }
36810         function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
36811             if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
36812                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
36813                 var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36814                 var message = isExport
36815                     ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
36816                     : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
36817                 var relatedMessage = isExport
36818                     ? ts.Diagnostics._0_was_exported_here
36819                     : ts.Diagnostics._0_was_imported_here;
36820                 // Non-null assertion is safe because the optionality comes from ImportClause,
36821                 // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
36822                 var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
36823                 ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
36824             }
36825         }
36826         function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
36827             var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
36828             if (exportValue) {
36829                 return getPropertyOfType(getTypeOfSymbol(exportValue), name);
36830             }
36831             var exportSymbol = moduleSymbol.exports.get(name);
36832             var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
36833             markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
36834             return resolved;
36835         }
36836         function isSyntacticDefault(node) {
36837             return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
36838         }
36839         function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
36840             if (!allowSyntheticDefaultImports) {
36841                 return false;
36842             }
36843             // Declaration files (and ambient modules)
36844             if (!file || file.isDeclarationFile) {
36845                 // Definitely cannot have a synthetic default if they have a syntactic default member specified
36846                 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
36847                 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
36848                     return false;
36849                 }
36850                 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
36851                 // So we check a bit more,
36852                 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
36853                     // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
36854                     // it definitely is a module and does not have a synthetic default
36855                     return false;
36856                 }
36857                 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
36858                 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
36859                 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
36860                 return true;
36861             }
36862             // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
36863             if (!ts.isSourceFileJS(file)) {
36864                 return hasExportAssignmentSymbol(moduleSymbol);
36865             }
36866             // 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
36867             return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
36868         }
36869         function getTargetOfImportClause(node, dontResolveAlias) {
36870             var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
36871             if (moduleSymbol) {
36872                 var exportDefaultSymbol = void 0;
36873                 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
36874                     exportDefaultSymbol = moduleSymbol;
36875                 }
36876                 else {
36877                     exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
36878                 }
36879                 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
36880                 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
36881                 if (!exportDefaultSymbol && !hasSyntheticDefault) {
36882                     if (hasExportAssignmentSymbol(moduleSymbol)) {
36883                         var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
36884                         var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
36885                         var exportAssignment = exportEqualsSymbol.valueDeclaration;
36886                         var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
36887                         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));
36888                     }
36889                     else {
36890                         reportNonDefaultExport(moduleSymbol, node);
36891                     }
36892                 }
36893                 else if (hasSyntheticDefault) {
36894                     // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
36895                     var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
36896                     markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
36897                     return resolved;
36898                 }
36899                 markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
36900                 return exportDefaultSymbol;
36901             }
36902         }
36903         function reportNonDefaultExport(moduleSymbol, node) {
36904             var _a, _b;
36905             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
36906                 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));
36907             }
36908             else {
36909                 var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
36910                 var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
36911                 if (exportStar) {
36912                     var defaultExport = ts.find(exportStar.declarations, function (decl) {
36913                         var _a, _b;
36914                         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 */)));
36915                     });
36916                     if (defaultExport) {
36917                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
36918                     }
36919                 }
36920             }
36921         }
36922         function getTargetOfNamespaceImport(node, dontResolveAlias) {
36923             var moduleSpecifier = node.parent.parent.moduleSpecifier;
36924             var immediate = resolveExternalModuleName(node, moduleSpecifier);
36925             var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
36926             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
36927             return resolved;
36928         }
36929         function getTargetOfNamespaceExport(node, dontResolveAlias) {
36930             var moduleSpecifier = node.parent.moduleSpecifier;
36931             var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
36932             var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
36933             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
36934             return resolved;
36935         }
36936         // This function creates a synthetic symbol that combines the value side of one symbol with the
36937         // type/namespace side of another symbol. Consider this example:
36938         //
36939         //   declare module graphics {
36940         //       interface Point {
36941         //           x: number;
36942         //           y: number;
36943         //       }
36944         //   }
36945         //   declare var graphics: {
36946         //       Point: new (x: number, y: number) => graphics.Point;
36947         //   }
36948         //   declare module "graphics" {
36949         //       export = graphics;
36950         //   }
36951         //
36952         // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
36953         // property with the type/namespace side interface 'Point'.
36954         function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
36955             if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
36956                 return unknownSymbol;
36957             }
36958             if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
36959                 return valueSymbol;
36960             }
36961             var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
36962             result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
36963             result.parent = valueSymbol.parent || typeSymbol.parent;
36964             if (valueSymbol.valueDeclaration)
36965                 result.valueDeclaration = valueSymbol.valueDeclaration;
36966             if (typeSymbol.members)
36967                 result.members = ts.cloneMap(typeSymbol.members);
36968             if (valueSymbol.exports)
36969                 result.exports = ts.cloneMap(valueSymbol.exports);
36970             return result;
36971         }
36972         function getExportOfModule(symbol, specifier, dontResolveAlias) {
36973             var _a;
36974             if (symbol.flags & 1536 /* Module */) {
36975                 var name = ((_a = specifier.propertyName) !== null && _a !== void 0 ? _a : specifier.name).escapedText;
36976                 var exportSymbol = getExportsOfSymbol(symbol).get(name);
36977                 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
36978                 markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
36979                 return resolved;
36980             }
36981         }
36982         function getPropertyOfVariable(symbol, name) {
36983             if (symbol.flags & 3 /* Variable */) {
36984                 var typeAnnotation = symbol.valueDeclaration.type;
36985                 if (typeAnnotation) {
36986                     return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
36987                 }
36988             }
36989         }
36990         function getExternalModuleMember(node, specifier, dontResolveAlias) {
36991             var _a;
36992             if (dontResolveAlias === void 0) { dontResolveAlias = false; }
36993             var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217
36994             var name = specifier.propertyName || specifier.name;
36995             var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
36996             var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias, suppressInteropError);
36997             if (targetSymbol) {
36998                 if (name.escapedText) {
36999                     if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
37000                         return moduleSymbol;
37001                     }
37002                     var symbolFromVariable = void 0;
37003                     // First check if module was specified with "export=". If so, get the member from the resolved type
37004                     if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
37005                         symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
37006                     }
37007                     else {
37008                         symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
37009                     }
37010                     // if symbolFromVariable is export - get its final target
37011                     symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
37012                     var symbolFromModule = getExportOfModule(targetSymbol, specifier, dontResolveAlias);
37013                     if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
37014                         var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
37015                         if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
37016                             symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
37017                         }
37018                     }
37019                     var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
37020                         combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
37021                         symbolFromModule || symbolFromVariable;
37022                     if (!symbol) {
37023                         var moduleName = getFullyQualifiedName(moduleSymbol, node);
37024                         var declarationName = ts.declarationNameToString(name);
37025                         var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
37026                         if (suggestion !== undefined) {
37027                             var suggestionName = symbolToString(suggestion);
37028                             var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
37029                             if (suggestion.valueDeclaration) {
37030                                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
37031                             }
37032                         }
37033                         else {
37034                             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
37035                                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
37036                             }
37037                             else {
37038                                 reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
37039                             }
37040                         }
37041                     }
37042                     return symbol;
37043                 }
37044             }
37045         }
37046         function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
37047             var _a;
37048             var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
37049             var exports = moduleSymbol.exports;
37050             if (localSymbol) {
37051                 var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
37052                 if (exportedEqualsSymbol) {
37053                     getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
37054                         error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37055                 }
37056                 else {
37057                     var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
37058                     var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
37059                         error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
37060                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
37061                         return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
37062                     })));
37063                 }
37064             }
37065             else {
37066                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37067             }
37068         }
37069         function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
37070             if (moduleKind >= ts.ModuleKind.ES2015) {
37071                 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
37072                     ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37073                 error(name, message, declarationName);
37074             }
37075             else {
37076                 if (ts.isInJSFile(node)) {
37077                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
37078                         ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37079                     error(name, message, declarationName);
37080                 }
37081                 else {
37082                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
37083                         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;
37084                     error(name, message, declarationName, declarationName, moduleName);
37085                 }
37086             }
37087         }
37088         function getTargetOfImportSpecifier(node, dontResolveAlias) {
37089             var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
37090             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37091             return resolved;
37092         }
37093         function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
37094             var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
37095             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37096             return resolved;
37097         }
37098         function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
37099             var resolved = node.parent.parent.moduleSpecifier ?
37100                 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
37101                 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
37102             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37103             return resolved;
37104         }
37105         function getTargetOfExportAssignment(node, dontResolveAlias) {
37106             var expression = ts.isExportAssignment(node) ? node.expression : node.right;
37107             var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
37108             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37109             return resolved;
37110         }
37111         function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
37112             if (ts.isClassExpression(expression)) {
37113                 return checkExpressionCached(expression).symbol;
37114             }
37115             if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
37116                 return undefined;
37117             }
37118             var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
37119             if (aliasLike) {
37120                 return aliasLike;
37121             }
37122             checkExpressionCached(expression);
37123             return getNodeLinks(expression).resolvedSymbol;
37124         }
37125         function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
37126             var expression = node.initializer;
37127             return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
37128         }
37129         function getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve) {
37130             if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
37131                 return undefined;
37132             }
37133             return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
37134         }
37135         function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
37136             if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
37137             switch (node.kind) {
37138                 case 253 /* ImportEqualsDeclaration */:
37139                     return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
37140                 case 255 /* ImportClause */:
37141                     return getTargetOfImportClause(node, dontRecursivelyResolve);
37142                 case 256 /* NamespaceImport */:
37143                     return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
37144                 case 262 /* NamespaceExport */:
37145                     return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
37146                 case 258 /* ImportSpecifier */:
37147                     return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
37148                 case 263 /* ExportSpecifier */:
37149                     return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
37150                 case 259 /* ExportAssignment */:
37151                 case 209 /* BinaryExpression */:
37152                     return getTargetOfExportAssignment(node, dontRecursivelyResolve);
37153                 case 252 /* NamespaceExportDeclaration */:
37154                     return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
37155                 case 282 /* ShorthandPropertyAssignment */:
37156                     return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
37157                 case 281 /* PropertyAssignment */:
37158                     return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
37159                 case 194 /* PropertyAccessExpression */:
37160                     return getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve);
37161                 default:
37162                     return ts.Debug.fail();
37163             }
37164         }
37165         /**
37166          * Indicates that a symbol is an alias that does not merge with a local declaration.
37167          * OR Is a JSContainer which may merge an alias with a local declaration
37168          */
37169         function isNonLocalAlias(symbol, excludes) {
37170             if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
37171             if (!symbol)
37172                 return false;
37173             return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
37174         }
37175         function resolveSymbol(symbol, dontResolveAlias) {
37176             return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
37177         }
37178         function resolveAlias(symbol) {
37179             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
37180             var links = getSymbolLinks(symbol);
37181             if (!links.target) {
37182                 links.target = resolvingSymbol;
37183                 var node = getDeclarationOfAliasSymbol(symbol);
37184                 if (!node)
37185                     return ts.Debug.fail();
37186                 var target = getTargetOfAliasDeclaration(node);
37187                 if (links.target === resolvingSymbol) {
37188                     links.target = target || unknownSymbol;
37189                 }
37190                 else {
37191                     error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
37192                 }
37193             }
37194             else if (links.target === resolvingSymbol) {
37195                 links.target = unknownSymbol;
37196             }
37197             return links.target;
37198         }
37199         function tryResolveAlias(symbol) {
37200             var links = getSymbolLinks(symbol);
37201             if (links.target !== resolvingSymbol) {
37202                 return resolveAlias(symbol);
37203             }
37204             return undefined;
37205         }
37206         /**
37207          * Marks a symbol as type-only if its declaration is syntactically type-only.
37208          * If it is not itself marked type-only, but resolves to a type-only alias
37209          * somewhere in its resolution chain, save a reference to the type-only alias declaration
37210          * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
37211          *
37212          * This function is called on each alias declaration that could be type-only or resolve to
37213          * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
37214          * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
37215          * and issue an error if so.
37216          *
37217          * @param aliasDeclaration The alias declaration not marked as type-only
37218          * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
37219          * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
37220          * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
37221          * must still be checked for a type-only marker, overwriting the previous negative result if found.
37222          * @param immediateTarget The symbol to which the alias declaration immediately resolves
37223          * @param finalTarget The symbol to which the alias declaration ultimately resolves
37224          * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
37225          */
37226         function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
37227             if (!aliasDeclaration)
37228                 return false;
37229             // If the declaration itself is type-only, mark it and return.
37230             // No need to check what it resolves to.
37231             var sourceSymbol = getSymbolOfNode(aliasDeclaration);
37232             if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
37233                 var links_1 = getSymbolLinks(sourceSymbol);
37234                 links_1.typeOnlyDeclaration = aliasDeclaration;
37235                 return true;
37236             }
37237             var links = getSymbolLinks(sourceSymbol);
37238             return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
37239                 || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
37240         }
37241         function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
37242             var _a, _b, _c;
37243             if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
37244                 var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
37245                 var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
37246                 aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
37247             }
37248             return !!aliasDeclarationLinks.typeOnlyDeclaration;
37249         }
37250         /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
37251         function getTypeOnlyAliasDeclaration(symbol) {
37252             if (!(symbol.flags & 2097152 /* Alias */)) {
37253                 return undefined;
37254             }
37255             var links = getSymbolLinks(symbol);
37256             return links.typeOnlyDeclaration || undefined;
37257         }
37258         function markExportAsReferenced(node) {
37259             var symbol = getSymbolOfNode(node);
37260             var target = resolveAlias(symbol);
37261             if (target) {
37262                 var markAlias = target === unknownSymbol ||
37263                     ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
37264                 if (markAlias) {
37265                     markAliasSymbolAsReferenced(symbol);
37266                 }
37267             }
37268         }
37269         // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
37270         // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
37271         // the alias as an expression (which recursively takes us back here if the target references another alias).
37272         function markAliasSymbolAsReferenced(symbol) {
37273             var links = getSymbolLinks(symbol);
37274             if (!links.referenced) {
37275                 links.referenced = true;
37276                 var node = getDeclarationOfAliasSymbol(symbol);
37277                 if (!node)
37278                     return ts.Debug.fail();
37279                 // We defer checking of the reference of an `import =` until the import itself is referenced,
37280                 // This way a chain of imports can be elided if ultimately the final input is only used in a type
37281                 // position.
37282                 if (ts.isInternalModuleImportEqualsDeclaration(node)) {
37283                     var target = resolveSymbol(symbol);
37284                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
37285                         // import foo = <symbol>
37286                         checkExpressionCached(node.moduleReference);
37287                     }
37288                 }
37289             }
37290         }
37291         // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
37292         // but their usage in value positions must be tracked to determine if the import can be type-only.
37293         function markConstEnumAliasAsReferenced(symbol) {
37294             var links = getSymbolLinks(symbol);
37295             if (!links.constEnumReferenced) {
37296                 links.constEnumReferenced = true;
37297             }
37298         }
37299         // This function is only for imports with entity names
37300         function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
37301             // There are three things we might try to look for. In the following examples,
37302             // the search term is enclosed in |...|:
37303             //
37304             //     import a = |b|; // Namespace
37305             //     import a = |b.c|; // Value, type, namespace
37306             //     import a = |b.c|.d; // Namespace
37307             if (entityName.kind === 75 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
37308                 entityName = entityName.parent;
37309             }
37310             // Check for case 1 and 3 in the above example
37311             if (entityName.kind === 75 /* Identifier */ || entityName.parent.kind === 153 /* QualifiedName */) {
37312                 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37313             }
37314             else {
37315                 // Case 2 in above example
37316                 // entityName.kind could be a QualifiedName or a Missing identifier
37317                 ts.Debug.assert(entityName.parent.kind === 253 /* ImportEqualsDeclaration */);
37318                 return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37319             }
37320         }
37321         function getFullyQualifiedName(symbol, containingLocation) {
37322             return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
37323         }
37324         /**
37325          * Resolves a qualified name and any involved aliases.
37326          */
37327         function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
37328             if (ts.nodeIsMissing(name)) {
37329                 return undefined;
37330             }
37331             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
37332             var symbol;
37333             if (name.kind === 75 /* Identifier */) {
37334                 var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
37335                 var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
37336                 symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true));
37337                 if (!symbol) {
37338                     return getMergedSymbol(symbolFromJSPrototype);
37339                 }
37340             }
37341             else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) {
37342                 var left = name.kind === 153 /* QualifiedName */ ? name.left : name.expression;
37343                 var right = name.kind === 153 /* QualifiedName */ ? name.right : name.name;
37344                 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
37345                 if (!namespace || ts.nodeIsMissing(right)) {
37346                     return undefined;
37347                 }
37348                 else if (namespace === unknownSymbol) {
37349                     return namespace;
37350                 }
37351                 if (ts.isInJSFile(name)) {
37352                     if (namespace.valueDeclaration &&
37353                         ts.isVariableDeclaration(namespace.valueDeclaration) &&
37354                         namespace.valueDeclaration.initializer &&
37355                         isCommonJsRequire(namespace.valueDeclaration.initializer)) {
37356                         var moduleName = namespace.valueDeclaration.initializer.arguments[0];
37357                         var moduleSym = resolveExternalModuleName(moduleName, moduleName);
37358                         if (moduleSym) {
37359                             var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
37360                             if (resolvedModuleSymbol) {
37361                                 namespace = resolvedModuleSymbol;
37362                             }
37363                         }
37364                     }
37365                 }
37366                 symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
37367                 if (!symbol) {
37368                     if (!ignoreErrors) {
37369                         error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
37370                     }
37371                     return undefined;
37372                 }
37373             }
37374             else {
37375                 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
37376             }
37377             ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
37378             if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 259 /* ExportAssignment */)) {
37379                 markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
37380             }
37381             return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
37382         }
37383         /**
37384          * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
37385          * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
37386          * name resolution won't work either.
37387          * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
37388          */
37389         function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
37390             if (isJSDocTypeReference(name.parent)) {
37391                 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
37392                 if (secondaryLocation) {
37393                     return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
37394                 }
37395             }
37396         }
37397         function getAssignmentDeclarationLocation(node) {
37398             var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
37399             if (typeAlias) {
37400                 return;
37401             }
37402             var host = ts.getJSDocHost(node);
37403             if (ts.isExpressionStatement(host) &&
37404                 ts.isBinaryExpression(host.expression) &&
37405                 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
37406                 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
37407                 var symbol = getSymbolOfNode(host.expression.left);
37408                 if (symbol) {
37409                     return getDeclarationOfJSPrototypeContainer(symbol);
37410                 }
37411             }
37412             if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
37413                 ts.isBinaryExpression(host.parent.parent) &&
37414                 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
37415                 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
37416                 var symbol = getSymbolOfNode(host.parent.parent.left);
37417                 if (symbol) {
37418                     return getDeclarationOfJSPrototypeContainer(symbol);
37419                 }
37420             }
37421             var sig = ts.getEffectiveJSDocHost(node);
37422             if (sig && ts.isFunctionLike(sig)) {
37423                 var symbol = getSymbolOfNode(sig);
37424                 return symbol && symbol.valueDeclaration;
37425             }
37426         }
37427         function getDeclarationOfJSPrototypeContainer(symbol) {
37428             var decl = symbol.parent.valueDeclaration;
37429             if (!decl) {
37430                 return undefined;
37431             }
37432             var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
37433                 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
37434                     undefined;
37435             return initializer || decl;
37436         }
37437         /**
37438          * Get the real symbol of a declaration with an expando initializer.
37439          *
37440          * Normally, declarations have an associated symbol, but when a declaration has an expando
37441          * initializer, the expando's symbol is the one that has all the members merged into it.
37442          */
37443         function getExpandoSymbol(symbol) {
37444             var decl = symbol.valueDeclaration;
37445             if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
37446                 return undefined;
37447             }
37448             var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
37449             if (init) {
37450                 var initSymbol = getSymbolOfNode(init);
37451                 if (initSymbol) {
37452                     return mergeJSSymbols(initSymbol, symbol);
37453                 }
37454             }
37455         }
37456         function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
37457             return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations);
37458         }
37459         function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
37460             if (isForAugmentation === void 0) { isForAugmentation = false; }
37461             return ts.isStringLiteralLike(moduleReferenceExpression)
37462                 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
37463                 : undefined;
37464         }
37465         function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
37466             if (isForAugmentation === void 0) { isForAugmentation = false; }
37467             if (ts.startsWith(moduleReference, "@types/")) {
37468                 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
37469                 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
37470                 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
37471             }
37472             var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
37473             if (ambientModule) {
37474                 return ambientModule;
37475             }
37476             var currentSourceFile = ts.getSourceFileOfNode(location);
37477             var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
37478             var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
37479             var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
37480             if (sourceFile) {
37481                 if (sourceFile.symbol) {
37482                     if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
37483                         errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
37484                     }
37485                     // merged symbol is module declaration symbol combined with all augmentations
37486                     return getMergedSymbol(sourceFile.symbol);
37487                 }
37488                 if (moduleNotFoundError) {
37489                     // report errors only if it was requested
37490                     error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
37491                 }
37492                 return undefined;
37493             }
37494             if (patternAmbientModules) {
37495                 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
37496                 if (pattern) {
37497                     // If the module reference matched a pattern ambient module ('*.foo') but there's also a
37498                     // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
37499                     // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
37500                     // from a.foo.
37501                     var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
37502                     if (augmentation) {
37503                         return getMergedSymbol(augmentation);
37504                     }
37505                     return getMergedSymbol(pattern.symbol);
37506                 }
37507             }
37508             // May be an untyped module. If so, ignore resolutionDiagnostic.
37509             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) {
37510                 if (isForAugmentation) {
37511                     var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
37512                     error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
37513                 }
37514                 else {
37515                     errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
37516                 }
37517                 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
37518                 return undefined;
37519             }
37520             if (moduleNotFoundError) {
37521                 // See if this was possibly a projectReference redirect
37522                 if (resolvedModule) {
37523                     var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
37524                     if (redirect) {
37525                         error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
37526                         return undefined;
37527                     }
37528                 }
37529                 if (resolutionDiagnostic) {
37530                     error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
37531                 }
37532                 else {
37533                     var tsExtension = ts.tryExtractTSExtension(moduleReference);
37534                     if (tsExtension) {
37535                         var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
37536                         error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
37537                     }
37538                     else if (!compilerOptions.resolveJsonModule &&
37539                         ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
37540                         ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
37541                         ts.hasJsonModuleEmitEnabled(compilerOptions)) {
37542                         error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
37543                     }
37544                     else {
37545                         error(errorNode, moduleNotFoundError, moduleReference);
37546                     }
37547                 }
37548             }
37549             return undefined;
37550         }
37551         function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
37552             var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
37553             var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
37554                 ? typesPackageExists(packageId.name)
37555                     ? ts.chainDiagnosticMessages(
37556                     /*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))
37557                     : ts.chainDiagnosticMessages(
37558                     /*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))
37559                 : undefined;
37560             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));
37561         }
37562         function typesPackageExists(packageName) {
37563             return getPackagesSet().has(ts.getTypesPackageName(packageName));
37564         }
37565         function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
37566             if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
37567                 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
37568                 var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
37569                 return getMergedSymbol(exported) || moduleSymbol;
37570             }
37571             return undefined;
37572         }
37573         function getCommonJsExportEquals(exported, moduleSymbol) {
37574             if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
37575                 return exported;
37576             }
37577             var links = getSymbolLinks(exported);
37578             if (links.cjsExportMerged) {
37579                 return links.cjsExportMerged;
37580             }
37581             var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
37582             merged.flags = merged.flags | 512 /* ValueModule */;
37583             if (merged.exports === undefined) {
37584                 merged.exports = ts.createSymbolTable();
37585             }
37586             moduleSymbol.exports.forEach(function (s, name) {
37587                 if (name === "export=" /* ExportEquals */)
37588                     return;
37589                 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
37590             });
37591             getSymbolLinks(merged).cjsExportMerged = merged;
37592             return links.cjsExportMerged = merged;
37593         }
37594         // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
37595         // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
37596         // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
37597         function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
37598             var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
37599             if (!dontResolveAlias && symbol) {
37600                 if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 290 /* SourceFile */)) {
37601                     var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
37602                         ? "allowSyntheticDefaultImports"
37603                         : "esModuleInterop";
37604                     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);
37605                     return symbol;
37606                 }
37607                 if (compilerOptions.esModuleInterop) {
37608                     var referenceParent = referencingLocation.parent;
37609                     if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
37610                         ts.isImportCall(referenceParent)) {
37611                         var type = getTypeOfSymbol(symbol);
37612                         var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
37613                         if (!sigs || !sigs.length) {
37614                             sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
37615                         }
37616                         if (sigs && sigs.length) {
37617                             var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
37618                             // Create a new symbol which has the module's type less the call and construct signatures
37619                             var result = createSymbol(symbol.flags, symbol.escapedName);
37620                             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
37621                             result.parent = symbol.parent;
37622                             result.target = symbol;
37623                             result.originatingImport = referenceParent;
37624                             if (symbol.valueDeclaration)
37625                                 result.valueDeclaration = symbol.valueDeclaration;
37626                             if (symbol.constEnumOnlyModule)
37627                                 result.constEnumOnlyModule = true;
37628                             if (symbol.members)
37629                                 result.members = ts.cloneMap(symbol.members);
37630                             if (symbol.exports)
37631                                 result.exports = ts.cloneMap(symbol.exports);
37632                             var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
37633                             result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
37634                             return result;
37635                         }
37636                     }
37637                 }
37638             }
37639             return symbol;
37640         }
37641         function hasExportAssignmentSymbol(moduleSymbol) {
37642             return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
37643         }
37644         function getExportsOfModuleAsArray(moduleSymbol) {
37645             return symbolsToArray(getExportsOfModule(moduleSymbol));
37646         }
37647         function getExportsAndPropertiesOfModule(moduleSymbol) {
37648             var exports = getExportsOfModuleAsArray(moduleSymbol);
37649             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37650             if (exportEquals !== moduleSymbol) {
37651                 ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
37652             }
37653             return exports;
37654         }
37655         function tryGetMemberInModuleExports(memberName, moduleSymbol) {
37656             var symbolTable = getExportsOfModule(moduleSymbol);
37657             if (symbolTable) {
37658                 return symbolTable.get(memberName);
37659             }
37660         }
37661         function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
37662             var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
37663             if (symbol) {
37664                 return symbol;
37665             }
37666             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37667             if (exportEquals === moduleSymbol) {
37668                 return undefined;
37669             }
37670             var type = getTypeOfSymbol(exportEquals);
37671             return type.flags & 131068 /* Primitive */ ||
37672                 ts.getObjectFlags(type) & 1 /* Class */ ||
37673                 isArrayOrTupleLikeType(type)
37674                 ? undefined
37675                 : getPropertyOfType(type, memberName);
37676         }
37677         function getExportsOfSymbol(symbol) {
37678             return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
37679                 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
37680                     symbol.exports || emptySymbols;
37681         }
37682         function getExportsOfModule(moduleSymbol) {
37683             var links = getSymbolLinks(moduleSymbol);
37684             return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
37685         }
37686         /**
37687          * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
37688          * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
37689          */
37690         function extendExportSymbols(target, source, lookupTable, exportNode) {
37691             if (!source)
37692                 return;
37693             source.forEach(function (sourceSymbol, id) {
37694                 if (id === "default" /* Default */)
37695                     return;
37696                 var targetSymbol = target.get(id);
37697                 if (!targetSymbol) {
37698                     target.set(id, sourceSymbol);
37699                     if (lookupTable && exportNode) {
37700                         lookupTable.set(id, {
37701                             specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
37702                         });
37703                     }
37704                 }
37705                 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
37706                     var collisionTracker = lookupTable.get(id);
37707                     if (!collisionTracker.exportsWithDuplicate) {
37708                         collisionTracker.exportsWithDuplicate = [exportNode];
37709                     }
37710                     else {
37711                         collisionTracker.exportsWithDuplicate.push(exportNode);
37712                     }
37713                 }
37714             });
37715         }
37716         function getExportsOfModuleWorker(moduleSymbol) {
37717             var visitedSymbols = [];
37718             // A module defined by an 'export=' consists of one export that needs to be resolved
37719             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
37720             return visit(moduleSymbol) || emptySymbols;
37721             // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
37722             // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
37723             function visit(symbol) {
37724                 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
37725                     return;
37726                 }
37727                 var symbols = ts.cloneMap(symbol.exports);
37728                 // All export * declarations are collected in an __export symbol by the binder
37729                 var exportStars = symbol.exports.get("__export" /* ExportStar */);
37730                 if (exportStars) {
37731                     var nestedSymbols = ts.createSymbolTable();
37732                     var lookupTable_1 = ts.createMap();
37733                     for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
37734                         var node = _a[_i];
37735                         var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
37736                         var exportedSymbols = visit(resolvedModule);
37737                         extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
37738                     }
37739                     lookupTable_1.forEach(function (_a, id) {
37740                         var exportsWithDuplicate = _a.exportsWithDuplicate;
37741                         // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
37742                         if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
37743                             return;
37744                         }
37745                         for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
37746                             var node = exportsWithDuplicate_1[_i];
37747                             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)));
37748                         }
37749                     });
37750                     extendExportSymbols(symbols, nestedSymbols);
37751                 }
37752                 return symbols;
37753             }
37754         }
37755         function getMergedSymbol(symbol) {
37756             var merged;
37757             return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
37758         }
37759         function getSymbolOfNode(node) {
37760             return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
37761         }
37762         function getParentOfSymbol(symbol) {
37763             return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
37764         }
37765         function getAlternativeContainingModules(symbol, enclosingDeclaration) {
37766             var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
37767             var id = "" + getNodeId(containingFile);
37768             var links = getSymbolLinks(symbol);
37769             var results;
37770             if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
37771                 return results;
37772             }
37773             if (containingFile && containingFile.imports) {
37774                 // Try to make an import using an import already in the enclosing file, if possible
37775                 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
37776                     var importRef = _a[_i];
37777                     if (ts.nodeIsSynthesized(importRef))
37778                         continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
37779                     var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
37780                     if (!resolvedModule)
37781                         continue;
37782                     var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
37783                     if (!ref)
37784                         continue;
37785                     results = ts.append(results, resolvedModule);
37786                 }
37787                 if (ts.length(results)) {
37788                     (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
37789                     return results;
37790                 }
37791             }
37792             if (links.extendedContainers) {
37793                 return links.extendedContainers;
37794             }
37795             // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
37796             var otherFiles = host.getSourceFiles();
37797             for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
37798                 var file = otherFiles_1[_b];
37799                 if (!ts.isExternalModule(file))
37800                     continue;
37801                 var sym = getSymbolOfNode(file);
37802                 var ref = getAliasForSymbolInContainer(sym, symbol);
37803                 if (!ref)
37804                     continue;
37805                 results = ts.append(results, sym);
37806             }
37807             return links.extendedContainers = results || ts.emptyArray;
37808         }
37809         /**
37810          * Attempts to find the symbol corresponding to the container a symbol is in - usually this
37811          * is just its' `.parent`, but for locals, this value is `undefined`
37812          */
37813         function getContainersOfSymbol(symbol, enclosingDeclaration) {
37814             var container = getParentOfSymbol(symbol);
37815             // Type parameters end up in the `members` lists but are not externally visible
37816             if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
37817                 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
37818                 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
37819                 if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
37820                     return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
37821                 }
37822                 var res = ts.append(additionalContainers, container);
37823                 return ts.concatenate(res, reexportContainers);
37824             }
37825             var candidates = ts.mapDefined(symbol.declarations, function (d) {
37826                 if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
37827                     return getSymbolOfNode(d.parent);
37828                 }
37829                 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)) {
37830                     if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
37831                         return getSymbolOfNode(ts.getSourceFileOfNode(d));
37832                     }
37833                     checkExpressionCached(d.parent.left.expression);
37834                     return getNodeLinks(d.parent.left.expression).resolvedSymbol;
37835                 }
37836             });
37837             if (!ts.length(candidates)) {
37838                 return undefined;
37839             }
37840             return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
37841             function fileSymbolIfFileSymbolExportEqualsContainer(d) {
37842                 return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
37843             }
37844         }
37845         function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
37846             var fileSymbol = getExternalModuleContainer(d);
37847             var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
37848             return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
37849         }
37850         function getAliasForSymbolInContainer(container, symbol) {
37851             if (container === getParentOfSymbol(symbol)) {
37852                 // fast path, `symbol` is either already the alias or isn't aliased
37853                 return symbol;
37854             }
37855             // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
37856             // the container itself as the alias for the symbol
37857             var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
37858             if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
37859                 return container;
37860             }
37861             var exports = getExportsOfSymbol(container);
37862             var quick = exports.get(symbol.escapedName);
37863             if (quick && getSymbolIfSameReference(quick, symbol)) {
37864                 return quick;
37865             }
37866             return ts.forEachEntry(exports, function (exported) {
37867                 if (getSymbolIfSameReference(exported, symbol)) {
37868                     return exported;
37869                 }
37870             });
37871         }
37872         /**
37873          * Checks if two symbols, through aliasing and/or merging, refer to the same thing
37874          */
37875         function getSymbolIfSameReference(s1, s2) {
37876             if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
37877                 return s1;
37878             }
37879         }
37880         function getExportSymbolOfValueSymbolIfExported(symbol) {
37881             return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
37882         }
37883         function symbolIsValue(symbol) {
37884             return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
37885         }
37886         function findConstructorDeclaration(node) {
37887             var members = node.members;
37888             for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
37889                 var member = members_3[_i];
37890                 if (member.kind === 162 /* Constructor */ && ts.nodeIsPresent(member.body)) {
37891                     return member;
37892                 }
37893             }
37894         }
37895         function createType(flags) {
37896             var result = new Type(checker, flags);
37897             typeCount++;
37898             result.id = typeCount;
37899             return result;
37900         }
37901         function createIntrinsicType(kind, intrinsicName, objectFlags) {
37902             if (objectFlags === void 0) { objectFlags = 0; }
37903             var type = createType(kind);
37904             type.intrinsicName = intrinsicName;
37905             type.objectFlags = objectFlags;
37906             return type;
37907         }
37908         function createBooleanType(trueFalseTypes) {
37909             var type = getUnionType(trueFalseTypes);
37910             type.flags |= 16 /* Boolean */;
37911             type.intrinsicName = "boolean";
37912             return type;
37913         }
37914         function createObjectType(objectFlags, symbol) {
37915             var type = createType(524288 /* Object */);
37916             type.objectFlags = objectFlags;
37917             type.symbol = symbol;
37918             type.members = undefined;
37919             type.properties = undefined;
37920             type.callSignatures = undefined;
37921             type.constructSignatures = undefined;
37922             type.stringIndexInfo = undefined;
37923             type.numberIndexInfo = undefined;
37924             return type;
37925         }
37926         function createTypeofType() {
37927             return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
37928         }
37929         function createTypeParameter(symbol) {
37930             var type = createType(262144 /* TypeParameter */);
37931             if (symbol)
37932                 type.symbol = symbol;
37933             return type;
37934         }
37935         // A reserved member name starts with two underscores, but the third character cannot be an underscore,
37936         // @, or #. A third underscore indicates an escaped form of an identifier that started
37937         // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
37938         // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
37939         function isReservedMemberName(name) {
37940             return name.charCodeAt(0) === 95 /* _ */ &&
37941                 name.charCodeAt(1) === 95 /* _ */ &&
37942                 name.charCodeAt(2) !== 95 /* _ */ &&
37943                 name.charCodeAt(2) !== 64 /* at */ &&
37944                 name.charCodeAt(2) !== 35 /* hash */;
37945         }
37946         function getNamedMembers(members) {
37947             var result;
37948             members.forEach(function (symbol, id) {
37949                 if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
37950                     (result || (result = [])).push(symbol);
37951                 }
37952             });
37953             return result || ts.emptyArray;
37954         }
37955         function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
37956             type.members = members;
37957             type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
37958             type.callSignatures = callSignatures;
37959             type.constructSignatures = constructSignatures;
37960             type.stringIndexInfo = stringIndexInfo;
37961             type.numberIndexInfo = numberIndexInfo;
37962             return type;
37963         }
37964         function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
37965             return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
37966         }
37967         function forEachSymbolTableInScope(enclosingDeclaration, callback) {
37968             var result;
37969             var _loop_7 = function (location) {
37970                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
37971                 if (location.locals && !isGlobalSourceFile(location)) {
37972                     if (result = callback(location.locals)) {
37973                         return { value: result };
37974                     }
37975                 }
37976                 switch (location.kind) {
37977                     case 290 /* SourceFile */:
37978                         if (!ts.isExternalOrCommonJsModule(location)) {
37979                             break;
37980                         }
37981                     // falls through
37982                     case 249 /* ModuleDeclaration */:
37983                         var sym = getSymbolOfNode(location);
37984                         // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
37985                         // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
37986                         // to one another anyway)
37987                         if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) {
37988                             return { value: result };
37989                         }
37990                         break;
37991                     case 245 /* ClassDeclaration */:
37992                     case 214 /* ClassExpression */:
37993                     case 246 /* InterfaceDeclaration */:
37994                         // Type parameters are bound into `members` lists so they can merge across declarations
37995                         // This is troublesome, since in all other respects, they behave like locals :cries:
37996                         // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
37997                         // lookup logic in terms of `resolveName` would be nice
37998                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
37999                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
38000                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
38001                         var table_1;
38002                         // TODO: Should this filtered table be cached in some way?
38003                         (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
38004                             if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
38005                                 (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
38006                             }
38007                         });
38008                         if (table_1 && (result = callback(table_1))) {
38009                             return { value: result };
38010                         }
38011                         break;
38012                 }
38013             };
38014             for (var location = enclosingDeclaration; location; location = location.parent) {
38015                 var state_2 = _loop_7(location);
38016                 if (typeof state_2 === "object")
38017                     return state_2.value;
38018             }
38019             return callback(globals);
38020         }
38021         function getQualifiedLeftMeaning(rightMeaning) {
38022             // If we are looking in value space, the parent meaning is value, other wise it is namespace
38023             return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
38024         }
38025         function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
38026             if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
38027             if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
38028                 return undefined;
38029             }
38030             var id = "" + getSymbolId(symbol);
38031             var visitedSymbolTables = visitedSymbolTablesMap.get(id);
38032             if (!visitedSymbolTables) {
38033                 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
38034             }
38035             return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
38036             /**
38037              * @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)
38038              */
38039             function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
38040                 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
38041                     return undefined;
38042                 }
38043                 var result = trySymbolTable(symbols, ignoreQualification);
38044                 visitedSymbolTables.pop();
38045                 return result;
38046             }
38047             function canQualifySymbol(symbolFromSymbolTable, meaning) {
38048                 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
38049                 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
38050                     // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
38051                     !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
38052             }
38053             function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
38054                 return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
38055                     // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
38056                     // and if symbolFromSymbolTable or alias resolution matches the symbol,
38057                     // check the symbol can be qualified, it is only then this symbol is accessible
38058                     !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
38059                     (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
38060             }
38061             function trySymbolTable(symbols, ignoreQualification) {
38062                 // If symbol is directly available by its name in the symbol table
38063                 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
38064                     return [symbol];
38065                 }
38066                 // Check if symbol is any of the aliases in scope
38067                 var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
38068                     if (symbolFromSymbolTable.flags & 2097152 /* Alias */
38069                         && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
38070                         && symbolFromSymbolTable.escapedName !== "default" /* Default */
38071                         && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
38072                         // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
38073                         && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
38074                         // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
38075                         // See similar comment in `resolveName` for details
38076                         && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */))) {
38077                         var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
38078                         var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
38079                         if (candidate) {
38080                             return candidate;
38081                         }
38082                     }
38083                     if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
38084                         if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
38085                             return [symbol];
38086                         }
38087                     }
38088                 });
38089                 // 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
38090                 return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
38091             }
38092             function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
38093                 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
38094                     return [symbolFromSymbolTable];
38095                 }
38096                 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
38097                 // but only if the symbolFromSymbolTable can be qualified
38098                 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
38099                 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
38100                 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
38101                     return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
38102                 }
38103             }
38104         }
38105         function needsQualification(symbol, enclosingDeclaration, meaning) {
38106             var qualify = false;
38107             forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
38108                 // If symbol of this name is not available in the symbol table we are ok
38109                 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
38110                 if (!symbolFromSymbolTable) {
38111                     // Continue to the next symbol table
38112                     return false;
38113                 }
38114                 // If the symbol with this name is present it should refer to the symbol
38115                 if (symbolFromSymbolTable === symbol) {
38116                     // No need to qualify
38117                     return true;
38118                 }
38119                 // Qualify if the symbol from symbol table has same meaning as expected
38120                 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
38121                 if (symbolFromSymbolTable.flags & meaning) {
38122                     qualify = true;
38123                     return true;
38124                 }
38125                 // Continue to the next symbol table
38126                 return false;
38127             });
38128             return qualify;
38129         }
38130         function isPropertyOrMethodDeclarationSymbol(symbol) {
38131             if (symbol.declarations && symbol.declarations.length) {
38132                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
38133                     var declaration = _a[_i];
38134                     switch (declaration.kind) {
38135                         case 159 /* PropertyDeclaration */:
38136                         case 161 /* MethodDeclaration */:
38137                         case 163 /* GetAccessor */:
38138                         case 164 /* SetAccessor */:
38139                             continue;
38140                         default:
38141                             return false;
38142                     }
38143                 }
38144                 return true;
38145             }
38146             return false;
38147         }
38148         function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
38149             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false);
38150             return access.accessibility === 0 /* Accessible */;
38151         }
38152         function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
38153             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false);
38154             return access.accessibility === 0 /* Accessible */;
38155         }
38156         function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) {
38157             if (!ts.length(symbols))
38158                 return;
38159             var hadAccessibleChain;
38160             var earlyModuleBail = false;
38161             for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
38162                 var symbol = _a[_i];
38163                 // Symbol is accessible if it by itself is accessible
38164                 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
38165                 if (accessibleSymbolChain) {
38166                     hadAccessibleChain = symbol;
38167                     var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
38168                     if (hasAccessibleDeclarations) {
38169                         return hasAccessibleDeclarations;
38170                     }
38171                 }
38172                 else {
38173                     if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
38174                         if (shouldComputeAliasesToMakeVisible) {
38175                             earlyModuleBail = true;
38176                             // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
38177                             // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
38178                             // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
38179                             // all other visibility options (in order to capture the possible aliases used to reference the module)
38180                             continue;
38181                         }
38182                         // Any meaning of a module symbol is always accessible via an `import` type
38183                         return {
38184                             accessibility: 0 /* Accessible */
38185                         };
38186                     }
38187                 }
38188                 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
38189                 // It could be a qualified symbol and hence verify the path
38190                 // e.g.:
38191                 // module m {
38192                 //     export class c {
38193                 //     }
38194                 // }
38195                 // const x: typeof m.c
38196                 // In the above example when we start with checking if typeof m.c symbol is accessible,
38197                 // we are going to see if c can be accessed in scope directly.
38198                 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
38199                 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
38200                 var containers = getContainersOfSymbol(symbol, enclosingDeclaration);
38201                 // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
38202                 // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
38203                 // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
38204                 var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations);
38205                 if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) {
38206                     if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) {
38207                         containers = [getSymbolOfNode(firstDecl.parent)];
38208                     }
38209                 }
38210                 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible);
38211                 if (parentResult) {
38212                     return parentResult;
38213                 }
38214             }
38215             if (earlyModuleBail) {
38216                 return {
38217                     accessibility: 0 /* Accessible */
38218                 };
38219             }
38220             if (hadAccessibleChain) {
38221                 return {
38222                     accessibility: 1 /* NotAccessible */,
38223                     errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
38224                     errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
38225                 };
38226             }
38227         }
38228         /**
38229          * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
38230          *
38231          * @param symbol a Symbol to check if accessible
38232          * @param enclosingDeclaration a Node containing reference to the symbol
38233          * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
38234          * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
38235          */
38236         function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
38237             if (symbol && enclosingDeclaration) {
38238                 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible);
38239                 if (result) {
38240                     return result;
38241                 }
38242                 // This could be a symbol that is not exported in the external module
38243                 // or it could be a symbol from different external module that is not aliased and hence cannot be named
38244                 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
38245                 if (symbolExternalModule) {
38246                     var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
38247                     if (symbolExternalModule !== enclosingExternalModule) {
38248                         // name from different external module that is not visible
38249                         return {
38250                             accessibility: 2 /* CannotBeNamed */,
38251                             errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38252                             errorModuleName: symbolToString(symbolExternalModule)
38253                         };
38254                     }
38255                 }
38256                 // Just a local name that is not accessible
38257                 return {
38258                     accessibility: 1 /* NotAccessible */,
38259                     errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38260                 };
38261             }
38262             return { accessibility: 0 /* Accessible */ };
38263         }
38264         function getExternalModuleContainer(declaration) {
38265             var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
38266             return node && getSymbolOfNode(node);
38267         }
38268         function hasExternalModuleSymbol(declaration) {
38269             return ts.isAmbientModule(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38270         }
38271         function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
38272             return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38273         }
38274         function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
38275             var aliasesToMakeVisible;
38276             if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 75 /* Identifier */; }), getIsDeclarationVisible)) {
38277                 return undefined;
38278             }
38279             return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
38280             function getIsDeclarationVisible(declaration) {
38281                 if (!isDeclarationVisible(declaration)) {
38282                     // Mark the unexported alias as visible if its parent is visible
38283                     // because these kind of aliases can be used to name types in declaration file
38284                     var anyImportSyntax = getAnyImportSyntax(declaration);
38285                     if (anyImportSyntax &&
38286                         !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
38287                         isDeclarationVisible(anyImportSyntax.parent)) {
38288                         return addVisibleAlias(declaration, anyImportSyntax);
38289                     }
38290                     else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
38291                         !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
38292                         isDeclarationVisible(declaration.parent.parent.parent)) {
38293                         return addVisibleAlias(declaration, declaration.parent.parent);
38294                     }
38295                     else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
38296                         && !ts.hasModifier(declaration, 1 /* Export */)
38297                         && isDeclarationVisible(declaration.parent)) {
38298                         return addVisibleAlias(declaration, declaration);
38299                     }
38300                     // Declaration is not visible
38301                     return false;
38302                 }
38303                 return true;
38304             }
38305             function addVisibleAlias(declaration, aliasingStatement) {
38306                 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
38307                 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
38308                 // since we will do the emitting later in trackSymbol.
38309                 if (shouldComputeAliasToMakeVisible) {
38310                     getNodeLinks(declaration).isVisible = true;
38311                     aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
38312                 }
38313                 return true;
38314             }
38315         }
38316         function isEntityNameVisible(entityName, enclosingDeclaration) {
38317             // get symbol of the first identifier of the entityName
38318             var meaning;
38319             if (entityName.parent.kind === 172 /* TypeQuery */ ||
38320                 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
38321                 entityName.parent.kind === 154 /* ComputedPropertyName */) {
38322                 // Typeof value
38323                 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
38324             }
38325             else if (entityName.kind === 153 /* QualifiedName */ || entityName.kind === 194 /* PropertyAccessExpression */ ||
38326                 entityName.parent.kind === 253 /* ImportEqualsDeclaration */) {
38327                 // Left identifier from type reference or TypeAlias
38328                 // Entity name of the import declaration
38329                 meaning = 1920 /* Namespace */;
38330             }
38331             else {
38332                 // Type Reference or TypeAlias entity = Identifier
38333                 meaning = 788968 /* Type */;
38334             }
38335             var firstIdentifier = ts.getFirstIdentifier(entityName);
38336             var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
38337             // Verify if the symbol is accessible
38338             return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
38339                 accessibility: 1 /* NotAccessible */,
38340                 errorSymbolName: ts.getTextOfNode(firstIdentifier),
38341                 errorNode: firstIdentifier
38342             };
38343         }
38344         function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
38345             if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
38346             var nodeFlags = 70221824 /* IgnoreErrors */;
38347             if (flags & 2 /* UseOnlyExternalAliasing */) {
38348                 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
38349             }
38350             if (flags & 1 /* WriteTypeParametersOrArguments */) {
38351                 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
38352             }
38353             if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
38354                 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
38355             }
38356             if (flags & 16 /* DoNotIncludeSymbolChain */) {
38357                 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
38358             }
38359             var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
38360             return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
38361             function symbolToStringWorker(writer) {
38362                 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
38363                 var printer = ts.createPrinter({ removeComments: true });
38364                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38365                 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
38366                 return writer;
38367             }
38368         }
38369         function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
38370             if (flags === void 0) { flags = 0 /* None */; }
38371             return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
38372             function signatureToStringWorker(writer) {
38373                 var sigOutput;
38374                 if (flags & 262144 /* WriteArrowStyleSignature */) {
38375                     sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructorType */ : 170 /* FunctionType */;
38376                 }
38377                 else {
38378                     sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructSignature */ : 165 /* CallSignature */;
38379                 }
38380                 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
38381                 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
38382                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38383                 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
38384                 return writer;
38385             }
38386         }
38387         function typeToString(type, enclosingDeclaration, flags, writer) {
38388             if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
38389             if (writer === void 0) { writer = ts.createTextWriter(""); }
38390             var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
38391             var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
38392             if (typeNode === undefined)
38393                 return ts.Debug.fail("should always get typenode");
38394             var options = { removeComments: true };
38395             var printer = ts.createPrinter(options);
38396             var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38397             printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
38398             var result = writer.getText();
38399             var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2;
38400             if (maxLength && result && result.length >= maxLength) {
38401                 return result.substr(0, maxLength - "...".length) + "...";
38402             }
38403             return result;
38404         }
38405         function getTypeNamesForErrorDisplay(left, right) {
38406             var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
38407             var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
38408             if (leftStr === rightStr) {
38409                 leftStr = typeToString(left, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38410                 rightStr = typeToString(right, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38411             }
38412             return [leftStr, rightStr];
38413         }
38414         function symbolValueDeclarationIsContextSensitive(symbol) {
38415             return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
38416         }
38417         function toNodeBuilderFlags(flags) {
38418             if (flags === void 0) { flags = 0 /* None */; }
38419             return flags & 814775659 /* NodeBuilderFlagsMask */;
38420         }
38421         function createNodeBuilder() {
38422             return {
38423                 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
38424                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
38425                 },
38426                 indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
38427                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); });
38428                 },
38429                 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
38430                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
38431                 },
38432                 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38433                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
38434                 },
38435                 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38436                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
38437                 },
38438                 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
38439                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
38440                 },
38441                 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
38442                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
38443                 },
38444                 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
38445                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
38446                 },
38447                 symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
38448                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
38449                 },
38450             };
38451             function withContext(enclosingDeclaration, flags, tracker, cb) {
38452                 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
38453                 var context = {
38454                     enclosingDeclaration: enclosingDeclaration,
38455                     flags: flags || 0 /* None */,
38456                     // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
38457                     tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
38458                             getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
38459                             getSourceFiles: function () { return host.getSourceFiles(); },
38460                             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
38461                             getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks),
38462                             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
38463                             redirectTargetsMap: host.redirectTargetsMap,
38464                             getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
38465                             isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
38466                             fileExists: function (fileName) { return host.fileExists(fileName); },
38467                         } : undefined },
38468                     encounteredError: false,
38469                     visitedTypes: undefined,
38470                     symbolDepth: undefined,
38471                     inferTypeParameters: undefined,
38472                     approximateLength: 0
38473                 };
38474                 var resultingNode = cb(context);
38475                 return context.encounteredError ? undefined : resultingNode;
38476             }
38477             function checkTruncationLength(context) {
38478                 if (context.truncating)
38479                     return context.truncating;
38480                 return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength);
38481             }
38482             function typeToTypeNodeHelper(type, context) {
38483                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
38484                     cancellationToken.throwIfCancellationRequested();
38485                 }
38486                 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
38487                 context.flags &= ~8388608 /* InTypeAlias */;
38488                 if (!type) {
38489                     if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38490                         context.encounteredError = true;
38491                         return undefined; // TODO: GH#18217
38492                     }
38493                     context.approximateLength += 3;
38494                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38495                 }
38496                 if (!(context.flags & 536870912 /* NoTypeReduction */)) {
38497                     type = getReducedType(type);
38498                 }
38499                 if (type.flags & 1 /* Any */) {
38500                     context.approximateLength += 3;
38501                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38502                 }
38503                 if (type.flags & 2 /* Unknown */) {
38504                     return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
38505                 }
38506                 if (type.flags & 4 /* String */) {
38507                     context.approximateLength += 6;
38508                     return ts.createKeywordTypeNode(143 /* StringKeyword */);
38509                 }
38510                 if (type.flags & 8 /* Number */) {
38511                     context.approximateLength += 6;
38512                     return ts.createKeywordTypeNode(140 /* NumberKeyword */);
38513                 }
38514                 if (type.flags & 64 /* BigInt */) {
38515                     context.approximateLength += 6;
38516                     return ts.createKeywordTypeNode(151 /* BigIntKeyword */);
38517                 }
38518                 if (type.flags & 16 /* Boolean */) {
38519                     context.approximateLength += 7;
38520                     return ts.createKeywordTypeNode(128 /* BooleanKeyword */);
38521                 }
38522                 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
38523                     var parentSymbol = getParentOfSymbol(type.symbol);
38524                     var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
38525                     var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type
38526                         ? parentName
38527                         : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined));
38528                     return enumLiteralName;
38529                 }
38530                 if (type.flags & 1056 /* EnumLike */) {
38531                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
38532                 }
38533                 if (type.flags & 128 /* StringLiteral */) {
38534                     context.approximateLength += (type.value.length + 2);
38535                     return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
38536                 }
38537                 if (type.flags & 256 /* NumberLiteral */) {
38538                     var value = type.value;
38539                     context.approximateLength += ("" + value).length;
38540                     return ts.createLiteralTypeNode(value < 0 ? ts.createPrefix(40 /* MinusToken */, ts.createLiteral(-value)) : ts.createLiteral(value));
38541                 }
38542                 if (type.flags & 2048 /* BigIntLiteral */) {
38543                     context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
38544                     return ts.createLiteralTypeNode((ts.createLiteral(type.value)));
38545                 }
38546                 if (type.flags & 512 /* BooleanLiteral */) {
38547                     context.approximateLength += type.intrinsicName.length;
38548                     return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse();
38549                 }
38550                 if (type.flags & 8192 /* UniqueESSymbol */) {
38551                     if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
38552                         if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38553                             context.approximateLength += 6;
38554                             return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
38555                         }
38556                         if (context.tracker.reportInaccessibleUniqueSymbolError) {
38557                             context.tracker.reportInaccessibleUniqueSymbolError();
38558                         }
38559                     }
38560                     context.approximateLength += 13;
38561                     return ts.createTypeOperatorNode(147 /* UniqueKeyword */, ts.createKeywordTypeNode(144 /* SymbolKeyword */));
38562                 }
38563                 if (type.flags & 16384 /* Void */) {
38564                     context.approximateLength += 4;
38565                     return ts.createKeywordTypeNode(110 /* VoidKeyword */);
38566                 }
38567                 if (type.flags & 32768 /* Undefined */) {
38568                     context.approximateLength += 9;
38569                     return ts.createKeywordTypeNode(146 /* UndefinedKeyword */);
38570                 }
38571                 if (type.flags & 65536 /* Null */) {
38572                     context.approximateLength += 4;
38573                     return ts.createKeywordTypeNode(100 /* NullKeyword */);
38574                 }
38575                 if (type.flags & 131072 /* Never */) {
38576                     context.approximateLength += 5;
38577                     return ts.createKeywordTypeNode(137 /* NeverKeyword */);
38578                 }
38579                 if (type.flags & 4096 /* ESSymbol */) {
38580                     context.approximateLength += 6;
38581                     return ts.createKeywordTypeNode(144 /* SymbolKeyword */);
38582                 }
38583                 if (type.flags & 67108864 /* NonPrimitive */) {
38584                     context.approximateLength += 6;
38585                     return ts.createKeywordTypeNode(141 /* ObjectKeyword */);
38586                 }
38587                 if (isThisTypeParameter(type)) {
38588                     if (context.flags & 4194304 /* InObjectTypeLiteral */) {
38589                         if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
38590                             context.encounteredError = true;
38591                         }
38592                         if (context.tracker.reportInaccessibleThisError) {
38593                             context.tracker.reportInaccessibleThisError();
38594                         }
38595                     }
38596                     context.approximateLength += 4;
38597                     return ts.createThis();
38598                 }
38599                 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
38600                     var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
38601                     if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
38602                         return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
38603                     return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
38604                 }
38605                 var objectFlags = ts.getObjectFlags(type);
38606                 if (objectFlags & 4 /* Reference */) {
38607                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38608                     return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
38609                 }
38610                 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
38611                     if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
38612                         context.approximateLength += (ts.symbolName(type.symbol).length + 6);
38613                         return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
38614                     }
38615                     if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
38616                         type.flags & 262144 /* TypeParameter */ &&
38617                         !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38618                         var name = typeParameterToName(type, context);
38619                         context.approximateLength += ts.idText(name).length;
38620                         return ts.createTypeReferenceNode(ts.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
38621                     }
38622                     // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
38623                     return type.symbol
38624                         ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
38625                         : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined);
38626                 }
38627                 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
38628                     var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
38629                     if (ts.length(types) === 1) {
38630                         return typeToTypeNodeHelper(types[0], context);
38631                     }
38632                     var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
38633                     if (typeNodes && typeNodes.length > 0) {
38634                         var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 178 /* UnionType */ : 179 /* IntersectionType */, typeNodes);
38635                         return unionOrIntersectionTypeNode;
38636                     }
38637                     else {
38638                         if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38639                             context.encounteredError = true;
38640                         }
38641                         return undefined; // TODO: GH#18217
38642                     }
38643                 }
38644                 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
38645                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38646                     // The type is an object literal type.
38647                     return createAnonymousTypeNode(type);
38648                 }
38649                 if (type.flags & 4194304 /* Index */) {
38650                     var indexedType = type.type;
38651                     context.approximateLength += 6;
38652                     var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
38653                     return ts.createTypeOperatorNode(indexTypeNode);
38654                 }
38655                 if (type.flags & 8388608 /* IndexedAccess */) {
38656                     var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
38657                     var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
38658                     context.approximateLength += 2;
38659                     return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
38660                 }
38661                 if (type.flags & 16777216 /* Conditional */) {
38662                     var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
38663                     var saveInferTypeParameters = context.inferTypeParameters;
38664                     context.inferTypeParameters = type.root.inferTypeParameters;
38665                     var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
38666                     context.inferTypeParameters = saveInferTypeParameters;
38667                     var trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type));
38668                     var falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type));
38669                     context.approximateLength += 15;
38670                     return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
38671                 }
38672                 if (type.flags & 33554432 /* Substitution */) {
38673                     return typeToTypeNodeHelper(type.baseType, context);
38674                 }
38675                 return ts.Debug.fail("Should be unreachable.");
38676                 function typeToTypeNodeOrCircularityElision(type) {
38677                     var _a, _b;
38678                     if (type.flags & 1048576 /* Union */) {
38679                         if (context.visitedTypes && context.visitedTypes.has("" + getTypeId(type))) {
38680                             if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
38681                                 context.encounteredError = true;
38682                                 (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportCyclicStructureError) === null || _b === void 0 ? void 0 : _b.call(_a);
38683                             }
38684                             return createElidedInformationPlaceholder(context);
38685                         }
38686                         return visitAndTransformType(type, function (type) { return typeToTypeNodeHelper(type, context); });
38687                     }
38688                     return typeToTypeNodeHelper(type, context);
38689                 }
38690                 function createMappedTypeNodeFromType(type) {
38691                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38692                     var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
38693                     var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
38694                     var appropriateConstraintTypeNode;
38695                     if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
38696                         // We have a { [P in keyof T]: X }
38697                         // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
38698                         appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
38699                     }
38700                     else {
38701                         appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
38702                     }
38703                     var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
38704                     var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
38705                     var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
38706                     context.approximateLength += 10;
38707                     return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
38708                 }
38709                 function createAnonymousTypeNode(type) {
38710                     var typeId = "" + type.id;
38711                     var symbol = type.symbol;
38712                     if (symbol) {
38713                         if (isJSConstructor(symbol.valueDeclaration)) {
38714                             // Instance and static types share the same symbol; only add 'typeof' for the static side.
38715                             var isInstanceType = type === getDeclaredTypeOfClassOrInterface(symbol) ? 788968 /* Type */ : 111551 /* Value */;
38716                             return symbolToTypeNode(symbol, context, isInstanceType);
38717                         }
38718                         // Always use 'typeof T' for type of class, enum, and module objects
38719                         else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 214 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
38720                             symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
38721                             shouldWriteTypeOfFunctionSymbol()) {
38722                             return symbolToTypeNode(symbol, context, 111551 /* Value */);
38723                         }
38724                         else if (context.visitedTypes && context.visitedTypes.has(typeId)) {
38725                             // If type is an anonymous type literal in a type alias declaration, use type alias name
38726                             var typeAlias = getTypeAliasForTypeLiteral(type);
38727                             if (typeAlias) {
38728                                 // The specified symbol flags need to be reinterpreted as type flags
38729                                 return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
38730                             }
38731                             else {
38732                                 return createElidedInformationPlaceholder(context);
38733                             }
38734                         }
38735                         else {
38736                             return visitAndTransformType(type, createTypeNodeFromObjectType);
38737                         }
38738                     }
38739                     else {
38740                         // Anonymous types without a symbol are never circular.
38741                         return createTypeNodeFromObjectType(type);
38742                     }
38743                     function shouldWriteTypeOfFunctionSymbol() {
38744                         var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
38745                             ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); });
38746                         var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
38747                             (symbol.parent || // is exported function symbol
38748                                 ts.forEach(symbol.declarations, function (declaration) {
38749                                     return declaration.parent.kind === 290 /* SourceFile */ || declaration.parent.kind === 250 /* ModuleBlock */;
38750                                 }));
38751                         if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
38752                             // typeof is allowed only for static/non local functions
38753                             return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively
38754                                 (!(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
38755                         }
38756                     }
38757                 }
38758                 function visitAndTransformType(type, transform) {
38759                     var typeId = "" + type.id;
38760                     var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
38761                     var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
38762                         type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
38763                             undefined;
38764                     // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
38765                     // of types allows us to catch circular references to instantiations of the same anonymous type
38766                     if (!context.visitedTypes) {
38767                         context.visitedTypes = ts.createMap();
38768                     }
38769                     if (id && !context.symbolDepth) {
38770                         context.symbolDepth = ts.createMap();
38771                     }
38772                     var depth;
38773                     if (id) {
38774                         depth = context.symbolDepth.get(id) || 0;
38775                         if (depth > 10) {
38776                             return createElidedInformationPlaceholder(context);
38777                         }
38778                         context.symbolDepth.set(id, depth + 1);
38779                     }
38780                     context.visitedTypes.set(typeId, true);
38781                     var result = transform(type);
38782                     context.visitedTypes.delete(typeId);
38783                     if (id) {
38784                         context.symbolDepth.set(id, depth);
38785                     }
38786                     return result;
38787                 }
38788                 function createTypeNodeFromObjectType(type) {
38789                     if (isGenericMappedType(type)) {
38790                         return createMappedTypeNodeFromType(type);
38791                     }
38792                     var resolved = resolveStructuredTypeMembers(type);
38793                     if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
38794                         if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
38795                             context.approximateLength += 2;
38796                             return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
38797                         }
38798                         if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
38799                             var signature = resolved.callSignatures[0];
38800                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 170 /* FunctionType */, context);
38801                             return signatureNode;
38802                         }
38803                         if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
38804                             var signature = resolved.constructSignatures[0];
38805                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 171 /* ConstructorType */, context);
38806                             return signatureNode;
38807                         }
38808                     }
38809                     var savedFlags = context.flags;
38810                     context.flags |= 4194304 /* InObjectTypeLiteral */;
38811                     var members = createTypeNodesFromResolvedType(resolved);
38812                     context.flags = savedFlags;
38813                     var typeLiteralNode = ts.createTypeLiteralNode(members);
38814                     context.approximateLength += 2;
38815                     return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
38816                 }
38817                 function typeReferenceToTypeNode(type) {
38818                     var typeArguments = getTypeArguments(type);
38819                     if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
38820                         if (context.flags & 2 /* WriteArrayAsGenericType */) {
38821                             var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
38822                             return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
38823                         }
38824                         var elementType = typeToTypeNodeHelper(typeArguments[0], context);
38825                         var arrayType = ts.createArrayTypeNode(elementType);
38826                         return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, arrayType);
38827                     }
38828                     else if (type.target.objectFlags & 8 /* Tuple */) {
38829                         if (typeArguments.length > 0) {
38830                             var arity = getTypeReferenceArity(type);
38831                             var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
38832                             var hasRestElement = type.target.hasRestElement;
38833                             if (tupleConstituentNodes) {
38834                                 for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) {
38835                                     tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ?
38836                                         ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
38837                                         ts.createOptionalTypeNode(tupleConstituentNodes[i]);
38838                                 }
38839                                 var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
38840                                 return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
38841                             }
38842                         }
38843                         if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
38844                             var tupleTypeNode = ts.createTupleTypeNode([]);
38845                             return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
38846                         }
38847                         context.encounteredError = true;
38848                         return undefined; // TODO: GH#18217
38849                     }
38850                     else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
38851                         type.symbol.valueDeclaration &&
38852                         ts.isClassLike(type.symbol.valueDeclaration) &&
38853                         !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38854                         return createAnonymousTypeNode(type);
38855                     }
38856                     else {
38857                         var outerTypeParameters = type.target.outerTypeParameters;
38858                         var i = 0;
38859                         var resultType = void 0;
38860                         if (outerTypeParameters) {
38861                             var length_2 = outerTypeParameters.length;
38862                             while (i < length_2) {
38863                                 // Find group of type arguments for type parameters with the same declaring container.
38864                                 var start = i;
38865                                 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
38866                                 do {
38867                                     i++;
38868                                 } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
38869                                 // When type parameters are their own type arguments for the whole group (i.e. we have
38870                                 // the default outer type arguments), we don't show the group.
38871                                 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
38872                                     var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
38873                                     var flags_2 = context.flags;
38874                                     context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
38875                                     var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
38876                                     context.flags = flags_2;
38877                                     resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
38878                                 }
38879                             }
38880                         }
38881                         var typeArgumentNodes = void 0;
38882                         if (typeArguments.length > 0) {
38883                             var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
38884                             typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
38885                         }
38886                         var flags = context.flags;
38887                         context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
38888                         var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
38889                         context.flags = flags;
38890                         return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
38891                     }
38892                 }
38893                 function appendReferenceToType(root, ref) {
38894                     if (ts.isImportTypeNode(root)) {
38895                         // first shift type arguments
38896                         var innerParams = root.typeArguments;
38897                         if (root.qualifier) {
38898                             (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams;
38899                         }
38900                         root.typeArguments = ref.typeArguments;
38901                         // then move qualifiers
38902                         var ids = getAccessStack(ref);
38903                         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
38904                             var id = ids_1[_i];
38905                             root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id;
38906                         }
38907                         return root;
38908                     }
38909                     else {
38910                         // first shift type arguments
38911                         var innerParams = root.typeArguments;
38912                         (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams;
38913                         root.typeArguments = ref.typeArguments;
38914                         // then move qualifiers
38915                         var ids = getAccessStack(ref);
38916                         for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
38917                             var id = ids_2[_a];
38918                             root.typeName = ts.createQualifiedName(root.typeName, id);
38919                         }
38920                         return root;
38921                     }
38922                 }
38923                 function getAccessStack(ref) {
38924                     var state = ref.typeName;
38925                     var ids = [];
38926                     while (!ts.isIdentifier(state)) {
38927                         ids.unshift(state.right);
38928                         state = state.left;
38929                     }
38930                     ids.unshift(state);
38931                     return ids;
38932                 }
38933                 function createTypeNodesFromResolvedType(resolvedType) {
38934                     if (checkTruncationLength(context)) {
38935                         return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)];
38936                     }
38937                     var typeElements = [];
38938                     for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
38939                         var signature = _a[_i];
38940                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 165 /* CallSignature */, context));
38941                     }
38942                     for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
38943                         var signature = _c[_b];
38944                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 166 /* ConstructSignature */, context));
38945                     }
38946                     if (resolvedType.stringIndexInfo) {
38947                         var indexSignature = void 0;
38948                         if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
38949                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
38950                             indexSignature.type = createElidedInformationPlaceholder(context);
38951                         }
38952                         else {
38953                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
38954                         }
38955                         typeElements.push(indexSignature);
38956                     }
38957                     if (resolvedType.numberIndexInfo) {
38958                         typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
38959                     }
38960                     var properties = resolvedType.properties;
38961                     if (!properties) {
38962                         return typeElements;
38963                     }
38964                     var i = 0;
38965                     for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
38966                         var propertySymbol = properties_1[_d];
38967                         i++;
38968                         if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
38969                             if (propertySymbol.flags & 4194304 /* Prototype */) {
38970                                 continue;
38971                             }
38972                             if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
38973                                 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
38974                             }
38975                         }
38976                         if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
38977                             typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
38978                             addPropertyToElementList(properties[properties.length - 1], context, typeElements);
38979                             break;
38980                         }
38981                         addPropertyToElementList(propertySymbol, context, typeElements);
38982                     }
38983                     return typeElements.length ? typeElements : undefined;
38984                 }
38985             }
38986             function createElidedInformationPlaceholder(context) {
38987                 context.approximateLength += 3;
38988                 if (!(context.flags & 1 /* NoTruncation */)) {
38989                     return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
38990                 }
38991                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38992             }
38993             function addPropertyToElementList(propertySymbol, context, typeElements) {
38994                 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
38995                 var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
38996                     anyType : getTypeOfSymbol(propertySymbol);
38997                 var saveEnclosingDeclaration = context.enclosingDeclaration;
38998                 context.enclosingDeclaration = undefined;
38999                 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */) {
39000                     var decl = ts.first(propertySymbol.declarations);
39001                     if (hasLateBindableName(decl)) {
39002                         if (ts.isBinaryExpression(decl)) {
39003                             var name = ts.getNameOfDeclaration(decl);
39004                             if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
39005                                 trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
39006                             }
39007                         }
39008                         else {
39009                             trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
39010                         }
39011                     }
39012                 }
39013                 context.enclosingDeclaration = saveEnclosingDeclaration;
39014                 var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
39015                 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
39016                 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined;
39017                 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
39018                     var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
39019                     for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
39020                         var signature = signatures_1[_i];
39021                         var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 160 /* MethodSignature */, context);
39022                         methodDeclaration.name = propertyName;
39023                         methodDeclaration.questionToken = optionalToken;
39024                         typeElements.push(preserveCommentsOn(methodDeclaration));
39025                     }
39026                 }
39027                 else {
39028                     var savedFlags = context.flags;
39029                     context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
39030                     var propertyTypeNode = void 0;
39031                     if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
39032                         propertyTypeNode = createElidedInformationPlaceholder(context);
39033                     }
39034                     else {
39035                         propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
39036                     }
39037                     context.flags = savedFlags;
39038                     var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined;
39039                     if (modifiers) {
39040                         context.approximateLength += 9;
39041                     }
39042                     var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, 
39043                     /*initializer*/ undefined);
39044                     typeElements.push(preserveCommentsOn(propertySignature));
39045                 }
39046                 function preserveCommentsOn(node) {
39047                     if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; })) {
39048                         var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; });
39049                         var commentText = d.comment;
39050                         if (commentText) {
39051                             ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
39052                         }
39053                     }
39054                     else if (propertySymbol.valueDeclaration) {
39055                         // Copy comments to node for declaration emit
39056                         ts.setCommentRange(node, propertySymbol.valueDeclaration);
39057                     }
39058                     return node;
39059                 }
39060             }
39061             function mapToTypeNodes(types, context, isBareList) {
39062                 if (ts.some(types)) {
39063                     if (checkTruncationLength(context)) {
39064                         if (!isBareList) {
39065                             return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
39066                         }
39067                         else if (types.length > 2) {
39068                             return [
39069                                 typeToTypeNodeHelper(types[0], context),
39070                                 ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
39071                                 typeToTypeNodeHelper(types[types.length - 1], context)
39072                             ];
39073                         }
39074                     }
39075                     var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
39076                     /** Map from type reference identifier text to [type, index in `result` where the type node is] */
39077                     var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined;
39078                     var result_3 = [];
39079                     var i = 0;
39080                     for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
39081                         var type = types_1[_i];
39082                         i++;
39083                         if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
39084                             result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
39085                             var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
39086                             if (typeNode_1) {
39087                                 result_3.push(typeNode_1);
39088                             }
39089                             break;
39090                         }
39091                         context.approximateLength += 2; // Account for whitespace + separator
39092                         var typeNode = typeToTypeNodeHelper(type, context);
39093                         if (typeNode) {
39094                             result_3.push(typeNode);
39095                             if (seenNames && ts.isIdentifierTypeReference(typeNode)) {
39096                                 seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]);
39097                             }
39098                         }
39099                     }
39100                     if (seenNames) {
39101                         // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where
39102                         // occurrences of the same name actually come from different
39103                         // namespaces, go through the single-identifier type reference nodes
39104                         // we just generated, and see if any names were generated more than
39105                         // once while referring to different types. If so, regenerate the
39106                         // type node for each entry by that name with the
39107                         // `UseFullyQualifiedType` flag enabled.
39108                         var saveContextFlags = context.flags;
39109                         context.flags |= 64 /* UseFullyQualifiedType */;
39110                         seenNames.forEach(function (types) {
39111                             if (!ts.arrayIsHomogeneous(types, function (_a, _b) {
39112                                 var a = _a[0];
39113                                 var b = _b[0];
39114                                 return typesAreSameReference(a, b);
39115                             })) {
39116                                 for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
39117                                     var _a = types_2[_i], type = _a[0], resultIndex = _a[1];
39118                                     result_3[resultIndex] = typeToTypeNodeHelper(type, context);
39119                                 }
39120                             }
39121                         });
39122                         context.flags = saveContextFlags;
39123                     }
39124                     return result_3;
39125                 }
39126             }
39127             function typesAreSameReference(a, b) {
39128                 return a === b
39129                     || !!a.symbol && a.symbol === b.symbol
39130                     || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
39131             }
39132             function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) {
39133                 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
39134                 var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */);
39135                 var indexingParameter = ts.createParameter(
39136                 /*decorators*/ undefined, 
39137                 /*modifiers*/ undefined, 
39138                 /*dotDotDotToken*/ undefined, name, 
39139                 /*questionToken*/ undefined, indexerTypeNode, 
39140                 /*initializer*/ undefined);
39141                 var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
39142                 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
39143                     context.encounteredError = true;
39144                 }
39145                 context.approximateLength += (name.length + 4);
39146                 return ts.createIndexSignature(
39147                 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
39148             }
39149             function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) {
39150                 var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
39151                 if (suppressAny)
39152                     context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
39153                 var typeParameters;
39154                 var typeArguments;
39155                 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
39156                     typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
39157                 }
39158                 else {
39159                     typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
39160                 }
39161                 var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); });
39162                 if (signature.thisParameter) {
39163                     var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
39164                     parameters.unshift(thisParameter);
39165                 }
39166                 var returnTypeNode;
39167                 var typePredicate = getTypePredicateOfSignature(signature);
39168                 if (typePredicate) {
39169                     var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39170                         ts.createToken(124 /* AssertsKeyword */) :
39171                         undefined;
39172                     var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39173                         ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
39174                         ts.createThisTypeNode();
39175                     var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
39176                     returnTypeNode = ts.createTypePredicateNodeWithModifier(assertsModifier, parameterName, typeNode);
39177                 }
39178                 else {
39179                     var returnType = getReturnTypeOfSignature(signature);
39180                     if (returnType && !(suppressAny && isTypeAny(returnType))) {
39181                         returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports);
39182                     }
39183                     else if (!suppressAny) {
39184                         returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */);
39185                     }
39186                 }
39187                 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
39188                 return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
39189             }
39190             function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
39191                 var savedContextFlags = context.flags;
39192                 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
39193                 var name = typeParameterToName(type, context);
39194                 var defaultParameter = getDefaultFromTypeParameter(type);
39195                 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
39196                 context.flags = savedContextFlags;
39197                 return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
39198             }
39199             function typeParameterToDeclaration(type, context, constraint) {
39200                 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
39201                 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
39202                 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
39203             }
39204             function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) {
39205                 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */);
39206                 if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
39207                     parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */);
39208                 }
39209                 var parameterType = getTypeOfSymbol(parameterSymbol);
39210                 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
39211                     parameterType = getOptionalType(parameterType);
39212                 }
39213                 var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports);
39214                 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined;
39215                 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
39216                 var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined;
39217                 var name = parameterDeclaration ? parameterDeclaration.name ?
39218                     parameterDeclaration.name.kind === 75 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
39219                         parameterDeclaration.name.kind === 153 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
39220                             cloneBindingName(parameterDeclaration.name) :
39221                     ts.symbolName(parameterSymbol) :
39222                     ts.symbolName(parameterSymbol);
39223                 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
39224                 var questionToken = isOptional ? ts.createToken(57 /* QuestionToken */) : undefined;
39225                 var parameterNode = ts.createParameter(
39226                 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, 
39227                 /*initializer*/ undefined);
39228                 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
39229                 return parameterNode;
39230                 function cloneBindingName(node) {
39231                     return elideInitializerAndSetEmitFlags(node);
39232                     function elideInitializerAndSetEmitFlags(node) {
39233                         if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
39234                             trackComputedName(node.expression, context.enclosingDeclaration, context);
39235                         }
39236                         var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
39237                         var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited);
39238                         if (clone.kind === 191 /* BindingElement */) {
39239                             clone.initializer = undefined;
39240                         }
39241                         return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
39242                     }
39243                 }
39244             }
39245             function trackComputedName(accessExpression, enclosingDeclaration, context) {
39246                 if (!context.tracker.trackSymbol)
39247                     return;
39248                 // get symbol of the first identifier of the entityName
39249                 var firstIdentifier = ts.getFirstIdentifier(accessExpression);
39250                 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
39251                 if (name) {
39252                     context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
39253                 }
39254             }
39255             function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
39256                 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
39257                 return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
39258             }
39259             function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
39260                 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
39261                 var chain;
39262                 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
39263                 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
39264                     chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
39265                     ts.Debug.assert(chain && chain.length > 0);
39266                 }
39267                 else {
39268                     chain = [symbol];
39269                 }
39270                 return chain;
39271                 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
39272                 function getSymbolChain(symbol, meaning, endOfChain) {
39273                     var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
39274                     var parentSpecifiers;
39275                     if (!accessibleSymbolChain ||
39276                         needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
39277                         // Go up and add our parent.
39278                         var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
39279                         if (ts.length(parents_1)) {
39280                             parentSpecifiers = parents_1.map(function (symbol) {
39281                                 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
39282                                     ? getSpecifierForModuleSymbol(symbol, context)
39283                                     : undefined;
39284                             });
39285                             var indices = parents_1.map(function (_, i) { return i; });
39286                             indices.sort(sortByBestName);
39287                             var sortedParents = indices.map(function (i) { return parents_1[i]; });
39288                             for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
39289                                 var parent = sortedParents_1[_i];
39290                                 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
39291                                 if (parentChain) {
39292                                     if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
39293                                         getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
39294                                         // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
39295                                         // No need to lookup an alias for the symbol in itself
39296                                         accessibleSymbolChain = parentChain;
39297                                         break;
39298                                     }
39299                                     accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
39300                                     break;
39301                                 }
39302                             }
39303                         }
39304                     }
39305                     if (accessibleSymbolChain) {
39306                         return accessibleSymbolChain;
39307                     }
39308                     if (
39309                     // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
39310                     endOfChain ||
39311                         // If a parent symbol is an anonymous type, don't write it.
39312                         !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
39313                         // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
39314                         if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39315                             return;
39316                         }
39317                         return [symbol];
39318                     }
39319                     function sortByBestName(a, b) {
39320                         var specifierA = parentSpecifiers[a];
39321                         var specifierB = parentSpecifiers[b];
39322                         if (specifierA && specifierB) {
39323                             var isBRelative = ts.pathIsRelative(specifierB);
39324                             if (ts.pathIsRelative(specifierA) === isBRelative) {
39325                                 // Both relative or both non-relative, sort by number of parts
39326                                 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
39327                             }
39328                             if (isBRelative) {
39329                                 // A is non-relative, B is relative: prefer A
39330                                 return -1;
39331                             }
39332                             // A is relative, B is non-relative: prefer B
39333                             return 1;
39334                         }
39335                         return 0;
39336                     }
39337                 }
39338             }
39339             function typeParametersToTypeParameterDeclarations(symbol, context) {
39340                 var typeParameterNodes;
39341                 var targetSymbol = getTargetSymbol(symbol);
39342                 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
39343                     typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
39344                 }
39345                 return typeParameterNodes;
39346             }
39347             function lookupTypeParameterNodes(chain, index, context) {
39348                 ts.Debug.assert(chain && 0 <= index && index < chain.length);
39349                 var symbol = chain[index];
39350                 var symbolId = "" + getSymbolId(symbol);
39351                 if (context.typeParameterSymbolList && context.typeParameterSymbolList.get(symbolId)) {
39352                     return undefined;
39353                 }
39354                 (context.typeParameterSymbolList || (context.typeParameterSymbolList = ts.createMap())).set(symbolId, true);
39355                 var typeParameterNodes;
39356                 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
39357                     var parentSymbol = symbol;
39358                     var nextSymbol_1 = chain[index + 1];
39359                     if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) {
39360                         var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
39361                         typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context);
39362                     }
39363                     else {
39364                         typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
39365                     }
39366                 }
39367                 return typeParameterNodes;
39368             }
39369             /**
39370              * Given A[B][C][D], finds A[B]
39371              */
39372             function getTopmostIndexedAccessType(top) {
39373                 if (ts.isIndexedAccessTypeNode(top.objectType)) {
39374                     return getTopmostIndexedAccessType(top.objectType);
39375                 }
39376                 return top;
39377             }
39378             function getSpecifierForModuleSymbol(symbol, context) {
39379                 var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */);
39380                 if (!file) {
39381                     var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); });
39382                     if (equivalentFileSymbol) {
39383                         file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */);
39384                     }
39385                 }
39386                 if (file && file.moduleName !== undefined) {
39387                     // Use the amd name if it is available
39388                     return file.moduleName;
39389                 }
39390                 if (!file) {
39391                     if (context.tracker.trackReferencedAmbientModule) {
39392                         var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
39393                         if (ts.length(ambientDecls)) {
39394                             for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
39395                                 var decl = ambientDecls_1[_i];
39396                                 context.tracker.trackReferencedAmbientModule(decl, symbol);
39397                             }
39398                         }
39399                     }
39400                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39401                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39402                     }
39403                 }
39404                 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
39405                     // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
39406                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39407                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39408                     }
39409                     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
39410                 }
39411                 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
39412                 var links = getSymbolLinks(symbol);
39413                 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
39414                 if (!specifier) {
39415                     var isBundle_1 = (compilerOptions.out || compilerOptions.outFile);
39416                     // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
39417                     // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
39418                     // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
39419                     // specifier preference
39420                     var moduleResolverHost = context.tracker.moduleResolverHost;
39421                     var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
39422                     specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }));
39423                     links.specifierCache = links.specifierCache || ts.createMap();
39424                     links.specifierCache.set(contextFile.path, specifier);
39425                 }
39426                 return specifier;
39427             }
39428             function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
39429                 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
39430                 var isTypeOf = meaning === 111551 /* Value */;
39431                 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39432                     // module is root, must use `ImportTypeNode`
39433                     var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
39434                     var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
39435                     var specifier = getSpecifierForModuleSymbol(chain[0], context);
39436                     if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
39437                         // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
39438                         // since declaration files with these kinds of references are liable to fail when published :(
39439                         context.encounteredError = true;
39440                         if (context.tracker.reportLikelyUnsafeImportRequiredError) {
39441                             context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
39442                         }
39443                     }
39444                     var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
39445                     if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
39446                         context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
39447                     context.approximateLength += specifier.length + 10; // specifier + import("")
39448                     if (!nonRootParts || ts.isEntityName(nonRootParts)) {
39449                         if (nonRootParts) {
39450                             var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
39451                             lastId.typeArguments = undefined;
39452                         }
39453                         return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
39454                     }
39455                     else {
39456                         var splitNode = getTopmostIndexedAccessType(nonRootParts);
39457                         var qualifier = splitNode.objectType.typeName;
39458                         return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
39459                     }
39460                 }
39461                 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
39462                 if (ts.isIndexedAccessTypeNode(entityName)) {
39463                     return entityName; // Indexed accesses can never be `typeof`
39464                 }
39465                 if (isTypeOf) {
39466                     return ts.createTypeQueryNode(entityName);
39467                 }
39468                 else {
39469                     var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
39470                     var lastTypeArgs = lastId.typeArguments;
39471                     lastId.typeArguments = undefined;
39472                     return ts.createTypeReferenceNode(entityName, lastTypeArgs);
39473                 }
39474                 function createAccessFromSymbolChain(chain, index, stopper) {
39475                     var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
39476                     var symbol = chain[index];
39477                     var parent = chain[index - 1];
39478                     var symbolName;
39479                     if (index === 0) {
39480                         context.flags |= 16777216 /* InInitialEntityName */;
39481                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39482                         context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
39483                         context.flags ^= 16777216 /* InInitialEntityName */;
39484                     }
39485                     else {
39486                         if (parent && getExportsOfSymbol(parent)) {
39487                             var exports_1 = getExportsOfSymbol(parent);
39488                             ts.forEachEntry(exports_1, function (ex, name) {
39489                                 if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
39490                                     symbolName = ts.unescapeLeadingUnderscores(name);
39491                                     return true;
39492                                 }
39493                             });
39494                         }
39495                     }
39496                     if (!symbolName) {
39497                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39498                     }
39499                     context.approximateLength += symbolName.length + 1;
39500                     if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
39501                         getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
39502                         getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
39503                         // Should use an indexed access
39504                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39505                         if (ts.isIndexedAccessTypeNode(LHS)) {
39506                             return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39507                         }
39508                         else {
39509                             return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39510                         }
39511                     }
39512                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39513                     identifier.symbol = symbol;
39514                     if (index > stopper) {
39515                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39516                         if (!ts.isEntityName(LHS)) {
39517                             return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
39518                         }
39519                         return ts.createQualifiedName(LHS, identifier);
39520                     }
39521                     return identifier;
39522                 }
39523             }
39524             function typeParameterShadowsNameInScope(escapedName, context, type) {
39525                 var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
39526                 if (result) {
39527                     if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) {
39528                         return false;
39529                     }
39530                     return true;
39531                 }
39532                 return false;
39533             }
39534             function typeParameterToName(type, context) {
39535                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
39536                     var cached = context.typeParameterNames.get("" + getTypeId(type));
39537                     if (cached) {
39538                         return cached;
39539                     }
39540                 }
39541                 var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
39542                 if (!(result.kind & 75 /* Identifier */)) {
39543                     return ts.createIdentifier("(Missing type parameter)");
39544                 }
39545                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
39546                     var rawtext = result.escapedText;
39547                     var i = 0;
39548                     var text = rawtext;
39549                     while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) {
39550                         i++;
39551                         text = rawtext + "_" + i;
39552                     }
39553                     if (text !== rawtext) {
39554                         result = ts.createIdentifier(text, result.typeArguments);
39555                     }
39556                     (context.typeParameterNames || (context.typeParameterNames = ts.createMap())).set("" + getTypeId(type), result);
39557                     (context.typeParameterNamesByText || (context.typeParameterNamesByText = ts.createMap())).set(result.escapedText, true);
39558                 }
39559                 return result;
39560             }
39561             function symbolToName(symbol, context, meaning, expectsIdentifier) {
39562                 var chain = lookupSymbolChain(symbol, context, meaning);
39563                 if (expectsIdentifier && chain.length !== 1
39564                     && !context.encounteredError
39565                     && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
39566                     context.encounteredError = true;
39567                 }
39568                 return createEntityNameFromSymbolChain(chain, chain.length - 1);
39569                 function createEntityNameFromSymbolChain(chain, index) {
39570                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39571                     var symbol = chain[index];
39572                     if (index === 0) {
39573                         context.flags |= 16777216 /* InInitialEntityName */;
39574                     }
39575                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39576                     if (index === 0) {
39577                         context.flags ^= 16777216 /* InInitialEntityName */;
39578                     }
39579                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39580                     identifier.symbol = symbol;
39581                     return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
39582                 }
39583             }
39584             function symbolToExpression(symbol, context, meaning) {
39585                 var chain = lookupSymbolChain(symbol, context, meaning);
39586                 return createExpressionFromSymbolChain(chain, chain.length - 1);
39587                 function createExpressionFromSymbolChain(chain, index) {
39588                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39589                     var symbol = chain[index];
39590                     if (index === 0) {
39591                         context.flags |= 16777216 /* InInitialEntityName */;
39592                     }
39593                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39594                     if (index === 0) {
39595                         context.flags ^= 16777216 /* InInitialEntityName */;
39596                     }
39597                     var firstChar = symbolName.charCodeAt(0);
39598                     if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39599                         return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context));
39600                     }
39601                     var canUsePropertyAccess = firstChar === 35 /* hash */ ?
39602                         symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
39603                         ts.isIdentifierStart(firstChar, languageVersion);
39604                     if (index === 0 || canUsePropertyAccess) {
39605                         var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39606                         identifier.symbol = symbol;
39607                         return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
39608                     }
39609                     else {
39610                         if (firstChar === 91 /* openBracket */) {
39611                             symbolName = symbolName.substring(1, symbolName.length - 1);
39612                             firstChar = symbolName.charCodeAt(0);
39613                         }
39614                         var expression = void 0;
39615                         if (ts.isSingleOrDoubleQuote(firstChar)) {
39616                             expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); }));
39617                             expression.singleQuote = firstChar === 39 /* singleQuote */;
39618                         }
39619                         else if (("" + +symbolName) === symbolName) {
39620                             expression = ts.createLiteral(+symbolName);
39621                         }
39622                         if (!expression) {
39623                             expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39624                             expression.symbol = symbol;
39625                         }
39626                         return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression);
39627                     }
39628                 }
39629             }
39630             function isSingleQuotedStringNamed(d) {
39631                 var name = ts.getNameOfDeclaration(d);
39632                 if (name && ts.isStringLiteral(name) && (name.singleQuote ||
39633                     (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) {
39634                     return true;
39635                 }
39636                 return false;
39637             }
39638             function getPropertyNameNodeForSymbol(symbol, context) {
39639                 var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
39640                 var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
39641                 if (fromNameType) {
39642                     return fromNameType;
39643                 }
39644                 if (ts.isKnownSymbol(symbol)) {
39645                     return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3)));
39646                 }
39647                 var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
39648                 return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote);
39649             }
39650             // See getNameForSymbolFromNameType for a stringy equivalent
39651             function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
39652                 var nameType = getSymbolLinks(symbol).nameType;
39653                 if (nameType) {
39654                     if (nameType.flags & 384 /* StringOrNumberLiteral */) {
39655                         var name = "" + nameType.value;
39656                         if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
39657                             return ts.createLiteral(name, !!singleQuote);
39658                         }
39659                         if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
39660                             return ts.createComputedPropertyName(ts.createLiteral(+name));
39661                         }
39662                         return createPropertyNameNodeForIdentifierOrLiteral(name);
39663                     }
39664                     if (nameType.flags & 8192 /* UniqueESSymbol */) {
39665                         return ts.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
39666                     }
39667                 }
39668             }
39669             function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) {
39670                 return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote);
39671             }
39672             function cloneNodeBuilderContext(context) {
39673                 var initial = __assign({}, context);
39674                 // Make type parameters created within this context not consume the name outside this context
39675                 // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
39676                 // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
39677                 // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
39678                 // were multiple generic overloads with similar generated type parameter names
39679                 // The effect:
39680                 // When we write out
39681                 // export const x: <T>(x: T) => T
39682                 // export const y: <T>(x: T) => T
39683                 // we write it out like that, rather than as
39684                 // export const x: <T>(x: T) => T
39685                 // export const y: <T_1>(x: T_1) => T_1
39686                 if (initial.typeParameterNames) {
39687                     initial.typeParameterNames = ts.cloneMap(initial.typeParameterNames);
39688                 }
39689                 if (initial.typeParameterNamesByText) {
39690                     initial.typeParameterNamesByText = ts.cloneMap(initial.typeParameterNamesByText);
39691                 }
39692                 if (initial.typeParameterSymbolList) {
39693                     initial.typeParameterSymbolList = ts.cloneMap(initial.typeParameterSymbolList);
39694                 }
39695                 return initial;
39696             }
39697             function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
39698                 return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); });
39699             }
39700             function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
39701                 return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
39702             }
39703             /**
39704              * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
39705              * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
39706              */
39707             function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) {
39708                 if (type !== errorType && enclosingDeclaration) {
39709                     var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration);
39710                     if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) {
39711                         // try to reuse the existing annotation
39712                         var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
39713                         if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
39714                             var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled);
39715                             if (result_4) {
39716                                 return result_4;
39717                             }
39718                         }
39719                     }
39720                 }
39721                 var oldFlags = context.flags;
39722                 if (type.flags & 8192 /* UniqueESSymbol */ &&
39723                     type.symbol === symbol) {
39724                     context.flags |= 1048576 /* AllowUniqueESSymbolType */;
39725                 }
39726                 var result = typeToTypeNodeHelper(type, context);
39727                 context.flags = oldFlags;
39728                 return result;
39729             }
39730             function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) {
39731                 if (type !== errorType && context.enclosingDeclaration) {
39732                     var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
39733                     if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) {
39734                         var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled);
39735                         if (result) {
39736                             return result;
39737                         }
39738                     }
39739                 }
39740                 return typeToTypeNodeHelper(type, context);
39741             }
39742             function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
39743                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
39744                     cancellationToken.throwIfCancellationRequested();
39745                 }
39746                 var hadError = false;
39747                 var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
39748                 if (hadError) {
39749                     return undefined;
39750                 }
39751                 return transformed === existing ? ts.getMutableClone(existing) : transformed;
39752                 function visitExistingNodeTreeSymbols(node) {
39753                     var _a, _b;
39754                     // We don't _actually_ support jsdoc namepath types, emit `any` instead
39755                     if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) {
39756                         return ts.createKeywordTypeNode(125 /* AnyKeyword */);
39757                     }
39758                     if (ts.isJSDocUnknownType(node)) {
39759                         return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
39760                     }
39761                     if (ts.isJSDocNullableType(node)) {
39762                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]);
39763                     }
39764                     if (ts.isJSDocOptionalType(node)) {
39765                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]);
39766                     }
39767                     if (ts.isJSDocNonNullableType(node)) {
39768                         return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
39769                     }
39770                     if (ts.isJSDocVariadicType(node)) {
39771                         return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39772                     }
39773                     if (ts.isJSDocTypeLiteral(node)) {
39774                         return ts.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) {
39775                             var name = ts.isIdentifier(t.name) ? t.name : t.name.right;
39776                             var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
39777                             var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
39778                             return ts.createPropertySignature(
39779                             /*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 */), 
39780                             /*initializer*/ undefined);
39781                         }));
39782                     }
39783                     if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
39784                         return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node);
39785                     }
39786                     if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
39787                         return ts.createTypeLiteralNode([ts.createIndexSignature(
39788                             /*decorators*/ undefined, 
39789                             /*modifiers*/ undefined, [ts.createParameter(
39790                                 /*decorators*/ undefined, 
39791                                 /*modifiers*/ undefined, 
39792                                 /*dotdotdotToken*/ undefined, "x", 
39793                                 /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
39794                     }
39795                     if (ts.isJSDocFunctionType(node)) {
39796                         if (ts.isJSDocConstructSignature(node)) {
39797                             var newTypeNode_1;
39798                             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(
39799                             /*decorators*/ undefined, 
39800                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39801                             /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols));
39802                         }
39803                         else {
39804                             return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter(
39805                             /*decorators*/ undefined, 
39806                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39807                             /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39808                         }
39809                     }
39810                     if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */, /*ignoreErrors*/ true))) {
39811                         return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
39812                     }
39813                     if (ts.isLiteralImportTypeNode(node)) {
39814                         return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf);
39815                     }
39816                     if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
39817                         var leftmost = ts.getFirstIdentifier(node);
39818                         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)))) {
39819                             hadError = true;
39820                             return node;
39821                         }
39822                         var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
39823                         if (sym) {
39824                             if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
39825                                 hadError = true;
39826                             }
39827                             else {
39828                                 (_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 */);
39829                                 includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
39830                             }
39831                             if (ts.isIdentifier(node)) {
39832                                 var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node);
39833                                 name.symbol = sym; // for quickinfo, which uses identifier symbol information
39834                                 return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */);
39835                             }
39836                         }
39837                     }
39838                     return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
39839                     function getEffectiveDotDotDotForParameter(p) {
39840                         return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined);
39841                     }
39842                     function rewriteModuleSpecifier(parent, lit) {
39843                         if (bundled) {
39844                             if (context.tracker && context.tracker.moduleResolverHost) {
39845                                 var targetFile = getExternalModuleFileFromDeclaration(parent);
39846                                 if (targetFile) {
39847                                     var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
39848                                     var resolverHost = {
39849                                         getCanonicalFileName: getCanonicalFileName,
39850                                         getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); },
39851                                         getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
39852                                     };
39853                                     var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
39854                                     return ts.createLiteral(newName);
39855                                 }
39856                             }
39857                         }
39858                         else {
39859                             if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
39860                                 var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
39861                                 if (moduleSym) {
39862                                     context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
39863                                 }
39864                             }
39865                         }
39866                         return lit;
39867                     }
39868                 }
39869             }
39870             function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
39871                 var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true);
39872                 var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false);
39873                 // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
39874                 // declaration mapping
39875                 // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
39876                 // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
39877                 // we're trying to emit from later on)
39878                 var enclosingDeclaration = context.enclosingDeclaration;
39879                 var results = [];
39880                 var visitedSymbols = ts.createMap();
39881                 var deferredPrivates;
39882                 var oldcontext = context;
39883                 context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
39884                             var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false);
39885                             if (accessibleResult.accessibility === 0 /* Accessible */) {
39886                                 // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
39887                                 var chain = lookupSymbolChainWorker(sym, context, meaning);
39888                                 if (!(sym.flags & 4 /* Property */)) {
39889                                     includePrivateSymbol(chain[0]);
39890                                 }
39891                             }
39892                             else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
39893                                 oldcontext.tracker.trackSymbol(sym, decl, meaning);
39894                             }
39895                         } }) });
39896                 if (oldcontext.usedSymbolNames) {
39897                     oldcontext.usedSymbolNames.forEach(function (_, name) {
39898                         context.usedSymbolNames.set(name, true);
39899                     });
39900                 }
39901                 ts.forEachEntry(symbolTable, function (symbol, name) {
39902                     var baseName = ts.unescapeLeadingUnderscores(name);
39903                     void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
39904                 });
39905                 var addingDeclare = !bundled;
39906                 var exportEquals = symbolTable.get("export=" /* ExportEquals */);
39907                 if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
39908                     symbolTable = ts.createSymbolTable();
39909                     // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
39910                     symbolTable.set("export=" /* ExportEquals */, exportEquals);
39911                 }
39912                 visitSymbolTable(symbolTable);
39913                 return mergeRedundantStatements(results);
39914                 function isIdentifierAndNotUndefined(node) {
39915                     return !!node && node.kind === 75 /* Identifier */;
39916                 }
39917                 function getNamesOfDeclaration(statement) {
39918                     if (ts.isVariableStatement(statement)) {
39919                         return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
39920                     }
39921                     return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
39922                 }
39923                 function flattenExportAssignedNamespace(statements) {
39924                     var exportAssignment = ts.find(statements, ts.isExportAssignment);
39925                     var ns = ts.find(statements, ts.isModuleDeclaration);
39926                     if (ns && exportAssignment && exportAssignment.isExportEquals &&
39927                         ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
39928                         ns.body && ts.isModuleBlock(ns.body)) {
39929                         // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
39930                         //  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
39931                         var excessExports = ts.filter(statements, function (s) { return !!(ts.getModifierFlags(s) & 1 /* Export */); });
39932                         if (ts.length(excessExports)) {
39933                             ns.body.statements = ts.createNodeArray(__spreadArrays(ns.body.statements, [ts.createExportDeclaration(
39934                                 /*decorators*/ undefined, 
39935                                 /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.createExportSpecifier(/*alias*/ undefined, id); })), 
39936                                 /*moduleSpecifier*/ undefined)]));
39937                         }
39938                         // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
39939                         if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, ns.name); })) {
39940                             results = [];
39941                             ts.forEach(ns.body.statements, function (s) {
39942                                 addResult(s, 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
39943                             });
39944                             statements = __spreadArrays(ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), results);
39945                         }
39946                     }
39947                     return statements;
39948                 }
39949                 function mergeExportDeclarations(statements) {
39950                     // Pass 2: Combine all `export {}` declarations
39951                     var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
39952                     if (ts.length(exports) > 1) {
39953                         var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
39954                         statements = __spreadArrays(nonExports, [ts.createExportDeclaration(
39955                             /*decorators*/ undefined, 
39956                             /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), 
39957                             /*moduleSpecifier*/ undefined)]);
39958                     }
39959                     // Pass 2b: Also combine all `export {} from "..."` declarations as needed
39960                     var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
39961                     if (ts.length(reexports) > 1) {
39962                         var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
39963                         if (groups.length !== reexports.length) {
39964                             var _loop_8 = function (group_1) {
39965                                 if (group_1.length > 1) {
39966                                     // remove group members from statements and then merge group members and add back to statements
39967                                     statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [
39968                                         ts.createExportDeclaration(
39969                                         /*decorators*/ undefined, 
39970                                         /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
39971                                     ]);
39972                                 }
39973                             };
39974                             for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
39975                                 var group_1 = groups_1[_i];
39976                                 _loop_8(group_1);
39977                             }
39978                         }
39979                     }
39980                     return statements;
39981                 }
39982                 function inlineExportModifiers(statements) {
39983                     // Pass 3: Move all `export {}`'s to `export` modifiers where possible
39984                     var exportDecl = ts.find(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause; });
39985                     if (exportDecl && exportDecl.exportClause && ts.isNamedExports(exportDecl.exportClause)) {
39986                         var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
39987                             if (!e.propertyName) {
39988                                 // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
39989                                 var associated = ts.filter(statements, function (s) { return ts.nodeHasName(s, e.name); });
39990                                 if (ts.length(associated) && ts.every(associated, canHaveExportModifier)) {
39991                                     ts.forEach(associated, addExportModifier);
39992                                     return undefined;
39993                                 }
39994                             }
39995                             return e;
39996                         });
39997                         if (!ts.length(replacements)) {
39998                             // all clauses removed, filter the export declaration
39999                             statements = ts.filter(statements, function (s) { return s !== exportDecl; });
40000                         }
40001                         else {
40002                             // some items filtered, others not - update the export declaration
40003                             // (mutating because why not, we're building a whole new tree here anyway)
40004                             exportDecl.exportClause.elements = ts.createNodeArray(replacements);
40005                         }
40006                     }
40007                     return statements;
40008                 }
40009                 function mergeRedundantStatements(statements) {
40010                     statements = flattenExportAssignedNamespace(statements);
40011                     statements = mergeExportDeclarations(statements);
40012                     statements = inlineExportModifiers(statements);
40013                     // 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
40014                     // declaration privacy is respected.
40015                     if (enclosingDeclaration &&
40016                         ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
40017                         (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
40018                         statements.push(ts.createEmptyExports());
40019                     }
40020                     return statements;
40021                 }
40022                 function canHaveExportModifier(node) {
40023                     return ts.isEnumDeclaration(node) ||
40024                         ts.isVariableStatement(node) ||
40025                         ts.isFunctionDeclaration(node) ||
40026                         ts.isClassDeclaration(node) ||
40027                         (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
40028                         ts.isInterfaceDeclaration(node) ||
40029                         isTypeDeclaration(node);
40030                 }
40031                 function addExportModifier(statement) {
40032                     var flags = (ts.getModifierFlags(statement) | 1 /* Export */) & ~2 /* Ambient */;
40033                     statement.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flags));
40034                     statement.modifierFlagsCache = 0;
40035                 }
40036                 function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
40037                     var oldDeferredPrivates = deferredPrivates;
40038                     if (!suppressNewPrivateContext) {
40039                         deferredPrivates = ts.createMap();
40040                     }
40041                     symbolTable.forEach(function (symbol) {
40042                         serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
40043                     });
40044                     if (!suppressNewPrivateContext) {
40045                         // deferredPrivates will be filled up by visiting the symbol table
40046                         // And will continue to iterate as elements are added while visited `deferredPrivates`
40047                         // (As that's how a map iterator is defined to work)
40048                         deferredPrivates.forEach(function (symbol) {
40049                             serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
40050                         });
40051                     }
40052                     deferredPrivates = oldDeferredPrivates;
40053                 }
40054                 function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
40055                     // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
40056                     // still skip reserializing it if we encounter the merged product later on
40057                     var visitedSym = getMergedSymbol(symbol);
40058                     if (visitedSymbols.has("" + getSymbolId(visitedSym))) {
40059                         return; // Already printed
40060                     }
40061                     visitedSymbols.set("" + getSymbolId(visitedSym), true);
40062                     // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
40063                     var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
40064                     if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
40065                         var oldContext = context;
40066                         context = cloneNodeBuilderContext(context);
40067                         var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
40068                         context = oldContext;
40069                         return result;
40070                     }
40071                 }
40072                 // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
40073                 // or a merge of some number of those.
40074                 // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
40075                 // each symbol in only one of the representations
40076                 // Also, synthesizing a default export of some kind
40077                 // If it's an alias: emit `export default ref`
40078                 // If it's a property: emit `export default _default` with a `_default` prop
40079                 // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
40080                 // These forms can merge, eg (`export default 12; export default interface A {}`)
40081                 function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
40082                     var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
40083                     var isDefault = symbol.escapedName === "default" /* Default */;
40084                     if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
40085                         // 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` :(
40086                         context.encounteredError = true;
40087                         // TODO: Issue error via symbol tracker?
40088                         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
40089                     }
40090                     var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
40091                         || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
40092                     if (needsPostExportDefault) {
40093                         isPrivate = true;
40094                     }
40095                     var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
40096                     var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
40097                         symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
40098                         symbol.escapedName !== "export=" /* ExportEquals */;
40099                     var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
40100                     if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
40101                         serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40102                     }
40103                     if (symbol.flags & 524288 /* TypeAlias */) {
40104                         serializeTypeAlias(symbol, symbolName, modifierFlags);
40105                     }
40106                     // Need to skip over export= symbols below - json source files get a single `Property` flagged
40107                     // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
40108                     if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
40109                         && symbol.escapedName !== "export=" /* ExportEquals */
40110                         && !(symbol.flags & 4194304 /* Prototype */)
40111                         && !(symbol.flags & 32 /* Class */)
40112                         && !isConstMergedWithNSPrintableAsSignatureMerge) {
40113                         serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags);
40114                     }
40115                     if (symbol.flags & 384 /* Enum */) {
40116                         serializeEnum(symbol, symbolName, modifierFlags);
40117                     }
40118                     if (symbol.flags & 32 /* Class */) {
40119                         if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) {
40120                             // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
40121                             // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
40122                             // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
40123                             serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40124                         }
40125                         else {
40126                             serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40127                         }
40128                     }
40129                     if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
40130                         serializeModule(symbol, symbolName, modifierFlags);
40131                     }
40132                     if (symbol.flags & 64 /* Interface */) {
40133                         serializeInterface(symbol, symbolName, modifierFlags);
40134                     }
40135                     if (symbol.flags & 2097152 /* Alias */) {
40136                         serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40137                     }
40138                     if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
40139                         serializeMaybeAliasAssignment(symbol);
40140                     }
40141                     if (symbol.flags & 8388608 /* ExportStar */) {
40142                         // synthesize export * from "moduleReference"
40143                         // Straightforward - only one thing to do - make an export declaration
40144                         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
40145                             var node = _a[_i];
40146                             var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
40147                             if (!resolvedModule)
40148                                 continue;
40149                             addResult(ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*exportClause*/ undefined, ts.createLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
40150                         }
40151                     }
40152                     if (needsPostExportDefault) {
40153                         addResult(ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
40154                     }
40155                 }
40156                 function includePrivateSymbol(symbol) {
40157                     if (ts.some(symbol.declarations, ts.isParameterDeclaration))
40158                         return;
40159                     ts.Debug.assertIsDefined(deferredPrivates);
40160                     getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
40161                     deferredPrivates.set("" + getSymbolId(symbol), symbol);
40162                 }
40163                 function isExportingScope(enclosingDeclaration) {
40164                     return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
40165                         (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
40166                 }
40167                 // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
40168                 // Note: This _mutates_ `node` without using `updateNode` - the assumption being that all nodes should be manufactured fresh by the node builder
40169                 function addResult(node, additionalModifierFlags) {
40170                     var newModifierFlags = 0 /* None */;
40171                     if (additionalModifierFlags & 1 /* Export */ &&
40172                         enclosingDeclaration &&
40173                         isExportingScope(enclosingDeclaration) &&
40174                         canHaveExportModifier(node)) {
40175                         // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
40176                         newModifierFlags |= 1 /* Export */;
40177                     }
40178                     if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
40179                         (!enclosingDeclaration || !(enclosingDeclaration.flags & 8388608 /* Ambient */)) &&
40180                         (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
40181                         // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
40182                         newModifierFlags |= 2 /* Ambient */;
40183                     }
40184                     if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
40185                         newModifierFlags |= 512 /* Default */;
40186                     }
40187                     if (newModifierFlags) {
40188                         node.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(newModifierFlags | ts.getModifierFlags(node)));
40189                         node.modifierFlagsCache = 0; // Reset computed flags cache
40190                     }
40191                     results.push(node);
40192                 }
40193                 function serializeTypeAlias(symbol, symbolName, modifierFlags) {
40194                     var aliasType = getDeclaredTypeOfTypeAlias(symbol);
40195                     var typeParams = getSymbolLinks(symbol).typeParameters;
40196                     var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
40197                     var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias);
40198                     var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
40199                     var oldFlags = context.flags;
40200                     context.flags |= 8388608 /* InTypeAlias */;
40201                     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);
40202                     context.flags = oldFlags;
40203                 }
40204                 function serializeInterface(symbol, symbolName, modifierFlags) {
40205                     var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
40206                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40207                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40208                     var baseTypes = getBaseTypes(interfaceType);
40209                     var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
40210                     var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
40211                     var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 165 /* CallSignature */);
40212                     var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 166 /* ConstructSignature */);
40213                     var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
40214                     var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b); }))];
40215                     addResult(ts.createInterfaceDeclaration(
40216                     /*decorators*/ undefined, 
40217                     /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags);
40218                 }
40219                 function getNamespaceMembersForSerialization(symbol) {
40220                     return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
40221                 }
40222                 function isTypeOnlyNamespace(symbol) {
40223                     return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
40224                 }
40225                 function serializeModule(symbol, symbolName, modifierFlags) {
40226                     var members = getNamespaceMembersForSerialization(symbol);
40227                     // 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)
40228                     var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
40229                     var realMembers = locationMap.get("real") || ts.emptyArray;
40230                     var mergedMembers = locationMap.get("merged") || ts.emptyArray;
40231                     // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
40232                     // 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,
40233                     // so we don't even have placeholders to fill in.
40234                     if (ts.length(realMembers)) {
40235                         var localName = getInternalSymbolName(symbol, symbolName);
40236                         serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
40237                     }
40238                     if (ts.length(mergedMembers)) {
40239                         var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration);
40240                         var localName = getInternalSymbolName(symbol, symbolName);
40241                         var nsBody = ts.createModuleBlock([ts.createExportDeclaration(
40242                             /*decorators*/ undefined, 
40243                             /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
40244                                 var _a, _b;
40245                                 var name = ts.unescapeLeadingUnderscores(s.escapedName);
40246                                 var localName = getInternalSymbolName(s, name);
40247                                 var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
40248                                 if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) {
40249                                     (_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);
40250                                     return undefined;
40251                                 }
40252                                 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40253                                 includePrivateSymbol(target || s);
40254                                 var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
40255                                 return ts.createExportSpecifier(name === targetName ? undefined : targetName, name);
40256                             })))]);
40257                         addResult(ts.createModuleDeclaration(
40258                         /*decorators*/ undefined, 
40259                         /*modifiers*/ undefined, ts.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
40260                     }
40261                 }
40262                 function serializeEnum(symbol, symbolName, modifierFlags) {
40263                     addResult(ts.createEnumDeclaration(
40264                     /*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) {
40265                         // TODO: Handle computed names
40266                         // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
40267                         // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
40268                         // _on the declaration_, not on the declaration's symbol...
40269                         var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) && getConstantValue(p.declarations[0]);
40270                         return ts.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined : ts.createLiteral(initializedValue));
40271                     })), modifierFlags);
40272                 }
40273                 function serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags) {
40274                     if (propertyAsAlias) {
40275                         serializeMaybeAliasAssignment(symbol);
40276                     }
40277                     else {
40278                         var type = getTypeOfSymbol(symbol);
40279                         var localName = getInternalSymbolName(symbol, symbolName);
40280                         if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
40281                             // 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
40282                             serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
40283                         }
40284                         else {
40285                             // 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!_
40286                             // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
40287                             var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
40288                                 : isConstVariable(symbol) ? 2 /* Const */
40289                                     : 1 /* Let */;
40290                             var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
40291                             var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
40292                             if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
40293                                 textRange = textRange.parent.parent;
40294                             }
40295                             var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40296                                 ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40297                             ], flags)), textRange);
40298                             addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
40299                             if (name !== localName && !isPrivate) {
40300                                 // We rename the variable declaration we generate for Property symbols since they may have a name which
40301                                 // conflicts with a local declaration. For example, given input:
40302                                 // ```
40303                                 // function g() {}
40304                                 // module.exports.g = g
40305                                 // ```
40306                                 // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
40307                                 // Naively, we would emit
40308                                 // ```
40309                                 // function g() {}
40310                                 // export const g: typeof g;
40311                                 // ```
40312                                 // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
40313                                 // the export declaration shadows it.
40314                                 // To work around that, we instead write
40315                                 // ```
40316                                 // function g() {}
40317                                 // const g_1: typeof g;
40318                                 // export { g_1 as g };
40319                                 // ```
40320                                 // To create an export named `g` that does _not_ shadow the local `g`
40321                                 addResult(ts.createExportDeclaration(
40322                                 /*decorators*/ undefined, 
40323                                 /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(name, localName)])), 0 /* None */);
40324                             }
40325                         }
40326                     }
40327                 }
40328                 function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
40329                     var signatures = getSignaturesOfType(type, 0 /* Call */);
40330                     for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
40331                         var sig = signatures_2[_i];
40332                         // Each overload becomes a separate function declaration, in order
40333                         var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled);
40334                         decl.name = ts.createIdentifier(localName);
40335                         // for expressions assigned to `var`s, use the `var` as the text range
40336                         addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags);
40337                     }
40338                     // Module symbol emit will take care of module-y members, provided it has exports
40339                     if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
40340                         var props = ts.filter(getPropertiesOfType(type), isNamespaceMember);
40341                         serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
40342                     }
40343                 }
40344                 function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
40345                     if (ts.length(props)) {
40346                         var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
40347                             return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
40348                                 return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
40349                             }) ? "local" : "remote";
40350                         });
40351                         var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
40352                         // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
40353                         // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
40354                         // Example:
40355                         // import Foo_1 = require("./exporter");
40356                         // export namespace ns {
40357                         //     import Foo = Foo_1.Foo;
40358                         //     export { Foo };
40359                         //     export const c: number;
40360                         // }
40361                         // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
40362                         // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
40363                         // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
40364                         // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
40365                         // emit akin to the above would be needed.
40366                         // Add a namespace
40367                         var fakespace = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(localName), ts.createModuleBlock([]), 16 /* Namespace */);
40368                         fakespace.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
40369                         fakespace.parent = enclosingDeclaration;
40370                         fakespace.locals = ts.createSymbolTable(props);
40371                         fakespace.symbol = props[0].parent;
40372                         var oldResults = results;
40373                         results = [];
40374                         var oldAddingDeclare = addingDeclare;
40375                         addingDeclare = false;
40376                         var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
40377                         var oldContext = context;
40378                         context = subcontext;
40379                         // 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
40380                         visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
40381                         context = oldContext;
40382                         addingDeclare = oldAddingDeclare;
40383                         var declarations = results;
40384                         results = oldResults;
40385                         fakespace.flags ^= 8 /* Synthesized */; // reset synthesized
40386                         fakespace.parent = undefined;
40387                         fakespace.locals = undefined;
40388                         fakespace.symbol = undefined;
40389                         fakespace.body = ts.createModuleBlock(declarations);
40390                         addResult(fakespace, modifierFlags); // namespaces can never be default exported
40391                     }
40392                 }
40393                 function isNamespaceMember(p) {
40394                     return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent));
40395                 }
40396                 function serializeAsClass(symbol, localName, modifierFlags) {
40397                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40398                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40399                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
40400                     var baseTypes = getBaseTypes(classType);
40401                     var implementsTypes = getImplementsTypes(classType);
40402                     var staticType = getTypeOfSymbol(symbol);
40403                     var staticBaseType = getBaseConstructorTypeOfClass(staticType);
40404                     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); }))]);
40405                     var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
40406                     var publicSymbolProps = ts.filter(symbolProps, function (s) {
40407                         // `valueDeclaration` could be undefined if inherited from
40408                         // a union/intersection base type, but inherited properties
40409                         // don't matter here.
40410                         var valueDecl = s.valueDeclaration;
40411                         return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
40412                     });
40413                     var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
40414                         // `valueDeclaration` could be undefined if inherited from
40415                         // a union/intersection base type, but inherited properties
40416                         // don't matter here.
40417                         var valueDecl = s.valueDeclaration;
40418                         return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
40419                     });
40420                     // Boil down all private properties into a single one.
40421                     var privateProperties = hasPrivateIdentifier ?
40422                         [ts.createProperty(
40423                             /*decorators*/ undefined, 
40424                             /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
40425                             /*questionOrExclamationToken*/ undefined, 
40426                             /*type*/ undefined, 
40427                             /*initializer*/ undefined)] :
40428                         ts.emptyArray;
40429                     var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
40430                     // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
40431                     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); });
40432                     var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */);
40433                     for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) {
40434                         var c = constructors_1[_i];
40435                         // A constructor's return type and type parameters are supposed to be controlled by the enclosing class declaration
40436                         // `signatureToSignatureDeclarationHelper` appends them regardless, so for now we delete them here
40437                         c.type = undefined;
40438                         c.typeParameters = undefined;
40439                     }
40440                     var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
40441                     addResult(ts.setTextRange(ts.createClassDeclaration(
40442                     /*decorators*/ undefined, 
40443                     /*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);
40444                 }
40445                 function serializeAsAlias(symbol, localName, modifierFlags) {
40446                     // synthesize an alias, eg `export { symbolName as Name }`
40447                     // need to mark the alias `symbol` points at
40448                     // as something we need to serialize as a private declaration as well
40449                     var node = getDeclarationOfAliasSymbol(symbol);
40450                     if (!node)
40451                         return ts.Debug.fail();
40452                     var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
40453                     if (!target) {
40454                         return;
40455                     }
40456                     var verbatimTargetName = ts.unescapeLeadingUnderscores(target.escapedName);
40457                     if (verbatimTargetName === "export=" /* ExportEquals */ && (compilerOptions.esModuleInterop || compilerOptions.allowSyntheticDefaultImports)) {
40458                         // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
40459                         verbatimTargetName = "default" /* Default */;
40460                     }
40461                     var targetName = getInternalSymbolName(target, verbatimTargetName);
40462                     includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
40463                     switch (node.kind) {
40464                         case 253 /* ImportEqualsDeclaration */:
40465                             // Could be a local `import localName = ns.member` or
40466                             // an external `import localName = require("whatever")`
40467                             var isLocalImport = !(target.flags & 512 /* ValueModule */);
40468                             addResult(ts.createImportEqualsDeclaration(
40469                             /*decorators*/ undefined, 
40470                             /*modifiers*/ undefined, ts.createIdentifier(localName), isLocalImport
40471                                 ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
40472                                 : ts.createExternalModuleReference(ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)))), isLocalImport ? modifierFlags : 0 /* None */);
40473                             break;
40474                         case 252 /* NamespaceExportDeclaration */:
40475                             // export as namespace foo
40476                             // TODO: Not part of a file's local or export symbol tables
40477                             // Is bound into file.symbol.globalExports instead, which we don't currently traverse
40478                             addResult(ts.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
40479                             break;
40480                         case 255 /* ImportClause */:
40481                             addResult(ts.createImportDeclaration(
40482                             /*decorators*/ undefined, 
40483                             /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), 
40484                             // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
40485                             // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
40486                             // In such cases, the `target` refers to the module itself already
40487                             ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40488                             break;
40489                         case 256 /* NamespaceImport */:
40490                             addResult(ts.createImportDeclaration(
40491                             /*decorators*/ undefined, 
40492                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamespaceImport(ts.createIdentifier(localName))), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40493                             break;
40494                         case 262 /* NamespaceExport */:
40495                             addResult(ts.createExportDeclaration(
40496                             /*decorators*/ undefined, 
40497                             /*modifiers*/ undefined, ts.createNamespaceExport(ts.createIdentifier(localName)), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40498                             break;
40499                         case 258 /* ImportSpecifier */:
40500                             addResult(ts.createImportDeclaration(
40501                             /*decorators*/ undefined, 
40502                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([
40503                                 ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName))
40504                             ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40505                             break;
40506                         case 263 /* ExportSpecifier */:
40507                             // does not use localName because the symbol name in this case refers to the name in the exports table,
40508                             // which we must exactly preserve
40509                             var specifier = node.parent.parent.moduleSpecifier;
40510                             // targetName is only used when the target is local, as otherwise the target is an alias that points at
40511                             // another file
40512                             serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.createLiteral(specifier.text) : undefined);
40513                             break;
40514                         case 259 /* ExportAssignment */:
40515                             serializeMaybeAliasAssignment(symbol);
40516                             break;
40517                         case 209 /* BinaryExpression */:
40518                         case 194 /* PropertyAccessExpression */:
40519                             // Could be best encoded as though an export specifier or as though an export assignment
40520                             // If name is default or export=, do an export assignment
40521                             // Otherwise do an export specifier
40522                             if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
40523                                 serializeMaybeAliasAssignment(symbol);
40524                             }
40525                             else {
40526                                 serializeExportSpecifier(localName, targetName);
40527                             }
40528                             break;
40529                         default:
40530                             return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
40531                     }
40532                 }
40533                 function serializeExportSpecifier(localName, targetName, specifier) {
40534                     addResult(ts.createExportDeclaration(
40535                     /*decorators*/ undefined, 
40536                     /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
40537                 }
40538                 function serializeMaybeAliasAssignment(symbol) {
40539                     if (symbol.flags & 4194304 /* Prototype */) {
40540                         return;
40541                     }
40542                     var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
40543                     var isExportEquals = name === "export=" /* ExportEquals */;
40544                     var isDefault = name === "default" /* Default */;
40545                     var isExportAssignment = isExportEquals || isDefault;
40546                     // synthesize export = ref
40547                     // ref should refer to either be a locally scoped symbol which we need to emit, or
40548                     // a reference to another namespace/module which we may need to emit an `import` statement for
40549                     var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
40550                     // serialize what the alias points to, preserve the declaration's initializer
40551                     var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40552                     // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
40553                     if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
40554                         // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
40555                         // eg, `namespace A { export class B {} }; exports = A.B;`
40556                         // Technically, this is all that's required in the case where the assignment is an entity name expression
40557                         var expr = isExportAssignment ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl);
40558                         var first_1 = ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
40559                         var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
40560                         if (referenced || target) {
40561                             includePrivateSymbol(referenced || target);
40562                         }
40563                         // We disable the context's symbol tracker for the duration of this name serialization
40564                         // as, by virtue of being here, the name is required to print something, and we don't want to
40565                         // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
40566                         // a visibility error here (as they're not visible within any scope), but we want to hoist them
40567                         // into the containing scope anyway, so we want to skip the visibility checks.
40568                         var oldTrack = context.tracker.trackSymbol;
40569                         context.tracker.trackSymbol = ts.noop;
40570                         if (isExportAssignment) {
40571                             results.push(ts.createExportAssignment(
40572                             /*decorators*/ undefined, 
40573                             /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
40574                         }
40575                         else {
40576                             if (first_1 === expr) {
40577                                 // serialize as `export {target as name}`
40578                                 serializeExportSpecifier(name, ts.idText(first_1));
40579                             }
40580                             else if (ts.isClassExpression(expr)) {
40581                                 serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
40582                             }
40583                             else {
40584                                 // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
40585                                 var varName = getUnusedName(name, symbol);
40586                                 addResult(ts.createImportEqualsDeclaration(
40587                                 /*decorators*/ undefined, 
40588                                 /*modifiers*/ undefined, ts.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
40589                                 serializeExportSpecifier(name, varName);
40590                             }
40591                         }
40592                         context.tracker.trackSymbol = oldTrack;
40593                     }
40594                     else {
40595                         // serialize as an anonymous property declaration
40596                         var varName = getUnusedName(name, symbol);
40597                         // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
40598                         // (Unwidened types can only exist in expression contexts and should never be serialized)
40599                         var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
40600                         if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
40601                             // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
40602                             serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */);
40603                         }
40604                         else {
40605                             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40606                                 ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40607                             ], 2 /* Const */));
40608                             addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */);
40609                         }
40610                         if (isExportAssignment) {
40611                             results.push(ts.createExportAssignment(
40612                             /*decorators*/ undefined, 
40613                             /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(varName)));
40614                         }
40615                         else if (name !== varName) {
40616                             serializeExportSpecifier(name, varName);
40617                         }
40618                     }
40619                 }
40620                 function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
40621                     // Only object types which are not constructable, or indexable, whose members all come from the
40622                     // context source file, and whose property names are all valid identifiers and not late-bound, _and_
40623                     // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
40624                     var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
40625                     return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
40626                         !getIndexInfoOfType(typeToSerialize, 0 /* String */) &&
40627                         !getIndexInfoOfType(typeToSerialize, 1 /* Number */) &&
40628                         !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
40629                         !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
40630                         !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) &&
40631                         !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
40632                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
40633                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
40634                         ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion) && !ts.isStringAKeyword(ts.symbolName(p)); });
40635                 }
40636                 function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
40637                     return function serializePropertySymbol(p, isStatic, baseType) {
40638                         var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
40639                         var isPrivate = !!(modifierFlags & 8 /* Private */);
40640                         if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
40641                             // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
40642                             // need to be merged namespace members
40643                             return [];
40644                         }
40645                         if (p.flags & 4194304 /* Prototype */ ||
40646                             (baseType && getPropertyOfType(baseType, p.escapedName)
40647                                 && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
40648                                 && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
40649                                 && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
40650                             return [];
40651                         }
40652                         var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
40653                         var name = getPropertyNameNodeForSymbol(p, context);
40654                         var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
40655                         if (p.flags & 98304 /* Accessor */ && useAccessors) {
40656                             var result = [];
40657                             if (p.flags & 65536 /* SetAccessor */) {
40658                                 result.push(ts.setTextRange(ts.createSetAccessor(
40659                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [ts.createParameter(
40660                                     /*decorators*/ undefined, 
40661                                     /*modifiers*/ undefined, 
40662                                     /*dotDotDotToken*/ undefined, "arg", 
40663                                     /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], 
40664                                 /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl));
40665                             }
40666                             if (p.flags & 32768 /* GetAccessor */) {
40667                                 var isPrivate_1 = modifierFlags & 8 /* Private */;
40668                                 result.push(ts.setTextRange(ts.createGetAccessor(
40669                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
40670                                 /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl));
40671                             }
40672                             return result;
40673                         }
40674                         // This is an else/if as accessors and properties can't merge in TS, but might in JS
40675                         // If this happens, we assume the accessor takes priority, as it imposes more constraints
40676                         else if (p.flags & (4 /* Property */ | 3 /* Variable */)) {
40677                             return ts.setTextRange(createProperty(
40678                             /*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), 
40679                             // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
40680                             // interface members can't have initializers, however class members _can_
40681                             /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl);
40682                         }
40683                         if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
40684                             var type = getTypeOfSymbol(p);
40685                             var signatures = getSignaturesOfType(type, 0 /* Call */);
40686                             if (flag & 8 /* Private */) {
40687                                 return ts.setTextRange(createProperty(
40688                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, 
40689                                 /*type*/ undefined, 
40690                                 /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]);
40691                             }
40692                             var results_1 = [];
40693                             for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
40694                                 var sig = signatures_3[_i];
40695                                 // Each overload becomes a separate method declaration, in order
40696                                 var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context);
40697                                 decl.name = name; // TODO: Clone
40698                                 if (flag) {
40699                                     decl.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flag));
40700                                 }
40701                                 if (p.flags & 16777216 /* Optional */) {
40702                                     decl.questionToken = ts.createToken(57 /* QuestionToken */);
40703                                 }
40704                                 results_1.push(ts.setTextRange(decl, sig.declaration));
40705                             }
40706                             return results_1;
40707                         }
40708                         // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
40709                         return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags));
40710                     };
40711                 }
40712                 function serializePropertySymbolForInterface(p, baseType) {
40713                     return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
40714                 }
40715                 function serializeSignatures(kind, input, baseType, outputKind) {
40716                     var signatures = getSignaturesOfType(input, kind);
40717                     if (kind === 1 /* Construct */) {
40718                         if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40719                             return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
40720                         }
40721                         if (baseType) {
40722                             // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
40723                             var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
40724                             if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40725                                 return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
40726                             }
40727                             if (baseSigs.length === signatures.length) {
40728                                 var failed = false;
40729                                 for (var i = 0; i < baseSigs.length; i++) {
40730                                     if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
40731                                         failed = true;
40732                                         break;
40733                                     }
40734                                 }
40735                                 if (!failed) {
40736                                     return []; // Every signature was identical - elide constructor list as it is inherited
40737                                 }
40738                             }
40739                         }
40740                         var privateProtected = 0;
40741                         for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
40742                             var s = signatures_4[_i];
40743                             if (s.declaration) {
40744                                 privateProtected |= ts.getSelectedModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
40745                             }
40746                         }
40747                         if (privateProtected) {
40748                             return [ts.setTextRange(ts.createConstructor(
40749                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(privateProtected), 
40750                                 /*parameters*/ [], 
40751                                 /*body*/ undefined), signatures[0].declaration)];
40752                         }
40753                     }
40754                     var results = [];
40755                     for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
40756                         var sig = signatures_5[_a];
40757                         // Each overload becomes a separate constructor declaration, in order
40758                         var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
40759                         results.push(ts.setTextRange(decl, sig.declaration));
40760                     }
40761                     return results;
40762                 }
40763                 function serializeIndexSignatures(input, baseType) {
40764                     var results = [];
40765                     for (var _i = 0, _a = [0 /* String */, 1 /* Number */]; _i < _a.length; _i++) {
40766                         var type = _a[_i];
40767                         var info = getIndexInfoOfType(input, type);
40768                         if (info) {
40769                             if (baseType) {
40770                                 var baseInfo = getIndexInfoOfType(baseType, type);
40771                                 if (baseInfo) {
40772                                     if (isTypeIdenticalTo(info.type, baseInfo.type)) {
40773                                         continue; // elide identical index signatures
40774                                     }
40775                                 }
40776                             }
40777                             results.push(indexInfoToIndexSignatureDeclarationHelper(info, type, context));
40778                         }
40779                     }
40780                     return results;
40781                 }
40782                 function serializeBaseType(t, staticType, rootName) {
40783                     var ref = trySerializeAsTypeReference(t);
40784                     if (ref) {
40785                         return ref;
40786                     }
40787                     var tempName = getUnusedName(rootName + "_base");
40788                     var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40789                         ts.createVariableDeclaration(tempName, typeToTypeNodeHelper(staticType, context))
40790                     ], 2 /* Const */));
40791                     addResult(statement, 0 /* None */);
40792                     return ts.createExpressionWithTypeArguments(/*typeArgs*/ undefined, ts.createIdentifier(tempName));
40793                 }
40794                 function trySerializeAsTypeReference(t) {
40795                     var typeArgs;
40796                     var reference;
40797                     // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
40798                     // which we can't write out in a syntactically valid way as an expression
40799                     if (t.target && getAccessibleSymbolChain(t.target.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40800                         typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
40801                         reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
40802                     }
40803                     else if (t.symbol && getAccessibleSymbolChain(t.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40804                         reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
40805                     }
40806                     if (reference) {
40807                         return ts.createExpressionWithTypeArguments(typeArgs, reference);
40808                     }
40809                 }
40810                 function getUnusedName(input, symbol) {
40811                     if (symbol) {
40812                         if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
40813                             return context.remappedSymbolNames.get("" + getSymbolId(symbol));
40814                         }
40815                     }
40816                     if (symbol) {
40817                         input = getNameCandidateWorker(symbol, input);
40818                     }
40819                     var i = 0;
40820                     var original = input;
40821                     while (context.usedSymbolNames.has(input)) {
40822                         i++;
40823                         input = original + "_" + i;
40824                     }
40825                     context.usedSymbolNames.set(input, true);
40826                     if (symbol) {
40827                         context.remappedSymbolNames.set("" + getSymbolId(symbol), input);
40828                     }
40829                     return input;
40830                 }
40831                 function getNameCandidateWorker(symbol, localName) {
40832                     if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
40833                         var flags = context.flags;
40834                         context.flags |= 16777216 /* InInitialEntityName */;
40835                         var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
40836                         context.flags = flags;
40837                         localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
40838                     }
40839                     if (localName === "default" /* Default */) {
40840                         localName = "_default";
40841                     }
40842                     else if (localName === "export=" /* ExportEquals */) {
40843                         localName = "_exports";
40844                     }
40845                     localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
40846                     return localName;
40847                 }
40848                 function getInternalSymbolName(symbol, localName) {
40849                     if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
40850                         return context.remappedSymbolNames.get("" + getSymbolId(symbol));
40851                     }
40852                     localName = getNameCandidateWorker(symbol, localName);
40853                     // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
40854                     context.remappedSymbolNames.set("" + getSymbolId(symbol), localName);
40855                     return localName;
40856                 }
40857             }
40858         }
40859         function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
40860             if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
40861             return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
40862             function typePredicateToStringWorker(writer) {
40863                 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
40864                 );
40865                 var printer = ts.createPrinter({ removeComments: true });
40866                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
40867                 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
40868                 return writer;
40869             }
40870         }
40871         function formatUnionTypes(types) {
40872             var result = [];
40873             var flags = 0;
40874             for (var i = 0; i < types.length; i++) {
40875                 var t = types[i];
40876                 flags |= t.flags;
40877                 if (!(t.flags & 98304 /* Nullable */)) {
40878                     if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
40879                         var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
40880                         if (baseType.flags & 1048576 /* Union */) {
40881                             var count = baseType.types.length;
40882                             if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
40883                                 result.push(baseType);
40884                                 i += count - 1;
40885                                 continue;
40886                             }
40887                         }
40888                     }
40889                     result.push(t);
40890                 }
40891             }
40892             if (flags & 65536 /* Null */)
40893                 result.push(nullType);
40894             if (flags & 32768 /* Undefined */)
40895                 result.push(undefinedType);
40896             return result || types;
40897         }
40898         function visibilityToString(flags) {
40899             if (flags === 8 /* Private */) {
40900                 return "private";
40901             }
40902             if (flags === 16 /* Protected */) {
40903                 return "protected";
40904             }
40905             return "public";
40906         }
40907         function getTypeAliasForTypeLiteral(type) {
40908             if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
40909                 var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 182 /* ParenthesizedType */; });
40910                 if (node.kind === 247 /* TypeAliasDeclaration */) {
40911                     return getSymbolOfNode(node);
40912                 }
40913             }
40914             return undefined;
40915         }
40916         function isTopLevelInExternalModuleAugmentation(node) {
40917             return node && node.parent &&
40918                 node.parent.kind === 250 /* ModuleBlock */ &&
40919                 ts.isExternalModuleAugmentation(node.parent.parent);
40920         }
40921         function isDefaultBindingContext(location) {
40922             return location.kind === 290 /* SourceFile */ || ts.isAmbientModule(location);
40923         }
40924         function getNameOfSymbolFromNameType(symbol, context) {
40925             var nameType = getSymbolLinks(symbol).nameType;
40926             if (nameType) {
40927                 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
40928                     var name = "" + nameType.value;
40929                     if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
40930                         return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
40931                     }
40932                     if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
40933                         return "[" + name + "]";
40934                     }
40935                     return name;
40936                 }
40937                 if (nameType.flags & 8192 /* UniqueESSymbol */) {
40938                     return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
40939                 }
40940             }
40941         }
40942         /**
40943          * Gets a human-readable name for a symbol.
40944          * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
40945          *
40946          * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
40947          * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
40948          */
40949         function getNameOfSymbolAsWritten(symbol, context) {
40950             if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
40951                 // If it's not the first part of an entity name, it must print as `default`
40952                 (!(context.flags & 16777216 /* InInitialEntityName */) ||
40953                     // if the symbol is synthesized, it will only be referenced externally it must print as `default`
40954                     !symbol.declarations ||
40955                     // if not in the same binding context (source file, module declaration), it must print as `default`
40956                     (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
40957                 return "default";
40958             }
40959             if (symbol.declarations && symbol.declarations.length) {
40960                 var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
40961                 var name_2 = declaration && ts.getNameOfDeclaration(declaration);
40962                 if (declaration && name_2) {
40963                     if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
40964                         return ts.symbolName(symbol);
40965                     }
40966                     if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
40967                         var nameType = getSymbolLinks(symbol).nameType;
40968                         if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
40969                             // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
40970                             var result = getNameOfSymbolFromNameType(symbol, context);
40971                             if (result !== undefined) {
40972                                 return result;
40973                             }
40974                         }
40975                     }
40976                     return ts.declarationNameToString(name_2);
40977                 }
40978                 if (!declaration) {
40979                     declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
40980                 }
40981                 if (declaration.parent && declaration.parent.kind === 242 /* VariableDeclaration */) {
40982                     return ts.declarationNameToString(declaration.parent.name);
40983                 }
40984                 switch (declaration.kind) {
40985                     case 214 /* ClassExpression */:
40986                     case 201 /* FunctionExpression */:
40987                     case 202 /* ArrowFunction */:
40988                         if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
40989                             context.encounteredError = true;
40990                         }
40991                         return declaration.kind === 214 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
40992                 }
40993             }
40994             var name = getNameOfSymbolFromNameType(symbol, context);
40995             return name !== undefined ? name : ts.symbolName(symbol);
40996         }
40997         function isDeclarationVisible(node) {
40998             if (node) {
40999                 var links = getNodeLinks(node);
41000                 if (links.isVisible === undefined) {
41001                     links.isVisible = !!determineIfDeclarationIsVisible();
41002                 }
41003                 return links.isVisible;
41004             }
41005             return false;
41006             function determineIfDeclarationIsVisible() {
41007                 switch (node.kind) {
41008                     case 315 /* JSDocCallbackTag */:
41009                     case 322 /* JSDocTypedefTag */:
41010                     case 316 /* JSDocEnumTag */:
41011                         // Top-level jsdoc type aliases are considered exported
41012                         // 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
41013                         return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
41014                     case 191 /* BindingElement */:
41015                         return isDeclarationVisible(node.parent.parent);
41016                     case 242 /* VariableDeclaration */:
41017                         if (ts.isBindingPattern(node.name) &&
41018                             !node.name.elements.length) {
41019                             // If the binding pattern is empty, this variable declaration is not visible
41020                             return false;
41021                         }
41022                     // falls through
41023                     case 249 /* ModuleDeclaration */:
41024                     case 245 /* ClassDeclaration */:
41025                     case 246 /* InterfaceDeclaration */:
41026                     case 247 /* TypeAliasDeclaration */:
41027                     case 244 /* FunctionDeclaration */:
41028                     case 248 /* EnumDeclaration */:
41029                     case 253 /* ImportEqualsDeclaration */:
41030                         // external module augmentation is always visible
41031                         if (ts.isExternalModuleAugmentation(node)) {
41032                             return true;
41033                         }
41034                         var parent = getDeclarationContainer(node);
41035                         // If the node is not exported or it is not ambient module element (except import declaration)
41036                         if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
41037                             !(node.kind !== 253 /* ImportEqualsDeclaration */ && parent.kind !== 290 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
41038                             return isGlobalSourceFile(parent);
41039                         }
41040                         // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
41041                         return isDeclarationVisible(parent);
41042                     case 159 /* PropertyDeclaration */:
41043                     case 158 /* PropertySignature */:
41044                     case 163 /* GetAccessor */:
41045                     case 164 /* SetAccessor */:
41046                     case 161 /* MethodDeclaration */:
41047                     case 160 /* MethodSignature */:
41048                         if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) {
41049                             // Private/protected properties/methods are not visible
41050                             return false;
41051                         }
41052                     // Public properties/methods are visible if its parents are visible, so:
41053                     // falls through
41054                     case 162 /* Constructor */:
41055                     case 166 /* ConstructSignature */:
41056                     case 165 /* CallSignature */:
41057                     case 167 /* IndexSignature */:
41058                     case 156 /* Parameter */:
41059                     case 250 /* ModuleBlock */:
41060                     case 170 /* FunctionType */:
41061                     case 171 /* ConstructorType */:
41062                     case 173 /* TypeLiteral */:
41063                     case 169 /* TypeReference */:
41064                     case 174 /* ArrayType */:
41065                     case 175 /* TupleType */:
41066                     case 178 /* UnionType */:
41067                     case 179 /* IntersectionType */:
41068                     case 182 /* ParenthesizedType */:
41069                         return isDeclarationVisible(node.parent);
41070                     // Default binding, import specifier and namespace import is visible
41071                     // only on demand so by default it is not visible
41072                     case 255 /* ImportClause */:
41073                     case 256 /* NamespaceImport */:
41074                     case 258 /* ImportSpecifier */:
41075                         return false;
41076                     // Type parameters are always visible
41077                     case 155 /* TypeParameter */:
41078                     // Source file and namespace export are always visible
41079                     // falls through
41080                     case 290 /* SourceFile */:
41081                     case 252 /* NamespaceExportDeclaration */:
41082                         return true;
41083                     // Export assignments do not create name bindings outside the module
41084                     case 259 /* ExportAssignment */:
41085                         return false;
41086                     default:
41087                         return false;
41088                 }
41089             }
41090         }
41091         function collectLinkedAliases(node, setVisibility) {
41092             var exportSymbol;
41093             if (node.parent && node.parent.kind === 259 /* ExportAssignment */) {
41094                 exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
41095             }
41096             else if (node.parent.kind === 263 /* ExportSpecifier */) {
41097                 exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
41098             }
41099             var result;
41100             var visited;
41101             if (exportSymbol) {
41102                 visited = ts.createMap();
41103                 visited.set("" + getSymbolId(exportSymbol), true);
41104                 buildVisibleNodeList(exportSymbol.declarations);
41105             }
41106             return result;
41107             function buildVisibleNodeList(declarations) {
41108                 ts.forEach(declarations, function (declaration) {
41109                     var resultNode = getAnyImportSyntax(declaration) || declaration;
41110                     if (setVisibility) {
41111                         getNodeLinks(declaration).isVisible = true;
41112                     }
41113                     else {
41114                         result = result || [];
41115                         ts.pushIfUnique(result, resultNode);
41116                     }
41117                     if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
41118                         // Add the referenced top container visible
41119                         var internalModuleReference = declaration.moduleReference;
41120                         var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
41121                         var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
41122                         var id = importSymbol && "" + getSymbolId(importSymbol);
41123                         if (importSymbol && !visited.has(id)) {
41124                             visited.set(id, true);
41125                             buildVisibleNodeList(importSymbol.declarations);
41126                         }
41127                     }
41128                 });
41129             }
41130         }
41131         /**
41132          * Push an entry on the type resolution stack. If an entry with the given target and the given property name
41133          * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
41134          * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
41135          * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
41136          * In order to see if the same query has already been done before, the target object and the propertyName both
41137          * must match the one passed in.
41138          *
41139          * @param target The symbol, type, or signature whose type is being queried
41140          * @param propertyName The property name that should be used to query the target for its type
41141          */
41142         function pushTypeResolution(target, propertyName) {
41143             var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
41144             if (resolutionCycleStartIndex >= 0) {
41145                 // A cycle was found
41146                 var length_3 = resolutionTargets.length;
41147                 for (var i = resolutionCycleStartIndex; i < length_3; i++) {
41148                     resolutionResults[i] = false;
41149                 }
41150                 return false;
41151             }
41152             resolutionTargets.push(target);
41153             resolutionResults.push(/*items*/ true);
41154             resolutionPropertyNames.push(propertyName);
41155             return true;
41156         }
41157         function findResolutionCycleStartIndex(target, propertyName) {
41158             for (var i = resolutionTargets.length - 1; i >= 0; i--) {
41159                 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
41160                     return -1;
41161                 }
41162                 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
41163                     return i;
41164                 }
41165             }
41166             return -1;
41167         }
41168         function hasType(target, propertyName) {
41169             switch (propertyName) {
41170                 case 0 /* Type */:
41171                     return !!getSymbolLinks(target).type;
41172                 case 5 /* EnumTagType */:
41173                     return !!(getNodeLinks(target).resolvedEnumType);
41174                 case 2 /* DeclaredType */:
41175                     return !!getSymbolLinks(target).declaredType;
41176                 case 1 /* ResolvedBaseConstructorType */:
41177                     return !!target.resolvedBaseConstructorType;
41178                 case 3 /* ResolvedReturnType */:
41179                     return !!target.resolvedReturnType;
41180                 case 4 /* ImmediateBaseConstraint */:
41181                     return !!target.immediateBaseConstraint;
41182                 case 6 /* ResolvedTypeArguments */:
41183                     return !!target.resolvedTypeArguments;
41184             }
41185             return ts.Debug.assertNever(propertyName);
41186         }
41187         /**
41188          * Pop an entry from the type resolution stack and return its associated result value. The result value will
41189          * be true if no circularities were detected, or false if a circularity was found.
41190          */
41191         function popTypeResolution() {
41192             resolutionTargets.pop();
41193             resolutionPropertyNames.pop();
41194             return resolutionResults.pop();
41195         }
41196         function getDeclarationContainer(node) {
41197             return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
41198                 switch (node.kind) {
41199                     case 242 /* VariableDeclaration */:
41200                     case 243 /* VariableDeclarationList */:
41201                     case 258 /* ImportSpecifier */:
41202                     case 257 /* NamedImports */:
41203                     case 256 /* NamespaceImport */:
41204                     case 255 /* ImportClause */:
41205                         return false;
41206                     default:
41207                         return true;
41208                 }
41209             }).parent;
41210         }
41211         function getTypeOfPrototypeProperty(prototype) {
41212             // TypeScript 1.0 spec (April 2014): 8.4
41213             // Every class automatically contains a static property member named 'prototype',
41214             // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
41215             // It is an error to explicitly declare a static property member with the name 'prototype'.
41216             var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
41217             return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
41218         }
41219         // Return the type of the given property in the given type, or undefined if no such property exists
41220         function getTypeOfPropertyOfType(type, name) {
41221             var prop = getPropertyOfType(type, name);
41222             return prop ? getTypeOfSymbol(prop) : undefined;
41223         }
41224         function getTypeOfPropertyOrIndexSignature(type, name) {
41225             return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
41226         }
41227         function isTypeAny(type) {
41228             return type && (type.flags & 1 /* Any */) !== 0;
41229         }
41230         // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
41231         // assigned by contextual typing.
41232         function getTypeForBindingElementParent(node) {
41233             var symbol = getSymbolOfNode(node);
41234             return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
41235         }
41236         function getRestType(source, properties, symbol) {
41237             source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
41238             if (source.flags & 131072 /* Never */) {
41239                 return emptyObjectType;
41240             }
41241             if (source.flags & 1048576 /* Union */) {
41242                 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
41243             }
41244             var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
41245             if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
41246                 if (omitKeyType.flags & 131072 /* Never */) {
41247                     return source;
41248                 }
41249                 var omitTypeAlias = getGlobalOmitSymbol();
41250                 if (!omitTypeAlias) {
41251                     return errorType;
41252                 }
41253                 return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
41254             }
41255             var members = ts.createSymbolTable();
41256             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
41257                 var prop = _a[_i];
41258                 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
41259                     && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
41260                     && isSpreadableProperty(prop)) {
41261                     members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
41262                 }
41263             }
41264             var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
41265             var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
41266             var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
41267             result.objectFlags |= 131072 /* ObjectRestType */;
41268             return result;
41269         }
41270         // Determine the control flow type associated with a destructuring declaration or assignment. The following
41271         // forms of destructuring are possible:
41272         //   let { x } = obj;  // BindingElement
41273         //   let [ x ] = obj;  // BindingElement
41274         //   { x } = obj;      // ShorthandPropertyAssignment
41275         //   { x: v } = obj;   // PropertyAssignment
41276         //   [ x ] = obj;      // Expression
41277         // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
41278         // flow analyzer doesn't have to handle all the different syntactic forms.
41279         function getFlowTypeOfDestructuring(node, declaredType) {
41280             var reference = getSyntheticElementAccess(node);
41281             return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
41282         }
41283         function getSyntheticElementAccess(node) {
41284             var parentAccess = getParentElementAccess(node);
41285             if (parentAccess && parentAccess.flowNode) {
41286                 var propName = getDestructuringPropertyName(node);
41287                 if (propName) {
41288                     var result = ts.createNode(195 /* ElementAccessExpression */, node.pos, node.end);
41289                     result.parent = node;
41290                     result.expression = parentAccess;
41291                     var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end);
41292                     literal.parent = result;
41293                     literal.text = propName;
41294                     result.argumentExpression = literal;
41295                     result.flowNode = parentAccess.flowNode;
41296                     return result;
41297                 }
41298             }
41299         }
41300         function getParentElementAccess(node) {
41301             var ancestor = node.parent.parent;
41302             switch (ancestor.kind) {
41303                 case 191 /* BindingElement */:
41304                 case 281 /* PropertyAssignment */:
41305                     return getSyntheticElementAccess(ancestor);
41306                 case 192 /* ArrayLiteralExpression */:
41307                     return getSyntheticElementAccess(node.parent);
41308                 case 242 /* VariableDeclaration */:
41309                     return ancestor.initializer;
41310                 case 209 /* BinaryExpression */:
41311                     return ancestor.right;
41312             }
41313         }
41314         function getDestructuringPropertyName(node) {
41315             var parent = node.parent;
41316             if (node.kind === 191 /* BindingElement */ && parent.kind === 189 /* ObjectBindingPattern */) {
41317                 return getLiteralPropertyNameText(node.propertyName || node.name);
41318             }
41319             if (node.kind === 281 /* PropertyAssignment */ || node.kind === 282 /* ShorthandPropertyAssignment */) {
41320                 return getLiteralPropertyNameText(node.name);
41321             }
41322             return "" + parent.elements.indexOf(node);
41323         }
41324         function getLiteralPropertyNameText(name) {
41325             var type = getLiteralTypeFromPropertyName(name);
41326             return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
41327         }
41328         /** Return the inferred type for a binding element */
41329         function getTypeForBindingElement(declaration) {
41330             var pattern = declaration.parent;
41331             var parentType = getTypeForBindingElementParent(pattern.parent);
41332             // If no type or an any type was inferred for parent, infer that for the binding element
41333             if (!parentType || isTypeAny(parentType)) {
41334                 return parentType;
41335             }
41336             // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
41337             if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
41338                 parentType = getNonNullableType(parentType);
41339             }
41340             // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined`
41341             else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) {
41342                 parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
41343             }
41344             var type;
41345             if (pattern.kind === 189 /* ObjectBindingPattern */) {
41346                 if (declaration.dotDotDotToken) {
41347                     parentType = getReducedType(parentType);
41348                     if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
41349                         error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
41350                         return errorType;
41351                     }
41352                     var literalMembers = [];
41353                     for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
41354                         var element = _a[_i];
41355                         if (!element.dotDotDotToken) {
41356                             literalMembers.push(element.propertyName || element.name);
41357                         }
41358                     }
41359                     type = getRestType(parentType, literalMembers, declaration.symbol);
41360                 }
41361                 else {
41362                     // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
41363                     var name = declaration.propertyName || declaration.name;
41364                     var indexType = getLiteralTypeFromPropertyName(name);
41365                     var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name);
41366                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41367                 }
41368             }
41369             else {
41370                 // This elementType will be used if the specific property corresponding to this index is not
41371                 // present (aka the tuple element property). This call also checks that the parentType is in
41372                 // fact an iterable or array (depending on target language).
41373                 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, parentType, undefinedType, pattern);
41374                 var index_1 = pattern.elements.indexOf(declaration);
41375                 if (declaration.dotDotDotToken) {
41376                     // If the parent is a tuple type, the rest element has a tuple type of the
41377                     // remaining tuple element types. Otherwise, the rest element has an array type with same
41378                     // element type as the parent type.
41379                     type = everyType(parentType, isTupleType) ?
41380                         mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) :
41381                         createArrayType(elementType);
41382                 }
41383                 else if (isArrayLikeType(parentType)) {
41384                     var indexType = getLiteralType(index_1);
41385                     var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0;
41386                     var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, declaration.name, accessFlags) || errorType, declaration.name);
41387                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41388                 }
41389                 else {
41390                     type = elementType;
41391                 }
41392             }
41393             if (!declaration.initializer) {
41394                 return type;
41395             }
41396             if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
41397                 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
41398                 // undefined from the final type.
41399                 return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ?
41400                     getTypeWithFacts(type, 524288 /* NEUndefined */) :
41401                     type;
41402             }
41403             return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
41404         }
41405         function getTypeForDeclarationFromJSDocComment(declaration) {
41406             var jsdocType = ts.getJSDocType(declaration);
41407             if (jsdocType) {
41408                 return getTypeFromTypeNode(jsdocType);
41409             }
41410             return undefined;
41411         }
41412         function isNullOrUndefined(node) {
41413             var expr = ts.skipParentheses(node);
41414             return expr.kind === 100 /* NullKeyword */ || expr.kind === 75 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
41415         }
41416         function isEmptyArrayLiteral(node) {
41417             var expr = ts.skipParentheses(node);
41418             return expr.kind === 192 /* ArrayLiteralExpression */ && expr.elements.length === 0;
41419         }
41420         function addOptionality(type, optional) {
41421             if (optional === void 0) { optional = true; }
41422             return strictNullChecks && optional ? getOptionalType(type) : type;
41423         }
41424         // Return the inferred type for a variable, parameter, or property declaration
41425         function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
41426             // A variable declared in a for..in statement is of type string, or of type keyof T when the
41427             // right hand expression is of a type parameter type.
41428             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 231 /* ForInStatement */) {
41429                 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
41430                 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
41431             }
41432             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
41433                 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
41434                 // missing properties/signatures required to get its iteratedType (like
41435                 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
41436                 // or it may have led to an error inside getElementTypeOfIterable.
41437                 var forOfStatement = declaration.parent.parent;
41438                 return checkRightHandSideOfForOf(forOfStatement) || anyType;
41439             }
41440             if (ts.isBindingPattern(declaration.parent)) {
41441                 return getTypeForBindingElement(declaration);
41442             }
41443             var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
41444                 || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
41445             // Use type from type annotation if one is present
41446             var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
41447             if (declaredType) {
41448                 return addOptionality(declaredType, isOptional);
41449             }
41450             if ((noImplicitAny || ts.isInJSFile(declaration)) &&
41451                 declaration.kind === 242 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) &&
41452                 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
41453                 // If --noImplicitAny is on or the declaration is in a Javascript file,
41454                 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
41455                 // initializer or a 'null' or 'undefined' initializer.
41456                 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
41457                     return autoType;
41458                 }
41459                 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
41460                 // literal initializer.
41461                 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
41462                     return autoArrayType;
41463                 }
41464             }
41465             if (declaration.kind === 156 /* Parameter */) {
41466                 var func = declaration.parent;
41467                 // For a parameter of a set accessor, use the type of the get accessor if one is present
41468                 if (func.kind === 164 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
41469                     var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 163 /* GetAccessor */);
41470                     if (getter) {
41471                         var getterSignature = getSignatureFromDeclaration(getter);
41472                         var thisParameter = getAccessorThisParameter(func);
41473                         if (thisParameter && declaration === thisParameter) {
41474                             // Use the type from the *getter*
41475                             ts.Debug.assert(!thisParameter.type);
41476                             return getTypeOfSymbol(getterSignature.thisParameter);
41477                         }
41478                         return getReturnTypeOfSignature(getterSignature);
41479                     }
41480                 }
41481                 if (ts.isInJSFile(declaration)) {
41482                     var typeTag = ts.getJSDocType(func);
41483                     if (typeTag && ts.isFunctionTypeNode(typeTag)) {
41484                         return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration));
41485                     }
41486                 }
41487                 // Use contextual parameter type if one is available
41488                 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
41489                 if (type) {
41490                     return addOptionality(type, isOptional);
41491                 }
41492             }
41493             else if (ts.isInJSFile(declaration)) {
41494                 var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
41495                 if (containerObjectType) {
41496                     return containerObjectType;
41497                 }
41498             }
41499             // Use the type of the initializer expression if one is present and the declaration is
41500             // not a parameter of a contextually typed function
41501             if (declaration.initializer) {
41502                 var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
41503                 return addOptionality(type, isOptional);
41504             }
41505             if (ts.isJsxAttribute(declaration)) {
41506                 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
41507                 // I.e <Elem attr /> is sugar for <Elem attr={true} />
41508                 return trueType;
41509             }
41510             // If the declaration specifies a binding pattern and is not a parameter of a contextually
41511             // typed function, use the type implied by the binding pattern
41512             if (ts.isBindingPattern(declaration.name)) {
41513                 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
41514             }
41515             // No type specified and nothing can be inferred
41516             return undefined;
41517         }
41518         function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
41519             // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
41520             var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
41521             if (container) {
41522                 var tag = ts.getJSDocTypeTag(container);
41523                 if (tag && tag.typeExpression) {
41524                     return getTypeFromTypeNode(tag.typeExpression);
41525                 }
41526                 var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
41527                 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
41528             }
41529             var definedInConstructor = false;
41530             var definedInMethod = false;
41531             var jsdocType;
41532             var types;
41533             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
41534                 var declaration = _a[_i];
41535                 var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
41536                     ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
41537                         undefined;
41538                 if (!expression) {
41539                     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
41540                 }
41541                 var kind = ts.isAccessExpression(expression)
41542                     ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
41543                     : ts.getAssignmentDeclarationKind(expression);
41544                 if (kind === 4 /* ThisProperty */) {
41545                     if (isDeclarationInConstructor(expression)) {
41546                         definedInConstructor = true;
41547                     }
41548                     else {
41549                         definedInMethod = true;
41550                     }
41551                 }
41552                 if (!ts.isCallExpression(expression)) {
41553                     jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
41554                 }
41555                 if (!jsdocType) {
41556                     (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
41557                 }
41558             }
41559             var type = jsdocType;
41560             if (!type) {
41561                 if (!ts.length(types)) {
41562                     return errorType; // No types from any declarations :(
41563                 }
41564                 var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
41565                 // use only the constructor types unless they were only assigned null | undefined (including widening variants)
41566                 if (definedInMethod) {
41567                     var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol);
41568                     if (propType) {
41569                         (constructorTypes || (constructorTypes = [])).push(propType);
41570                         definedInConstructor = true;
41571                     }
41572                 }
41573                 var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
41574                 type = getUnionType(sourceTypes, 2 /* Subtype */);
41575             }
41576             var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
41577             if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
41578                 reportImplicitAny(symbol.valueDeclaration, anyType);
41579                 return anyType;
41580             }
41581             return widened;
41582         }
41583         function getJSContainerObjectType(decl, symbol, init) {
41584             if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
41585                 return undefined;
41586             }
41587             var exports = ts.createSymbolTable();
41588             while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
41589                 var s_2 = getSymbolOfNode(decl);
41590                 if (s_2 && ts.hasEntries(s_2.exports)) {
41591                     mergeSymbolTable(exports, s_2.exports);
41592                 }
41593                 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
41594             }
41595             var s = getSymbolOfNode(decl);
41596             if (s && ts.hasEntries(s.exports)) {
41597                 mergeSymbolTable(exports, s.exports);
41598             }
41599             var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
41600             type.objectFlags |= 16384 /* JSLiteral */;
41601             return type;
41602         }
41603         function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
41604             var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
41605             if (typeNode) {
41606                 var type = getWidenedType(getTypeFromTypeNode(typeNode));
41607                 if (!declaredType) {
41608                     return type;
41609                 }
41610                 else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
41611                     errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
41612                 }
41613             }
41614             if (symbol.parent) {
41615                 var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
41616                 if (typeNode_2) {
41617                     return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
41618                 }
41619             }
41620             return declaredType;
41621         }
41622         /** If we don't have an explicit JSDoc type, get the type from the initializer. */
41623         function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
41624             if (ts.isCallExpression(expression)) {
41625                 if (resolvedSymbol) {
41626                     return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
41627                 }
41628                 var objectLitType = checkExpressionCached(expression.arguments[2]);
41629                 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
41630                 if (valueType) {
41631                     return valueType;
41632                 }
41633                 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
41634                 if (getFunc) {
41635                     var getSig = getSingleCallSignature(getFunc);
41636                     if (getSig) {
41637                         return getReturnTypeOfSignature(getSig);
41638                     }
41639                 }
41640                 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
41641                 if (setFunc) {
41642                     var setSig = getSingleCallSignature(setFunc);
41643                     if (setSig) {
41644                         return getTypeOfFirstParameterOfSignature(setSig);
41645                     }
41646                 }
41647                 return anyType;
41648             }
41649             if (containsSameNamedThisProperty(expression.left, expression.right)) {
41650                 return anyType;
41651             }
41652             var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
41653             if (type.flags & 524288 /* Object */ &&
41654                 kind === 2 /* ModuleExports */ &&
41655                 symbol.escapedName === "export=" /* ExportEquals */) {
41656                 var exportedType = resolveStructuredTypeMembers(type);
41657                 var members_4 = ts.createSymbolTable();
41658                 ts.copyEntries(exportedType.members, members_4);
41659                 if (resolvedSymbol && !resolvedSymbol.exports) {
41660                     resolvedSymbol.exports = ts.createSymbolTable();
41661                 }
41662                 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
41663                     var _a;
41664                     var exportedMember = members_4.get(name);
41665                     if (exportedMember && exportedMember !== s) {
41666                         if (s.flags & 111551 /* Value */) {
41667                             // If the member has an additional value-like declaration, union the types from the two declarations,
41668                             // but issue an error if they occurred in two different files. The purpose is to support a JS file with
41669                             // a pattern like:
41670                             //
41671                             // module.exports = { a: true };
41672                             // module.exports.a = 3;
41673                             //
41674                             // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation
41675                             // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because
41676                             // it's unclear what that's supposed to mean, so it's probably a mistake.
41677                             if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) {
41678                                 var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName);
41679                                 var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration;
41680                                 ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41681                                 ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41682                             }
41683                             var union = createSymbol(s.flags | exportedMember.flags, name);
41684                             union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
41685                             union.valueDeclaration = exportedMember.valueDeclaration;
41686                             union.declarations = ts.concatenate(exportedMember.declarations, s.declarations);
41687                             members_4.set(name, union);
41688                         }
41689                         else {
41690                             members_4.set(name, mergeSymbol(s, exportedMember));
41691                         }
41692                     }
41693                     else {
41694                         members_4.set(name, s);
41695                     }
41696                 });
41697                 var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo);
41698                 result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
41699                 return result;
41700             }
41701             if (isEmptyArrayLiteralType(type)) {
41702                 reportImplicitAny(expression, anyArrayType);
41703                 return anyArrayType;
41704             }
41705             return type;
41706         }
41707         function containsSameNamedThisProperty(thisProperty, expression) {
41708             return ts.isPropertyAccessExpression(thisProperty)
41709                 && thisProperty.expression.kind === 104 /* ThisKeyword */
41710                 && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); });
41711         }
41712         function isDeclarationInConstructor(expression) {
41713             var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
41714             // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
41715             // Function expressions that are assigned to the prototype count as methods.
41716             return thisContainer.kind === 162 /* Constructor */ ||
41717                 thisContainer.kind === 244 /* FunctionDeclaration */ ||
41718                 (thisContainer.kind === 201 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
41719         }
41720         function getConstructorDefinedThisAssignmentTypes(types, declarations) {
41721             ts.Debug.assert(types.length === declarations.length);
41722             return types.filter(function (_, i) {
41723                 var declaration = declarations[i];
41724                 var expression = ts.isBinaryExpression(declaration) ? declaration :
41725                     ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
41726                 return expression && isDeclarationInConstructor(expression);
41727             });
41728         }
41729         /** check for definition in base class if any declaration is in a class */
41730         function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) {
41731             var parentDeclaration = ts.forEach(property.declarations, function (d) {
41732                 var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent;
41733                 return ts.isClassLike(parent) && parent;
41734             });
41735             if (parentDeclaration) {
41736                 var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration));
41737                 var baseClassType = classType && getBaseTypes(classType)[0];
41738                 if (baseClassType) {
41739                     return getTypeOfPropertyOfType(baseClassType, property.escapedName);
41740                 }
41741             }
41742         }
41743         // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
41744         // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
41745         // pattern. Otherwise, it is the type any.
41746         function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
41747             if (element.initializer) {
41748                 // The type implied by a binding pattern is independent of context, so we check the initializer with no
41749                 // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
41750                 // pattern.
41751                 var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
41752                 return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
41753             }
41754             if (ts.isBindingPattern(element.name)) {
41755                 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
41756             }
41757             if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
41758                 reportImplicitAny(element, anyType);
41759             }
41760             // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
41761             // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
41762             // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
41763             // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
41764             return includePatternInType ? nonInferrableAnyType : anyType;
41765         }
41766         // Return the type implied by an object binding pattern
41767         function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
41768             var members = ts.createSymbolTable();
41769             var stringIndexInfo;
41770             var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
41771             ts.forEach(pattern.elements, function (e) {
41772                 var name = e.propertyName || e.name;
41773                 if (e.dotDotDotToken) {
41774                     stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
41775                     return;
41776                 }
41777                 var exprType = getLiteralTypeFromPropertyName(name);
41778                 if (!isTypeUsableAsPropertyName(exprType)) {
41779                     // do not include computed properties in the implied type
41780                     objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
41781                     return;
41782                 }
41783                 var text = getPropertyNameFromType(exprType);
41784                 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
41785                 var symbol = createSymbol(flags, text);
41786                 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
41787                 symbol.bindingElement = e;
41788                 members.set(symbol.escapedName, symbol);
41789             });
41790             var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
41791             result.objectFlags |= objectFlags;
41792             if (includePatternInType) {
41793                 result.pattern = pattern;
41794                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41795             }
41796             return result;
41797         }
41798         // Return the type implied by an array binding pattern
41799         function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
41800             var elements = pattern.elements;
41801             var lastElement = ts.lastOrUndefined(elements);
41802             var hasRestElement = !!(lastElement && lastElement.kind === 191 /* BindingElement */ && lastElement.dotDotDotToken);
41803             if (elements.length === 0 || elements.length === 1 && hasRestElement) {
41804                 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
41805             }
41806             var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
41807             var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1;
41808             var result = createTupleType(elementTypes, minLength, hasRestElement);
41809             if (includePatternInType) {
41810                 result = cloneTypeReference(result);
41811                 result.pattern = pattern;
41812                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41813             }
41814             return result;
41815         }
41816         // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
41817         // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
41818         // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
41819         // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
41820         // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
41821         // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
41822         // the parameter.
41823         function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
41824             if (includePatternInType === void 0) { includePatternInType = false; }
41825             if (reportErrors === void 0) { reportErrors = false; }
41826             return pattern.kind === 189 /* ObjectBindingPattern */
41827                 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
41828                 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
41829         }
41830         // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
41831         // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
41832         // is a bit more involved. For example:
41833         //
41834         //   var [x, s = ""] = [1, "one"];
41835         //
41836         // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
41837         // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
41838         // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
41839         function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
41840             return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
41841         }
41842         function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
41843             if (type) {
41844                 if (reportErrors) {
41845                     reportErrorsFromWidening(declaration, type);
41846                 }
41847                 // always widen a 'unique symbol' type if the type was created for a different declaration.
41848                 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
41849                     type = esSymbolType;
41850                 }
41851                 return getWidenedType(type);
41852             }
41853             // Rest parameters default to type any[], other parameters default to type any
41854             type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
41855             // Report implicit any errors unless this is a private property within an ambient declaration
41856             if (reportErrors) {
41857                 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
41858                     reportImplicitAny(declaration, type);
41859                 }
41860             }
41861             return type;
41862         }
41863         function declarationBelongsToPrivateAmbientMember(declaration) {
41864             var root = ts.getRootDeclaration(declaration);
41865             var memberDeclaration = root.kind === 156 /* Parameter */ ? root.parent : root;
41866             return isPrivateWithinAmbient(memberDeclaration);
41867         }
41868         function tryGetTypeFromEffectiveTypeNode(declaration) {
41869             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
41870             if (typeNode) {
41871                 return getTypeFromTypeNode(typeNode);
41872             }
41873         }
41874         function getTypeOfVariableOrParameterOrProperty(symbol) {
41875             var links = getSymbolLinks(symbol);
41876             if (!links.type) {
41877                 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
41878                 // For a contextually typed parameter it is possible that a type has already
41879                 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
41880                 // to preserve this type.
41881                 if (!links.type) {
41882                     links.type = type;
41883                 }
41884             }
41885             return links.type;
41886         }
41887         function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
41888             // Handle prototype property
41889             if (symbol.flags & 4194304 /* Prototype */) {
41890                 return getTypeOfPrototypeProperty(symbol);
41891             }
41892             // CommonsJS require and module both have type any.
41893             if (symbol === requireSymbol) {
41894                 return anyType;
41895             }
41896             if (symbol.flags & 134217728 /* ModuleExports */) {
41897                 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
41898                 var members = ts.createSymbolTable();
41899                 members.set("exports", fileSymbol);
41900                 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
41901             }
41902             // Handle catch clause variables
41903             var declaration = symbol.valueDeclaration;
41904             if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
41905                 return anyType;
41906             }
41907             // Handle export default expressions
41908             if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
41909                 if (!declaration.statements.length) {
41910                     return emptyObjectType;
41911                 }
41912                 return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
41913             }
41914             // Handle variable, parameter or property
41915             if (!pushTypeResolution(symbol, 0 /* Type */)) {
41916                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41917                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
41918                     return getTypeOfFuncClassEnumModule(symbol);
41919                 }
41920                 return reportCircularityError(symbol);
41921             }
41922             var type;
41923             if (declaration.kind === 259 /* ExportAssignment */) {
41924                 type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
41925             }
41926             else if (ts.isBinaryExpression(declaration) ||
41927                 (ts.isInJSFile(declaration) &&
41928                     (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
41929                 type = getWidenedTypeForAssignmentDeclaration(symbol);
41930             }
41931             else if (ts.isJSDocPropertyLikeTag(declaration)
41932                 || ts.isPropertyAccessExpression(declaration)
41933                 || ts.isElementAccessExpression(declaration)
41934                 || ts.isIdentifier(declaration)
41935                 || ts.isStringLiteralLike(declaration)
41936                 || ts.isNumericLiteral(declaration)
41937                 || ts.isClassDeclaration(declaration)
41938                 || ts.isFunctionDeclaration(declaration)
41939                 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
41940                 || ts.isMethodSignature(declaration)
41941                 || ts.isSourceFile(declaration)) {
41942                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41943                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
41944                     return getTypeOfFuncClassEnumModule(symbol);
41945                 }
41946                 type = ts.isBinaryExpression(declaration.parent) ?
41947                     getWidenedTypeForAssignmentDeclaration(symbol) :
41948                     tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
41949             }
41950             else if (ts.isPropertyAssignment(declaration)) {
41951                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
41952             }
41953             else if (ts.isJsxAttribute(declaration)) {
41954                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
41955             }
41956             else if (ts.isShorthandPropertyAssignment(declaration)) {
41957                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
41958             }
41959             else if (ts.isObjectLiteralMethod(declaration)) {
41960                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
41961             }
41962             else if (ts.isParameter(declaration)
41963                 || ts.isPropertyDeclaration(declaration)
41964                 || ts.isPropertySignature(declaration)
41965                 || ts.isVariableDeclaration(declaration)
41966                 || ts.isBindingElement(declaration)) {
41967                 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
41968             }
41969             // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
41970             // Re-dispatch based on valueDeclaration.kind instead.
41971             else if (ts.isEnumDeclaration(declaration)) {
41972                 type = getTypeOfFuncClassEnumModule(symbol);
41973             }
41974             else if (ts.isEnumMember(declaration)) {
41975                 type = getTypeOfEnumMember(symbol);
41976             }
41977             else if (ts.isAccessor(declaration)) {
41978                 type = resolveTypeOfAccessors(symbol);
41979             }
41980             else {
41981                 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
41982             }
41983             if (!popTypeResolution()) {
41984                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41985                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
41986                     return getTypeOfFuncClassEnumModule(symbol);
41987                 }
41988                 return reportCircularityError(symbol);
41989             }
41990             return type;
41991         }
41992         function getAnnotatedAccessorTypeNode(accessor) {
41993             if (accessor) {
41994                 if (accessor.kind === 163 /* GetAccessor */) {
41995                     var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
41996                     return getterTypeAnnotation;
41997                 }
41998                 else {
41999                     var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
42000                     return setterTypeAnnotation;
42001                 }
42002             }
42003             return undefined;
42004         }
42005         function getAnnotatedAccessorType(accessor) {
42006             var node = getAnnotatedAccessorTypeNode(accessor);
42007             return node && getTypeFromTypeNode(node);
42008         }
42009         function getAnnotatedAccessorThisParameter(accessor) {
42010             var parameter = getAccessorThisParameter(accessor);
42011             return parameter && parameter.symbol;
42012         }
42013         function getThisTypeOfDeclaration(declaration) {
42014             return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
42015         }
42016         function getTypeOfAccessors(symbol) {
42017             var links = getSymbolLinks(symbol);
42018             return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
42019         }
42020         function getTypeOfAccessorsWorker(symbol) {
42021             if (!pushTypeResolution(symbol, 0 /* Type */)) {
42022                 return errorType;
42023             }
42024             var type = resolveTypeOfAccessors(symbol);
42025             if (!popTypeResolution()) {
42026                 type = anyType;
42027                 if (noImplicitAny) {
42028                     var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42029                     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));
42030                 }
42031             }
42032             return type;
42033         }
42034         function resolveTypeOfAccessors(symbol) {
42035             var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42036             var setter = ts.getDeclarationOfKind(symbol, 164 /* SetAccessor */);
42037             if (getter && ts.isInJSFile(getter)) {
42038                 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
42039                 if (jsDocType) {
42040                     return jsDocType;
42041                 }
42042             }
42043             // First try to see if the user specified a return type on the get-accessor.
42044             var getterReturnType = getAnnotatedAccessorType(getter);
42045             if (getterReturnType) {
42046                 return getterReturnType;
42047             }
42048             else {
42049                 // If the user didn't specify a return type, try to use the set-accessor's parameter type.
42050                 var setterParameterType = getAnnotatedAccessorType(setter);
42051                 if (setterParameterType) {
42052                     return setterParameterType;
42053                 }
42054                 else {
42055                     // If there are no specified types, try to infer it from the body of the get accessor if it exists.
42056                     if (getter && getter.body) {
42057                         return getReturnTypeFromBody(getter);
42058                     }
42059                     // Otherwise, fall back to 'any'.
42060                     else {
42061                         if (setter) {
42062                             if (!isPrivateWithinAmbient(setter)) {
42063                                 errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
42064                             }
42065                         }
42066                         else {
42067                             ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
42068                             if (!isPrivateWithinAmbient(getter)) {
42069                                 errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
42070                             }
42071                         }
42072                         return anyType;
42073                     }
42074                 }
42075             }
42076         }
42077         function getBaseTypeVariableOfClass(symbol) {
42078             var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
42079             return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
42080                 baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
42081                     undefined;
42082         }
42083         function getTypeOfFuncClassEnumModule(symbol) {
42084             var links = getSymbolLinks(symbol);
42085             var originalLinks = links;
42086             if (!links.type) {
42087                 var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration);
42088                 if (jsDeclaration) {
42089                     var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration));
42090                     if (merged) {
42091                         // note:we overwrite links because we just cloned the symbol
42092                         symbol = links = merged;
42093                     }
42094                 }
42095                 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
42096             }
42097             return links.type;
42098         }
42099         function getTypeOfFuncClassEnumModuleWorker(symbol) {
42100             var declaration = symbol.valueDeclaration;
42101             if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
42102                 return anyType;
42103             }
42104             else if (declaration && (declaration.kind === 209 /* BinaryExpression */ ||
42105                 ts.isAccessExpression(declaration) &&
42106                     declaration.parent.kind === 209 /* BinaryExpression */)) {
42107                 return getWidenedTypeForAssignmentDeclaration(symbol);
42108             }
42109             else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
42110                 var resolvedModule = resolveExternalModuleSymbol(symbol);
42111                 if (resolvedModule !== symbol) {
42112                     if (!pushTypeResolution(symbol, 0 /* Type */)) {
42113                         return errorType;
42114                     }
42115                     var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
42116                     var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
42117                     if (!popTypeResolution()) {
42118                         return reportCircularityError(symbol);
42119                     }
42120                     return type_1;
42121                 }
42122             }
42123             var type = createObjectType(16 /* Anonymous */, symbol);
42124             if (symbol.flags & 32 /* Class */) {
42125                 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
42126                 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
42127             }
42128             else {
42129                 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
42130             }
42131         }
42132         function getTypeOfEnumMember(symbol) {
42133             var links = getSymbolLinks(symbol);
42134             return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
42135         }
42136         function getTypeOfAlias(symbol) {
42137             var links = getSymbolLinks(symbol);
42138             if (!links.type) {
42139                 var targetSymbol = resolveAlias(symbol);
42140                 // It only makes sense to get the type of a value symbol. If the result of resolving
42141                 // the alias is not a value, then it has no type. To get the type associated with a
42142                 // type symbol, call getDeclaredTypeOfSymbol.
42143                 // This check is important because without it, a call to getTypeOfSymbol could end
42144                 // up recursively calling getTypeOfAlias, causing a stack overflow.
42145                 links.type = targetSymbol.flags & 111551 /* Value */
42146                     ? getTypeOfSymbol(targetSymbol)
42147                     : errorType;
42148             }
42149             return links.type;
42150         }
42151         function getTypeOfInstantiatedSymbol(symbol) {
42152             var links = getSymbolLinks(symbol);
42153             if (!links.type) {
42154                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
42155                     return links.type = errorType;
42156                 }
42157                 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
42158                 if (!popTypeResolution()) {
42159                     type = reportCircularityError(symbol);
42160                 }
42161                 links.type = type;
42162             }
42163             return links.type;
42164         }
42165         function reportCircularityError(symbol) {
42166             var declaration = symbol.valueDeclaration;
42167             // Check if variable has type annotation that circularly references the variable itself
42168             if (ts.getEffectiveTypeAnnotationNode(declaration)) {
42169                 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
42170                 return errorType;
42171             }
42172             // Check if variable has initializer that circularly references the variable itself
42173             if (noImplicitAny && (declaration.kind !== 156 /* Parameter */ || declaration.initializer)) {
42174                 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));
42175             }
42176             // Circularities could also result from parameters in function expressions that end up
42177             // having themselves as contextual types following type argument inference. In those cases
42178             // we have already reported an implicit any error so we don't report anything here.
42179             return anyType;
42180         }
42181         function getTypeOfSymbolWithDeferredType(symbol) {
42182             var links = getSymbolLinks(symbol);
42183             if (!links.type) {
42184                 ts.Debug.assertIsDefined(links.deferralParent);
42185                 ts.Debug.assertIsDefined(links.deferralConstituents);
42186                 links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
42187             }
42188             return links.type;
42189         }
42190         function getTypeOfSymbol(symbol) {
42191             var checkFlags = ts.getCheckFlags(symbol);
42192             if (checkFlags & 65536 /* DeferredType */) {
42193                 return getTypeOfSymbolWithDeferredType(symbol);
42194             }
42195             if (checkFlags & 1 /* Instantiated */) {
42196                 return getTypeOfInstantiatedSymbol(symbol);
42197             }
42198             if (checkFlags & 262144 /* Mapped */) {
42199                 return getTypeOfMappedSymbol(symbol);
42200             }
42201             if (checkFlags & 8192 /* ReverseMapped */) {
42202                 return getTypeOfReverseMappedSymbol(symbol);
42203             }
42204             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
42205                 return getTypeOfVariableOrParameterOrProperty(symbol);
42206             }
42207             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
42208                 return getTypeOfFuncClassEnumModule(symbol);
42209             }
42210             if (symbol.flags & 8 /* EnumMember */) {
42211                 return getTypeOfEnumMember(symbol);
42212             }
42213             if (symbol.flags & 98304 /* Accessor */) {
42214                 return getTypeOfAccessors(symbol);
42215             }
42216             if (symbol.flags & 2097152 /* Alias */) {
42217                 return getTypeOfAlias(symbol);
42218             }
42219             return errorType;
42220         }
42221         function isReferenceToType(type, target) {
42222             return type !== undefined
42223                 && target !== undefined
42224                 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
42225                 && type.target === target;
42226         }
42227         function getTargetType(type) {
42228             return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
42229         }
42230         // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
42231         function hasBaseType(type, checkBase) {
42232             return check(type);
42233             function check(type) {
42234                 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
42235                     var target = getTargetType(type);
42236                     return target === checkBase || ts.some(getBaseTypes(target), check);
42237                 }
42238                 else if (type.flags & 2097152 /* Intersection */) {
42239                     return ts.some(type.types, check);
42240                 }
42241                 return false;
42242             }
42243         }
42244         // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
42245         // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
42246         // in-place and returns the same array.
42247         function appendTypeParameters(typeParameters, declarations) {
42248             for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
42249                 var declaration = declarations_2[_i];
42250                 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
42251             }
42252             return typeParameters;
42253         }
42254         // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
42255         function getOuterTypeParameters(node, includeThisTypes) {
42256             while (true) {
42257                 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
42258                 if (node && ts.isBinaryExpression(node)) {
42259                     // prototype assignments get the outer type parameters of their constructor function
42260                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
42261                     if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
42262                         var symbol = getSymbolOfNode(node.left);
42263                         if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
42264                             node = symbol.parent.valueDeclaration;
42265                         }
42266                     }
42267                 }
42268                 if (!node) {
42269                     return undefined;
42270                 }
42271                 switch (node.kind) {
42272                     case 225 /* VariableStatement */:
42273                     case 245 /* ClassDeclaration */:
42274                     case 214 /* ClassExpression */:
42275                     case 246 /* InterfaceDeclaration */:
42276                     case 165 /* CallSignature */:
42277                     case 166 /* ConstructSignature */:
42278                     case 160 /* MethodSignature */:
42279                     case 170 /* FunctionType */:
42280                     case 171 /* ConstructorType */:
42281                     case 300 /* JSDocFunctionType */:
42282                     case 244 /* FunctionDeclaration */:
42283                     case 161 /* MethodDeclaration */:
42284                     case 201 /* FunctionExpression */:
42285                     case 202 /* ArrowFunction */:
42286                     case 247 /* TypeAliasDeclaration */:
42287                     case 321 /* JSDocTemplateTag */:
42288                     case 322 /* JSDocTypedefTag */:
42289                     case 316 /* JSDocEnumTag */:
42290                     case 315 /* JSDocCallbackTag */:
42291                     case 186 /* MappedType */:
42292                     case 180 /* ConditionalType */:
42293                         var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
42294                         if (node.kind === 186 /* MappedType */) {
42295                             return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
42296                         }
42297                         else if (node.kind === 180 /* ConditionalType */) {
42298                             return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
42299                         }
42300                         else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) {
42301                             break;
42302                         }
42303                         var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
42304                         var thisType = includeThisTypes &&
42305                             (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
42306                             getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
42307                         return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
42308                 }
42309             }
42310         }
42311         // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
42312         function getOuterTypeParametersOfClassOrInterface(symbol) {
42313             var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
42314             ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
42315             return getOuterTypeParameters(declaration);
42316         }
42317         // The local type parameters are the combined set of type parameters from all declarations of the class,
42318         // interface, or type alias.
42319         function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
42320             var result;
42321             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42322                 var node = _a[_i];
42323                 if (node.kind === 246 /* InterfaceDeclaration */ ||
42324                     node.kind === 245 /* ClassDeclaration */ ||
42325                     node.kind === 214 /* ClassExpression */ ||
42326                     isJSConstructor(node) ||
42327                     ts.isTypeAlias(node)) {
42328                     var declaration = node;
42329                     result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
42330                 }
42331             }
42332             return result;
42333         }
42334         // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
42335         // its locally declared type parameters.
42336         function getTypeParametersOfClassOrInterface(symbol) {
42337             return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
42338         }
42339         // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
42340         // rest parameter of type any[].
42341         function isMixinConstructorType(type) {
42342             var signatures = getSignaturesOfType(type, 1 /* Construct */);
42343             if (signatures.length === 1) {
42344                 var s = signatures[0];
42345                 return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType;
42346             }
42347             return false;
42348         }
42349         function isConstructorType(type) {
42350             if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
42351                 return true;
42352             }
42353             if (type.flags & 8650752 /* TypeVariable */) {
42354                 var constraint = getBaseConstraintOfType(type);
42355                 return !!constraint && isMixinConstructorType(constraint);
42356             }
42357             return false;
42358         }
42359         function getBaseTypeNodeOfClass(type) {
42360             return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
42361         }
42362         function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42363             var typeArgCount = ts.length(typeArgumentNodes);
42364             var isJavascript = ts.isInJSFile(location);
42365             return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
42366         }
42367         function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42368             var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
42369             var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
42370             return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
42371         }
42372         /**
42373          * The base constructor of a class can resolve to
42374          * * undefinedType if the class has no extends clause,
42375          * * unknownType if an error occurred during resolution of the extends expression,
42376          * * nullType if the extends expression is the null value,
42377          * * anyType if the extends expression has type any, or
42378          * * an object type with at least one construct signature.
42379          */
42380         function getBaseConstructorTypeOfClass(type) {
42381             if (!type.resolvedBaseConstructorType) {
42382                 var decl = type.symbol.valueDeclaration;
42383                 var extended = ts.getEffectiveBaseTypeNode(decl);
42384                 var baseTypeNode = getBaseTypeNodeOfClass(type);
42385                 if (!baseTypeNode) {
42386                     return type.resolvedBaseConstructorType = undefinedType;
42387                 }
42388                 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
42389                     return errorType;
42390                 }
42391                 var baseConstructorType = checkExpression(baseTypeNode.expression);
42392                 if (extended && baseTypeNode !== extended) {
42393                     ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
42394                     checkExpression(extended.expression);
42395                 }
42396                 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
42397                     // Resolving the members of a class requires us to resolve the base class of that class.
42398                     // We force resolution here such that we catch circularities now.
42399                     resolveStructuredTypeMembers(baseConstructorType);
42400                 }
42401                 if (!popTypeResolution()) {
42402                     error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
42403                     return type.resolvedBaseConstructorType = errorType;
42404                 }
42405                 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
42406                     var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
42407                     if (baseConstructorType.flags & 262144 /* TypeParameter */) {
42408                         var constraint = getConstraintFromTypeParameter(baseConstructorType);
42409                         var ctorReturn = unknownType;
42410                         if (constraint) {
42411                             var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
42412                             if (ctorSig[0]) {
42413                                 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
42414                             }
42415                         }
42416                         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)));
42417                     }
42418                     return type.resolvedBaseConstructorType = errorType;
42419                 }
42420                 type.resolvedBaseConstructorType = baseConstructorType;
42421             }
42422             return type.resolvedBaseConstructorType;
42423         }
42424         function getImplementsTypes(type) {
42425             var resolvedImplementsTypes = ts.emptyArray;
42426             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42427                 var declaration = _a[_i];
42428                 var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration);
42429                 if (!implementsTypeNodes)
42430                     continue;
42431                 for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) {
42432                     var node = implementsTypeNodes_1[_b];
42433                     var implementsType = getTypeFromTypeNode(node);
42434                     if (implementsType !== errorType) {
42435                         if (resolvedImplementsTypes === ts.emptyArray) {
42436                             resolvedImplementsTypes = [implementsType];
42437                         }
42438                         else {
42439                             resolvedImplementsTypes.push(implementsType);
42440                         }
42441                     }
42442                 }
42443             }
42444             return resolvedImplementsTypes;
42445         }
42446         function getBaseTypes(type) {
42447             if (!type.resolvedBaseTypes) {
42448                 if (type.objectFlags & 8 /* Tuple */) {
42449                     type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
42450                 }
42451                 else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42452                     if (type.symbol.flags & 32 /* Class */) {
42453                         resolveBaseTypesOfClass(type);
42454                     }
42455                     if (type.symbol.flags & 64 /* Interface */) {
42456                         resolveBaseTypesOfInterface(type);
42457                     }
42458                 }
42459                 else {
42460                     ts.Debug.fail("type must be class or interface");
42461                 }
42462             }
42463             return type.resolvedBaseTypes;
42464         }
42465         function resolveBaseTypesOfClass(type) {
42466             type.resolvedBaseTypes = ts.resolvingEmptyArray;
42467             var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
42468             if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
42469                 return type.resolvedBaseTypes = ts.emptyArray;
42470             }
42471             var baseTypeNode = getBaseTypeNodeOfClass(type);
42472             var baseType;
42473             var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
42474             if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
42475                 areAllOuterTypeParametersApplied(originalBaseType)) {
42476                 // 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
42477                 // class and all return the instance type of the class. There is no need for further checks and we can apply the
42478                 // type arguments in the same manner as a type reference to get the same error reporting experience.
42479                 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
42480             }
42481             else if (baseConstructorType.flags & 1 /* Any */) {
42482                 baseType = baseConstructorType;
42483             }
42484             else {
42485                 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
42486                 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
42487                 // we check that all instantiated signatures return the same type.
42488                 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
42489                 if (!constructors.length) {
42490                     error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
42491                     return type.resolvedBaseTypes = ts.emptyArray;
42492                 }
42493                 baseType = getReturnTypeOfSignature(constructors[0]);
42494             }
42495             if (baseType === errorType) {
42496                 return type.resolvedBaseTypes = ts.emptyArray;
42497             }
42498             var reducedBaseType = getReducedType(baseType);
42499             if (!isValidBaseType(reducedBaseType)) {
42500                 var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType);
42501                 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));
42502                 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic));
42503                 return type.resolvedBaseTypes = ts.emptyArray;
42504             }
42505             if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
42506                 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42507                 return type.resolvedBaseTypes = ts.emptyArray;
42508             }
42509             if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
42510                 // Circular reference, likely through instantiation of default parameters
42511                 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
42512                 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
42513                 // partial instantiation of the members without the base types fully resolved
42514                 type.members = undefined;
42515             }
42516             return type.resolvedBaseTypes = [reducedBaseType];
42517         }
42518         function areAllOuterTypeParametersApplied(type) {
42519             // An unapplied type parameter has its symbol still the same as the matching argument symbol.
42520             // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
42521             var outerTypeParameters = type.outerTypeParameters;
42522             if (outerTypeParameters) {
42523                 var last_1 = outerTypeParameters.length - 1;
42524                 var typeArguments = getTypeArguments(type);
42525                 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
42526             }
42527             return true;
42528         }
42529         // A valid base type is `any`, an object type or intersection of object types.
42530         function isValidBaseType(type) {
42531             if (type.flags & 262144 /* TypeParameter */) {
42532                 var constraint = getBaseConstraintOfType(type);
42533                 if (constraint) {
42534                     return isValidBaseType(constraint);
42535                 }
42536             }
42537             // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
42538             // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
42539             return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
42540                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType));
42541         }
42542         function resolveBaseTypesOfInterface(type) {
42543             type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
42544             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42545                 var declaration = _a[_i];
42546                 if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
42547                     for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
42548                         var node = _c[_b];
42549                         var baseType = getReducedType(getTypeFromTypeNode(node));
42550                         if (baseType !== errorType) {
42551                             if (isValidBaseType(baseType)) {
42552                                 if (type !== baseType && !hasBaseType(baseType, type)) {
42553                                     if (type.resolvedBaseTypes === ts.emptyArray) {
42554                                         type.resolvedBaseTypes = [baseType];
42555                                     }
42556                                     else {
42557                                         type.resolvedBaseTypes.push(baseType);
42558                                     }
42559                                 }
42560                                 else {
42561                                     error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42562                                 }
42563                             }
42564                             else {
42565                                 error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
42566                             }
42567                         }
42568                     }
42569                 }
42570             }
42571         }
42572         /**
42573          * Returns true if the interface given by the symbol is free of "this" references.
42574          *
42575          * Specifically, the result is true if the interface itself contains no references
42576          * to "this" in its body, if all base types are interfaces,
42577          * and if none of the base interfaces have a "this" type.
42578          */
42579         function isThislessInterface(symbol) {
42580             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42581                 var declaration = _a[_i];
42582                 if (declaration.kind === 246 /* InterfaceDeclaration */) {
42583                     if (declaration.flags & 128 /* ContainsThis */) {
42584                         return false;
42585                     }
42586                     var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
42587                     if (baseTypeNodes) {
42588                         for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
42589                             var node = baseTypeNodes_1[_b];
42590                             if (ts.isEntityNameExpression(node.expression)) {
42591                                 var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
42592                                 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
42593                                     return false;
42594                                 }
42595                             }
42596                         }
42597                     }
42598                 }
42599             }
42600             return true;
42601         }
42602         function getDeclaredTypeOfClassOrInterface(symbol) {
42603             var links = getSymbolLinks(symbol);
42604             var originalLinks = links;
42605             if (!links.declaredType) {
42606                 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
42607                 var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration));
42608                 if (merged) {
42609                     // note:we overwrite links because we just cloned the symbol
42610                     symbol = links = merged;
42611                 }
42612                 var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
42613                 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
42614                 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42615                 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
42616                 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
42617                 // property types inferred from initializers and method return types inferred from return statements are very hard
42618                 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
42619                 // "this" references.
42620                 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
42621                     type.objectFlags |= 4 /* Reference */;
42622                     type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
42623                     type.outerTypeParameters = outerTypeParameters;
42624                     type.localTypeParameters = localTypeParameters;
42625                     type.instantiations = ts.createMap();
42626                     type.instantiations.set(getTypeListId(type.typeParameters), type);
42627                     type.target = type;
42628                     type.resolvedTypeArguments = type.typeParameters;
42629                     type.thisType = createTypeParameter(symbol);
42630                     type.thisType.isThisType = true;
42631                     type.thisType.constraint = type;
42632                 }
42633             }
42634             return links.declaredType;
42635         }
42636         function getDeclaredTypeOfTypeAlias(symbol) {
42637             var links = getSymbolLinks(symbol);
42638             if (!links.declaredType) {
42639                 // Note that we use the links object as the target here because the symbol object is used as the unique
42640                 // identity for resolution of the 'type' property in SymbolLinks.
42641                 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
42642                     return errorType;
42643                 }
42644                 var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found");
42645                 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
42646                 // If typeNode is missing, we will error in checkJSDocTypedefTag.
42647                 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
42648                 if (popTypeResolution()) {
42649                     var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42650                     if (typeParameters) {
42651                         // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
42652                         // an instantiation of the type alias with the type parameters supplied as type arguments.
42653                         links.typeParameters = typeParameters;
42654                         links.instantiations = ts.createMap();
42655                         links.instantiations.set(getTypeListId(typeParameters), type);
42656                     }
42657                 }
42658                 else {
42659                     type = errorType;
42660                     error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
42661                 }
42662                 links.declaredType = type;
42663             }
42664             return links.declaredType;
42665         }
42666         function isStringConcatExpression(expr) {
42667             if (ts.isStringLiteralLike(expr)) {
42668                 return true;
42669             }
42670             else if (expr.kind === 209 /* BinaryExpression */) {
42671                 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
42672             }
42673             return false;
42674         }
42675         function isLiteralEnumMember(member) {
42676             var expr = member.initializer;
42677             if (!expr) {
42678                 return !(member.flags & 8388608 /* Ambient */);
42679             }
42680             switch (expr.kind) {
42681                 case 10 /* StringLiteral */:
42682                 case 8 /* NumericLiteral */:
42683                 case 14 /* NoSubstitutionTemplateLiteral */:
42684                     return true;
42685                 case 207 /* PrefixUnaryExpression */:
42686                     return expr.operator === 40 /* MinusToken */ &&
42687                         expr.operand.kind === 8 /* NumericLiteral */;
42688                 case 75 /* Identifier */:
42689                     return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
42690                 case 209 /* BinaryExpression */:
42691                     return isStringConcatExpression(expr);
42692                 default:
42693                     return false;
42694             }
42695         }
42696         function getEnumKind(symbol) {
42697             var links = getSymbolLinks(symbol);
42698             if (links.enumKind !== undefined) {
42699                 return links.enumKind;
42700             }
42701             var hasNonLiteralMember = false;
42702             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42703                 var declaration = _a[_i];
42704                 if (declaration.kind === 248 /* EnumDeclaration */) {
42705                     for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42706                         var member = _c[_b];
42707                         if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
42708                             return links.enumKind = 1 /* Literal */;
42709                         }
42710                         if (!isLiteralEnumMember(member)) {
42711                             hasNonLiteralMember = true;
42712                         }
42713                     }
42714                 }
42715             }
42716             return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
42717         }
42718         function getBaseTypeOfEnumLiteralType(type) {
42719             return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
42720         }
42721         function getDeclaredTypeOfEnum(symbol) {
42722             var links = getSymbolLinks(symbol);
42723             if (links.declaredType) {
42724                 return links.declaredType;
42725             }
42726             if (getEnumKind(symbol) === 1 /* Literal */) {
42727                 enumCount++;
42728                 var memberTypeList = [];
42729                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42730                     var declaration = _a[_i];
42731                     if (declaration.kind === 248 /* EnumDeclaration */) {
42732                         for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42733                             var member = _c[_b];
42734                             var value = getEnumMemberValue(member);
42735                             var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
42736                             getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
42737                             memberTypeList.push(getRegularTypeOfLiteralType(memberType));
42738                         }
42739                     }
42740                 }
42741                 if (memberTypeList.length) {
42742                     var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
42743                     if (enumType_1.flags & 1048576 /* Union */) {
42744                         enumType_1.flags |= 1024 /* EnumLiteral */;
42745                         enumType_1.symbol = symbol;
42746                     }
42747                     return links.declaredType = enumType_1;
42748                 }
42749             }
42750             var enumType = createType(32 /* Enum */);
42751             enumType.symbol = symbol;
42752             return links.declaredType = enumType;
42753         }
42754         function getDeclaredTypeOfEnumMember(symbol) {
42755             var links = getSymbolLinks(symbol);
42756             if (!links.declaredType) {
42757                 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
42758                 if (!links.declaredType) {
42759                     links.declaredType = enumType;
42760                 }
42761             }
42762             return links.declaredType;
42763         }
42764         function getDeclaredTypeOfTypeParameter(symbol) {
42765             var links = getSymbolLinks(symbol);
42766             return links.declaredType || (links.declaredType = createTypeParameter(symbol));
42767         }
42768         function getDeclaredTypeOfAlias(symbol) {
42769             var links = getSymbolLinks(symbol);
42770             return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
42771         }
42772         function getDeclaredTypeOfSymbol(symbol) {
42773             return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
42774         }
42775         function tryGetDeclaredTypeOfSymbol(symbol) {
42776             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42777                 return getDeclaredTypeOfClassOrInterface(symbol);
42778             }
42779             if (symbol.flags & 524288 /* TypeAlias */) {
42780                 return getDeclaredTypeOfTypeAlias(symbol);
42781             }
42782             if (symbol.flags & 262144 /* TypeParameter */) {
42783                 return getDeclaredTypeOfTypeParameter(symbol);
42784             }
42785             if (symbol.flags & 384 /* Enum */) {
42786                 return getDeclaredTypeOfEnum(symbol);
42787             }
42788             if (symbol.flags & 8 /* EnumMember */) {
42789                 return getDeclaredTypeOfEnumMember(symbol);
42790             }
42791             if (symbol.flags & 2097152 /* Alias */) {
42792                 return getDeclaredTypeOfAlias(symbol);
42793             }
42794             return undefined;
42795         }
42796         /**
42797          * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
42798          * literal type, an array with an element type that is free of this references, or a type reference that is
42799          * free of this references.
42800          */
42801         function isThislessType(node) {
42802             switch (node.kind) {
42803                 case 125 /* AnyKeyword */:
42804                 case 148 /* UnknownKeyword */:
42805                 case 143 /* StringKeyword */:
42806                 case 140 /* NumberKeyword */:
42807                 case 151 /* BigIntKeyword */:
42808                 case 128 /* BooleanKeyword */:
42809                 case 144 /* SymbolKeyword */:
42810                 case 141 /* ObjectKeyword */:
42811                 case 110 /* VoidKeyword */:
42812                 case 146 /* UndefinedKeyword */:
42813                 case 100 /* NullKeyword */:
42814                 case 137 /* NeverKeyword */:
42815                 case 187 /* LiteralType */:
42816                     return true;
42817                 case 174 /* ArrayType */:
42818                     return isThislessType(node.elementType);
42819                 case 169 /* TypeReference */:
42820                     return !node.typeArguments || node.typeArguments.every(isThislessType);
42821             }
42822             return false;
42823         }
42824         /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
42825         function isThislessTypeParameter(node) {
42826             var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
42827             return !constraint || isThislessType(constraint);
42828         }
42829         /**
42830          * A variable-like declaration is free of this references if it has a type annotation
42831          * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
42832          */
42833         function isThislessVariableLikeDeclaration(node) {
42834             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
42835             return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
42836         }
42837         /**
42838          * A function-like declaration is considered free of `this` references if it has a return type
42839          * annotation that is free of this references and if each parameter is thisless and if
42840          * each type parameter (if present) is thisless.
42841          */
42842         function isThislessFunctionLikeDeclaration(node) {
42843             var returnType = ts.getEffectiveReturnTypeNode(node);
42844             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
42845             return (node.kind === 162 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
42846                 node.parameters.every(isThislessVariableLikeDeclaration) &&
42847                 typeParameters.every(isThislessTypeParameter);
42848         }
42849         /**
42850          * Returns true if the class or interface member given by the symbol is free of "this" references. The
42851          * function may return false for symbols that are actually free of "this" references because it is not
42852          * feasible to perform a complete analysis in all cases. In particular, property members with types
42853          * inferred from their initializers and function members with inferred return types are conservatively
42854          * assumed not to be free of "this" references.
42855          */
42856         function isThisless(symbol) {
42857             if (symbol.declarations && symbol.declarations.length === 1) {
42858                 var declaration = symbol.declarations[0];
42859                 if (declaration) {
42860                     switch (declaration.kind) {
42861                         case 159 /* PropertyDeclaration */:
42862                         case 158 /* PropertySignature */:
42863                             return isThislessVariableLikeDeclaration(declaration);
42864                         case 161 /* MethodDeclaration */:
42865                         case 160 /* MethodSignature */:
42866                         case 162 /* Constructor */:
42867                         case 163 /* GetAccessor */:
42868                         case 164 /* SetAccessor */:
42869                             return isThislessFunctionLikeDeclaration(declaration);
42870                     }
42871                 }
42872             }
42873             return false;
42874         }
42875         // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
42876         // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
42877         function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
42878             var result = ts.createSymbolTable();
42879             for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
42880                 var symbol = symbols_2[_i];
42881                 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
42882             }
42883             return result;
42884         }
42885         function addInheritedMembers(symbols, baseSymbols) {
42886             for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
42887                 var s = baseSymbols_1[_i];
42888                 if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
42889                     symbols.set(s.escapedName, s);
42890                 }
42891             }
42892         }
42893         function isStaticPrivateIdentifierProperty(s) {
42894             return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasModifier(s.valueDeclaration, 32 /* Static */);
42895         }
42896         function resolveDeclaredMembers(type) {
42897             if (!type.declaredProperties) {
42898                 var symbol = type.symbol;
42899                 var members = getMembersOfSymbol(symbol);
42900                 type.declaredProperties = getNamedMembers(members);
42901                 // Start with signatures at empty array in case of recursive types
42902                 type.declaredCallSignatures = ts.emptyArray;
42903                 type.declaredConstructSignatures = ts.emptyArray;
42904                 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
42905                 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
42906                 type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
42907                 type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
42908             }
42909             return type;
42910         }
42911         /**
42912          * Indicates whether a type can be used as a property name.
42913          */
42914         function isTypeUsableAsPropertyName(type) {
42915             return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
42916         }
42917         /**
42918          * Indicates whether a declaration name is definitely late-bindable.
42919          * A declaration name is only late-bindable if:
42920          * - It is a `ComputedPropertyName`.
42921          * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
42922          * `ElementAccessExpression` consisting only of these same three types of nodes.
42923          * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
42924          */
42925         function isLateBindableName(node) {
42926             if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
42927                 return false;
42928             }
42929             var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
42930             return ts.isEntityNameExpression(expr)
42931                 && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
42932         }
42933         function isLateBoundName(name) {
42934             return name.charCodeAt(0) === 95 /* _ */ &&
42935                 name.charCodeAt(1) === 95 /* _ */ &&
42936                 name.charCodeAt(2) === 64 /* at */;
42937         }
42938         /**
42939          * Indicates whether a declaration has a late-bindable dynamic name.
42940          */
42941         function hasLateBindableName(node) {
42942             var name = ts.getNameOfDeclaration(node);
42943             return !!name && isLateBindableName(name);
42944         }
42945         /**
42946          * Indicates whether a declaration has a dynamic name that cannot be late-bound.
42947          */
42948         function hasNonBindableDynamicName(node) {
42949             return ts.hasDynamicName(node) && !hasLateBindableName(node);
42950         }
42951         /**
42952          * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
42953          */
42954         function isNonBindableDynamicName(node) {
42955             return ts.isDynamicName(node) && !isLateBindableName(node);
42956         }
42957         /**
42958          * Gets the symbolic name for a member from its type.
42959          */
42960         function getPropertyNameFromType(type) {
42961             if (type.flags & 8192 /* UniqueESSymbol */) {
42962                 return type.escapedName;
42963             }
42964             if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
42965                 return ts.escapeLeadingUnderscores("" + type.value);
42966             }
42967             return ts.Debug.fail();
42968         }
42969         /**
42970          * Adds a declaration to a late-bound dynamic member. This performs the same function for
42971          * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
42972          * members.
42973          */
42974         function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
42975             ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
42976             symbol.flags |= symbolFlags;
42977             getSymbolLinks(member.symbol).lateSymbol = symbol;
42978             if (!symbol.declarations) {
42979                 symbol.declarations = [member];
42980             }
42981             else {
42982                 symbol.declarations.push(member);
42983             }
42984             if (symbolFlags & 111551 /* Value */) {
42985                 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
42986                     symbol.valueDeclaration = member;
42987                 }
42988             }
42989         }
42990         /**
42991          * Performs late-binding of a dynamic member. This performs the same function for
42992          * late-bound members that `declareSymbol` in binder.ts performs for early-bound
42993          * members.
42994          *
42995          * If a symbol is a dynamic name from a computed property, we perform an additional "late"
42996          * binding phase to attempt to resolve the name for the symbol from the type of the computed
42997          * property's expression. If the type of the expression is a string-literal, numeric-literal,
42998          * or unique symbol type, we can use that type as the name of the symbol.
42999          *
43000          * For example, given:
43001          *
43002          *   const x = Symbol();
43003          *
43004          *   interface I {
43005          *     [x]: number;
43006          *   }
43007          *
43008          * The binder gives the property `[x]: number` a special symbol with the name "__computed".
43009          * In the late-binding phase we can type-check the expression `x` and see that it has a
43010          * unique symbol type which we can then use as the name of the member. This allows users
43011          * to define custom symbols that can be used in the members of an object type.
43012          *
43013          * @param parent The containing symbol for the member.
43014          * @param earlySymbols The early-bound symbols of the parent.
43015          * @param lateSymbols The late-bound symbols of the parent.
43016          * @param decl The member to bind.
43017          */
43018         function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
43019             ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
43020             var links = getNodeLinks(decl);
43021             if (!links.resolvedSymbol) {
43022                 // In the event we attempt to resolve the late-bound name of this member recursively,
43023                 // fall back to the early-bound name of this member.
43024                 links.resolvedSymbol = decl.symbol;
43025                 var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
43026                 var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
43027                 if (isTypeUsableAsPropertyName(type)) {
43028                     var memberName = getPropertyNameFromType(type);
43029                     var symbolFlags = decl.symbol.flags;
43030                     // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
43031                     var lateSymbol = lateSymbols.get(memberName);
43032                     if (!lateSymbol)
43033                         lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
43034                     // Report an error if a late-bound member has the same name as an early-bound member,
43035                     // or if we have another early-bound symbol declaration with the same name and
43036                     // conflicting flags.
43037                     var earlySymbol = earlySymbols && earlySymbols.get(memberName);
43038                     if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
43039                         // If we have an existing early-bound member, combine its declarations so that we can
43040                         // report an error at each declaration.
43041                         var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
43042                         var name_3 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
43043                         ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_3); });
43044                         error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_3);
43045                         lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
43046                     }
43047                     lateSymbol.nameType = type;
43048                     addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
43049                     if (lateSymbol.parent) {
43050                         ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
43051                     }
43052                     else {
43053                         lateSymbol.parent = parent;
43054                     }
43055                     return links.resolvedSymbol = lateSymbol;
43056                 }
43057             }
43058             return links.resolvedSymbol;
43059         }
43060         function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
43061             var links = getSymbolLinks(symbol);
43062             if (!links[resolutionKind]) {
43063                 var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
43064                 var earlySymbols = !isStatic ? symbol.members :
43065                     symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
43066                         symbol.exports;
43067                 // In the event we recursively resolve the members/exports of the symbol, we
43068                 // set the initial value of resolvedMembers/resolvedExports to the early-bound
43069                 // members/exports of the symbol.
43070                 links[resolutionKind] = earlySymbols || emptySymbols;
43071                 // fill in any as-yet-unresolved late-bound members.
43072                 var lateSymbols = ts.createSymbolTable();
43073                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
43074                     var decl = _a[_i];
43075                     var members = ts.getMembersOfDeclaration(decl);
43076                     if (members) {
43077                         for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
43078                             var member = members_5[_b];
43079                             if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
43080                                 lateBindMember(symbol, earlySymbols, lateSymbols, member);
43081                             }
43082                         }
43083                     }
43084                 }
43085                 var assignments = symbol.assignmentDeclarationMembers;
43086                 if (assignments) {
43087                     var decls = ts.arrayFrom(assignments.values());
43088                     for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
43089                         var member = decls_1[_c];
43090                         var assignmentKind = ts.getAssignmentDeclarationKind(member);
43091                         var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
43092                             || assignmentKind === 4 /* ThisProperty */
43093                             || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
43094                             || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
43095                         if (isStatic === !isInstanceMember && hasLateBindableName(member)) {
43096                             lateBindMember(symbol, earlySymbols, lateSymbols, member);
43097                         }
43098                     }
43099                 }
43100                 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
43101             }
43102             return links[resolutionKind];
43103         }
43104         /**
43105          * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
43106          *
43107          * For a description of late-binding, see `lateBindMember`.
43108          */
43109         function getMembersOfSymbol(symbol) {
43110             return symbol.flags & 6256 /* LateBindingContainer */
43111                 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
43112                 : symbol.members || emptySymbols;
43113         }
43114         /**
43115          * If a symbol is the dynamic name of the member of an object type, get the late-bound
43116          * symbol of the member.
43117          *
43118          * For a description of late-binding, see `lateBindMember`.
43119          */
43120         function getLateBoundSymbol(symbol) {
43121             if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
43122                 var links = getSymbolLinks(symbol);
43123                 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
43124                     // force late binding of members/exports. This will set the late-bound symbol
43125                     var parent = getMergedSymbol(symbol.parent);
43126                     if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
43127                         getExportsOfSymbol(parent);
43128                     }
43129                     else {
43130                         getMembersOfSymbol(parent);
43131                     }
43132                 }
43133                 return links.lateSymbol || (links.lateSymbol = symbol);
43134             }
43135             return symbol;
43136         }
43137         function getTypeWithThisArgument(type, thisArgument, needApparentType) {
43138             if (ts.getObjectFlags(type) & 4 /* Reference */) {
43139                 var target = type.target;
43140                 var typeArguments = getTypeArguments(type);
43141                 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
43142                     var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
43143                     return needApparentType ? getApparentType(ref) : ref;
43144                 }
43145             }
43146             else if (type.flags & 2097152 /* Intersection */) {
43147                 return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
43148             }
43149             return needApparentType ? getApparentType(type) : type;
43150         }
43151         function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
43152             var mapper;
43153             var members;
43154             var callSignatures;
43155             var constructSignatures;
43156             var stringIndexInfo;
43157             var numberIndexInfo;
43158             if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
43159                 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
43160                 callSignatures = source.declaredCallSignatures;
43161                 constructSignatures = source.declaredConstructSignatures;
43162                 stringIndexInfo = source.declaredStringIndexInfo;
43163                 numberIndexInfo = source.declaredNumberIndexInfo;
43164             }
43165             else {
43166                 mapper = createTypeMapper(typeParameters, typeArguments);
43167                 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
43168                 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
43169                 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
43170                 stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
43171                 numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
43172             }
43173             var baseTypes = getBaseTypes(source);
43174             if (baseTypes.length) {
43175                 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
43176                     members = ts.createSymbolTable(source.declaredProperties);
43177                 }
43178                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43179                 var thisArgument = ts.lastOrUndefined(typeArguments);
43180                 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
43181                     var baseType = baseTypes_1[_i];
43182                     var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
43183                     addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
43184                     callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
43185                     constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
43186                     if (!stringIndexInfo) {
43187                         stringIndexInfo = instantiatedBaseType === anyType ?
43188                             createIndexInfo(anyType, /*isReadonly*/ false) :
43189                             getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
43190                     }
43191                     numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
43192                 }
43193             }
43194             setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43195         }
43196         function resolveClassOrInterfaceMembers(type) {
43197             resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
43198         }
43199         function resolveTypeReferenceMembers(type) {
43200             var source = resolveDeclaredMembers(type.target);
43201             var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
43202             var typeArguments = getTypeArguments(type);
43203             var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
43204             resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
43205         }
43206         function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
43207             var sig = new Signature(checker, flags);
43208             sig.declaration = declaration;
43209             sig.typeParameters = typeParameters;
43210             sig.parameters = parameters;
43211             sig.thisParameter = thisParameter;
43212             sig.resolvedReturnType = resolvedReturnType;
43213             sig.resolvedTypePredicate = resolvedTypePredicate;
43214             sig.minArgumentCount = minArgumentCount;
43215             sig.target = undefined;
43216             sig.mapper = undefined;
43217             sig.unionSignatures = undefined;
43218             return sig;
43219         }
43220         function cloneSignature(sig) {
43221             var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, 
43222             /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */);
43223             result.target = sig.target;
43224             result.mapper = sig.mapper;
43225             result.unionSignatures = sig.unionSignatures;
43226             return result;
43227         }
43228         function createUnionSignature(signature, unionSignatures) {
43229             var result = cloneSignature(signature);
43230             result.unionSignatures = unionSignatures;
43231             result.target = undefined;
43232             result.mapper = undefined;
43233             return result;
43234         }
43235         function getOptionalCallSignature(signature, callChainFlags) {
43236             if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) {
43237                 return signature;
43238             }
43239             if (!signature.optionalCallSignatureCache) {
43240                 signature.optionalCallSignatureCache = {};
43241             }
43242             var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer";
43243             return signature.optionalCallSignatureCache[key]
43244                 || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
43245         }
43246         function createOptionalCallSignature(signature, callChainFlags) {
43247             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.");
43248             var result = cloneSignature(signature);
43249             result.flags |= callChainFlags;
43250             return result;
43251         }
43252         function getExpandedParameters(sig) {
43253             if (signatureHasRestParameter(sig)) {
43254                 var restIndex_1 = sig.parameters.length - 1;
43255                 var restParameter = sig.parameters[restIndex_1];
43256                 var restType = getTypeOfSymbol(restParameter);
43257                 if (isTupleType(restType)) {
43258                     var elementTypes = getTypeArguments(restType);
43259                     var minLength_1 = restType.target.minLength;
43260                     var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1;
43261                     var restParams = ts.map(elementTypes, function (t, i) {
43262                         var name = getParameterNameAtPosition(sig, restIndex_1 + i);
43263                         var checkFlags = i === tupleRestIndex_1 ? 32768 /* RestParameter */ :
43264                             i >= minLength_1 ? 16384 /* OptionalParameter */ : 0;
43265                         var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
43266                         symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t;
43267                         return symbol;
43268                     });
43269                     return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams);
43270                 }
43271             }
43272             return sig.parameters;
43273         }
43274         function getDefaultConstructSignatures(classType) {
43275             var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43276             var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
43277             if (baseSignatures.length === 0) {
43278                 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)];
43279             }
43280             var baseTypeNode = getBaseTypeNodeOfClass(classType);
43281             var isJavaScript = ts.isInJSFile(baseTypeNode);
43282             var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
43283             var typeArgCount = ts.length(typeArguments);
43284             var result = [];
43285             for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
43286                 var baseSig = baseSignatures_1[_i];
43287                 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
43288                 var typeParamCount = ts.length(baseSig.typeParameters);
43289                 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
43290                     var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
43291                     sig.typeParameters = classType.localTypeParameters;
43292                     sig.resolvedReturnType = classType;
43293                     result.push(sig);
43294                 }
43295             }
43296             return result;
43297         }
43298         function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
43299             for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
43300                 var s = signatureList_1[_i];
43301                 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
43302                     return s;
43303                 }
43304             }
43305         }
43306         function findMatchingSignatures(signatureLists, signature, listIndex) {
43307             if (signature.typeParameters) {
43308                 // We require an exact match for generic signatures, so we only return signatures from the first
43309                 // signature list and only if they have exact matches in the other signature lists.
43310                 if (listIndex > 0) {
43311                     return undefined;
43312                 }
43313                 for (var i = 1; i < signatureLists.length; i++) {
43314                     if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
43315                         return undefined;
43316                     }
43317                 }
43318                 return [signature];
43319             }
43320             var result;
43321             for (var i = 0; i < signatureLists.length; i++) {
43322                 // Allow matching non-generic signatures to have excess parameters and different return types.
43323                 // Prefer matching this types if possible.
43324                 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
43325                 if (!match) {
43326                     return undefined;
43327                 }
43328                 result = ts.appendIfUnique(result, match);
43329             }
43330             return result;
43331         }
43332         // The signatures of a union type are those signatures that are present in each of the constituent types.
43333         // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
43334         // parameters and may differ in return types. When signatures differ in return types, the resulting return
43335         // type is the union of the constituent return types.
43336         function getUnionSignatures(signatureLists) {
43337             var result;
43338             var indexWithLengthOverOne;
43339             for (var i = 0; i < signatureLists.length; i++) {
43340                 if (signatureLists[i].length === 0)
43341                     return ts.emptyArray;
43342                 if (signatureLists[i].length > 1) {
43343                     indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
43344                 }
43345                 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
43346                     var signature = _a[_i];
43347                     // Only process signatures with parameter lists that aren't already in the result list
43348                     if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
43349                         var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
43350                         if (unionSignatures) {
43351                             var s = signature;
43352                             // Union the result types when more than one signature matches
43353                             if (unionSignatures.length > 1) {
43354                                 var thisParameter = signature.thisParameter;
43355                                 var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
43356                                 if (firstThisParameterOfUnionSignatures) {
43357                                     var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
43358                                     thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
43359                                 }
43360                                 s = createUnionSignature(signature, unionSignatures);
43361                                 s.thisParameter = thisParameter;
43362                             }
43363                             (result || (result = [])).push(s);
43364                         }
43365                     }
43366                 }
43367             }
43368             if (!ts.length(result) && indexWithLengthOverOne !== -1) {
43369                 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
43370                 // signature that handles all over them. We only do this when there are overloads in only one constituent.
43371                 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
43372                 // signatures from the type, whose ordering would be non-obvious)
43373                 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
43374                 var results = masterList.slice();
43375                 var _loop_9 = function (signatures) {
43376                     if (signatures !== masterList) {
43377                         var signature_1 = signatures[0];
43378                         ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
43379                         results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
43380                         if (!results) {
43381                             return "break";
43382                         }
43383                     }
43384                 };
43385                 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
43386                     var signatures = signatureLists_1[_b];
43387                     var state_3 = _loop_9(signatures);
43388                     if (state_3 === "break")
43389                         break;
43390                 }
43391                 result = results;
43392             }
43393             return result || ts.emptyArray;
43394         }
43395         function combineUnionThisParam(left, right) {
43396             if (!left || !right) {
43397                 return left || right;
43398             }
43399             // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
43400             // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
43401             // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
43402             var thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]);
43403             return createSymbolWithType(left, thisType);
43404         }
43405         function combineUnionParameters(left, right) {
43406             var leftCount = getParameterCount(left);
43407             var rightCount = getParameterCount(right);
43408             var longest = leftCount >= rightCount ? left : right;
43409             var shorter = longest === left ? right : left;
43410             var longestCount = longest === left ? leftCount : rightCount;
43411             var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
43412             var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
43413             var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
43414             for (var i = 0; i < longestCount; i++) {
43415                 var longestParamType = tryGetTypeAtPosition(longest, i);
43416                 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
43417                 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
43418                 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
43419                 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
43420                 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
43421                 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
43422                 var paramName = leftName === rightName ? leftName :
43423                     !leftName ? rightName :
43424                         !rightName ? leftName :
43425                             undefined;
43426                 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i);
43427                 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
43428                 params[i] = paramSymbol;
43429             }
43430             if (needsExtraRestElement) {
43431                 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
43432                 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
43433                 params[longestCount] = restParamSymbol;
43434             }
43435             return params;
43436         }
43437         function combineSignaturesOfUnionMembers(left, right) {
43438             var declaration = left.declaration;
43439             var params = combineUnionParameters(left, right);
43440             var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
43441             var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
43442             var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, 
43443             /*resolvedReturnType*/ undefined, 
43444             /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */);
43445             result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
43446             return result;
43447         }
43448         function getUnionIndexInfo(types, kind) {
43449             var indexTypes = [];
43450             var isAnyReadonly = false;
43451             for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
43452                 var type = types_3[_i];
43453                 var indexInfo = getIndexInfoOfType(getApparentType(type), kind);
43454                 if (!indexInfo) {
43455                     return undefined;
43456                 }
43457                 indexTypes.push(indexInfo.type);
43458                 isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
43459             }
43460             return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
43461         }
43462         function resolveUnionTypeMembers(type) {
43463             // The members and properties collections are empty for union types. To get all properties of a union
43464             // type use getPropertiesOfType (only the language service uses this).
43465             var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
43466             var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
43467             var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
43468             var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
43469             setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43470         }
43471         function intersectTypes(type1, type2) {
43472             return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
43473         }
43474         function intersectIndexInfos(info1, info2) {
43475             return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
43476         }
43477         function unionSpreadIndexInfos(info1, info2) {
43478             return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
43479         }
43480         function findMixins(types) {
43481             var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
43482             var mixinFlags = ts.map(types, isMixinConstructorType);
43483             if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
43484                 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
43485                 mixinFlags[firstMixinIndex] = false;
43486             }
43487             return mixinFlags;
43488         }
43489         function includeMixinType(type, types, mixinFlags, index) {
43490             var mixedTypes = [];
43491             for (var i = 0; i < types.length; i++) {
43492                 if (i === index) {
43493                     mixedTypes.push(type);
43494                 }
43495                 else if (mixinFlags[i]) {
43496                     mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
43497                 }
43498             }
43499             return getIntersectionType(mixedTypes);
43500         }
43501         function resolveIntersectionTypeMembers(type) {
43502             // The members and properties collections are empty for intersection types. To get all properties of an
43503             // intersection type use getPropertiesOfType (only the language service uses this).
43504             var callSignatures;
43505             var constructSignatures;
43506             var stringIndexInfo;
43507             var numberIndexInfo;
43508             var types = type.types;
43509             var mixinFlags = findMixins(types);
43510             var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
43511             var _loop_10 = function (i) {
43512                 var t = type.types[i];
43513                 // When an intersection type contains mixin constructor types, the construct signatures from
43514                 // those types are discarded and their return types are mixed into the return types of all
43515                 // other construct signatures in the intersection type. For example, the intersection type
43516                 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
43517                 // 'new(s: string) => A & B'.
43518                 if (!mixinFlags[i]) {
43519                     var signatures = getSignaturesOfType(t, 1 /* Construct */);
43520                     if (signatures.length && mixinCount > 0) {
43521                         signatures = ts.map(signatures, function (s) {
43522                             var clone = cloneSignature(s);
43523                             clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
43524                             return clone;
43525                         });
43526                     }
43527                     constructSignatures = appendSignatures(constructSignatures, signatures);
43528                 }
43529                 callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
43530                 stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
43531                 numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
43532             };
43533             for (var i = 0; i < types.length; i++) {
43534                 _loop_10(i);
43535             }
43536             setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo);
43537         }
43538         function appendSignatures(signatures, newSignatures) {
43539             var _loop_11 = function (sig) {
43540                 if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
43541                     signatures = ts.append(signatures, sig);
43542                 }
43543             };
43544             for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
43545                 var sig = newSignatures_1[_i];
43546                 _loop_11(sig);
43547             }
43548             return signatures;
43549         }
43550         /**
43551          * Converts an AnonymousType to a ResolvedType.
43552          */
43553         function resolveAnonymousTypeMembers(type) {
43554             var symbol = getMergedSymbol(type.symbol);
43555             if (type.target) {
43556                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43557                 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
43558                 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
43559                 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
43560                 var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
43561                 var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
43562                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43563             }
43564             else if (symbol.flags & 2048 /* TypeLiteral */) {
43565                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43566                 var members = getMembersOfSymbol(symbol);
43567                 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
43568                 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
43569                 var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
43570                 var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
43571                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43572             }
43573             else {
43574                 // Combinations of function, class, enum and module
43575                 var members = emptySymbols;
43576                 var stringIndexInfo = void 0;
43577                 if (symbol.exports) {
43578                     members = getExportsOfSymbol(symbol);
43579                     if (symbol === globalThisSymbol) {
43580                         var varsOnly_1 = ts.createMap();
43581                         members.forEach(function (p) {
43582                             if (!(p.flags & 418 /* BlockScoped */)) {
43583                                 varsOnly_1.set(p.escapedName, p);
43584                             }
43585                         });
43586                         members = varsOnly_1;
43587                     }
43588                 }
43589                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
43590                 if (symbol.flags & 32 /* Class */) {
43591                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
43592                     var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43593                     if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
43594                         members = ts.createSymbolTable(getNamedMembers(members));
43595                         addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
43596                     }
43597                     else if (baseConstructorType === anyType) {
43598                         stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
43599                     }
43600                 }
43601                 var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
43602                     ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined;
43603                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43604                 // We resolve the members before computing the signatures because a signature may use
43605                 // typeof with a qualified name expression that circularly references the type we are
43606                 // in the process of resolving (see issue #6072). The temporarily empty signature list
43607                 // will never be observed because a qualified name can't reference signatures.
43608                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
43609                     type.callSignatures = getSignaturesOfSymbol(symbol);
43610                 }
43611                 // And likewise for construct signatures for classes
43612                 if (symbol.flags & 32 /* Class */) {
43613                     var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
43614                     var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
43615                     if (symbol.flags & 16 /* Function */) {
43616                         constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
43617                             createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) :
43618                             undefined; }));
43619                     }
43620                     if (!constructSignatures.length) {
43621                         constructSignatures = getDefaultConstructSignatures(classType_1);
43622                     }
43623                     type.constructSignatures = constructSignatures;
43624                 }
43625             }
43626         }
43627         function resolveReverseMappedTypeMembers(type) {
43628             var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
43629             var modifiers = getMappedTypeModifiers(type.mappedType);
43630             var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
43631             var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
43632             var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
43633             var members = ts.createSymbolTable();
43634             for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
43635                 var prop = _a[_i];
43636                 var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
43637                 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
43638                 inferredProp.declarations = prop.declarations;
43639                 inferredProp.nameType = getSymbolLinks(prop).nameType;
43640                 inferredProp.propertyType = getTypeOfSymbol(prop);
43641                 inferredProp.mappedType = type.mappedType;
43642                 inferredProp.constraintType = type.constraintType;
43643                 members.set(prop.escapedName, inferredProp);
43644             }
43645             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
43646         }
43647         // Return the lower bound of the key type in a mapped type. Intuitively, the lower
43648         // bound includes those keys that are known to always be present, for example because
43649         // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
43650         function getLowerBoundOfKeyType(type) {
43651             if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) {
43652                 return type;
43653             }
43654             if (type.flags & 4194304 /* Index */) {
43655                 return getIndexType(getApparentType(type.type));
43656             }
43657             if (type.flags & 16777216 /* Conditional */) {
43658                 if (type.root.isDistributive) {
43659                     var checkType = type.checkType;
43660                     var constraint = getLowerBoundOfKeyType(checkType);
43661                     if (constraint !== checkType) {
43662                         return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
43663                     }
43664                 }
43665                 return type;
43666             }
43667             if (type.flags & 1048576 /* Union */) {
43668                 return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43669             }
43670             if (type.flags & 2097152 /* Intersection */) {
43671                 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43672             }
43673             return neverType;
43674         }
43675         /** Resolve the members of a mapped type { [P in K]: T } */
43676         function resolveMappedTypeMembers(type) {
43677             var members = ts.createSymbolTable();
43678             var stringIndexInfo;
43679             var numberIndexInfo;
43680             // Resolve upfront such that recursive references see an empty object type.
43681             setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43682             // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
43683             // and T as the template type.
43684             var typeParameter = getTypeParameterFromMappedType(type);
43685             var constraintType = getConstraintTypeFromMappedType(type);
43686             var templateType = getTemplateTypeFromMappedType(type.target || type);
43687             var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
43688             var templateModifiers = getMappedTypeModifiers(type);
43689             var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
43690             if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43691                 // We have a { [P in keyof T]: X }
43692                 for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
43693                     var prop = _a[_i];
43694                     addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
43695                 }
43696                 if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
43697                     addMemberForKeyType(stringType);
43698                 }
43699                 if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
43700                     addMemberForKeyType(numberType);
43701                 }
43702             }
43703             else {
43704                 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
43705             }
43706             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43707             function addMemberForKeyType(t) {
43708                 // Create a mapper from T to the current iteration type constituent. Then, if the
43709                 // mapped type is itself an instantiated type, combine the iteration mapper with the
43710                 // instantiation mapper.
43711                 var templateMapper = appendTypeMapping(type.mapper, typeParameter, t);
43712                 // If the current iteration type constituent is a string literal type, create a property.
43713                 // Otherwise, for type string create a string index signature.
43714                 if (isTypeUsableAsPropertyName(t)) {
43715                     var propName = getPropertyNameFromType(t);
43716                     var modifiersProp = getPropertyOfType(modifiersType, propName);
43717                     var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
43718                         !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
43719                     var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
43720                         !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
43721                     var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
43722                     var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
43723                     prop.mappedType = type;
43724                     prop.mapper = templateMapper;
43725                     if (modifiersProp) {
43726                         prop.syntheticOrigin = modifiersProp;
43727                         prop.declarations = modifiersProp.declarations;
43728                     }
43729                     prop.nameType = t;
43730                     members.set(propName, prop);
43731                 }
43732                 else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) {
43733                     var propType = instantiateType(templateType, templateMapper);
43734                     if (t.flags & (1 /* Any */ | 4 /* String */)) {
43735                         stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43736                     }
43737                     else {
43738                         numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43739                     }
43740                 }
43741             }
43742         }
43743         function getTypeOfMappedSymbol(symbol) {
43744             if (!symbol.type) {
43745                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
43746                     return errorType;
43747                 }
43748                 var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType);
43749                 var propType = instantiateType(templateType, symbol.mapper);
43750                 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
43751                 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
43752                 // mode, if the underlying property is optional we remove 'undefined' from the type.
43753                 var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
43754                     symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
43755                         propType;
43756                 if (!popTypeResolution()) {
43757                     error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType));
43758                     type = errorType;
43759                 }
43760                 symbol.type = type;
43761                 symbol.mapper = undefined;
43762             }
43763             return symbol.type;
43764         }
43765         function getTypeParameterFromMappedType(type) {
43766             return type.typeParameter ||
43767                 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
43768         }
43769         function getConstraintTypeFromMappedType(type) {
43770             return type.constraintType ||
43771                 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
43772         }
43773         function getTemplateTypeFromMappedType(type) {
43774             return type.templateType ||
43775                 (type.templateType = type.declaration.type ?
43776                     instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) :
43777                     errorType);
43778         }
43779         function getConstraintDeclarationForMappedType(type) {
43780             return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
43781         }
43782         function isMappedTypeWithKeyofConstraintDeclaration(type) {
43783             var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
43784             return constraintDeclaration.kind === 184 /* TypeOperator */ &&
43785                 constraintDeclaration.operator === 134 /* KeyOfKeyword */;
43786         }
43787         function getModifiersTypeFromMappedType(type) {
43788             if (!type.modifiersType) {
43789                 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43790                     // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
43791                     // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
43792                     // 'keyof T' to a literal union type and we can't recover T from that type.
43793                     type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
43794                 }
43795                 else {
43796                     // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
43797                     // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
43798                     // the modifiers type is T. Otherwise, the modifiers type is unknown.
43799                     var declaredType = getTypeFromMappedTypeNode(type.declaration);
43800                     var constraint = getConstraintTypeFromMappedType(declaredType);
43801                     var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
43802                     type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
43803                 }
43804             }
43805             return type.modifiersType;
43806         }
43807         function getMappedTypeModifiers(type) {
43808             var declaration = type.declaration;
43809             return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
43810                 (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
43811         }
43812         function getMappedTypeOptionality(type) {
43813             var modifiers = getMappedTypeModifiers(type);
43814             return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
43815         }
43816         function getCombinedMappedTypeOptionality(type) {
43817             var optionality = getMappedTypeOptionality(type);
43818             var modifiersType = getModifiersTypeFromMappedType(type);
43819             return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
43820         }
43821         function isPartialMappedType(type) {
43822             return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
43823         }
43824         function isGenericMappedType(type) {
43825             return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
43826         }
43827         function resolveStructuredTypeMembers(type) {
43828             if (!type.members) {
43829                 if (type.flags & 524288 /* Object */) {
43830                     if (type.objectFlags & 4 /* Reference */) {
43831                         resolveTypeReferenceMembers(type);
43832                     }
43833                     else if (type.objectFlags & 3 /* ClassOrInterface */) {
43834                         resolveClassOrInterfaceMembers(type);
43835                     }
43836                     else if (type.objectFlags & 2048 /* ReverseMapped */) {
43837                         resolveReverseMappedTypeMembers(type);
43838                     }
43839                     else if (type.objectFlags & 16 /* Anonymous */) {
43840                         resolveAnonymousTypeMembers(type);
43841                     }
43842                     else if (type.objectFlags & 32 /* Mapped */) {
43843                         resolveMappedTypeMembers(type);
43844                     }
43845                 }
43846                 else if (type.flags & 1048576 /* Union */) {
43847                     resolveUnionTypeMembers(type);
43848                 }
43849                 else if (type.flags & 2097152 /* Intersection */) {
43850                     resolveIntersectionTypeMembers(type);
43851                 }
43852             }
43853             return type;
43854         }
43855         /** Return properties of an object type or an empty array for other types */
43856         function getPropertiesOfObjectType(type) {
43857             if (type.flags & 524288 /* Object */) {
43858                 return resolveStructuredTypeMembers(type).properties;
43859             }
43860             return ts.emptyArray;
43861         }
43862         /** If the given type is an object type and that type has a property by the given name,
43863          * return the symbol for that property. Otherwise return undefined.
43864          */
43865         function getPropertyOfObjectType(type, name) {
43866             if (type.flags & 524288 /* Object */) {
43867                 var resolved = resolveStructuredTypeMembers(type);
43868                 var symbol = resolved.members.get(name);
43869                 if (symbol && symbolIsValue(symbol)) {
43870                     return symbol;
43871                 }
43872             }
43873         }
43874         function getPropertiesOfUnionOrIntersectionType(type) {
43875             if (!type.resolvedProperties) {
43876                 var members = ts.createSymbolTable();
43877                 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
43878                     var current = _a[_i];
43879                     for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
43880                         var prop = _c[_b];
43881                         if (!members.has(prop.escapedName)) {
43882                             var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
43883                             if (combinedProp) {
43884                                 members.set(prop.escapedName, combinedProp);
43885                             }
43886                         }
43887                     }
43888                     // The properties of a union type are those that are present in all constituent types, so
43889                     // we only need to check the properties of the first type without index signature
43890                     if (type.flags & 1048576 /* Union */ && !getIndexInfoOfType(current, 0 /* String */) && !getIndexInfoOfType(current, 1 /* Number */)) {
43891                         break;
43892                     }
43893                 }
43894                 type.resolvedProperties = getNamedMembers(members);
43895             }
43896             return type.resolvedProperties;
43897         }
43898         function getPropertiesOfType(type) {
43899             type = getReducedApparentType(type);
43900             return type.flags & 3145728 /* UnionOrIntersection */ ?
43901                 getPropertiesOfUnionOrIntersectionType(type) :
43902                 getPropertiesOfObjectType(type);
43903         }
43904         function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
43905             var list = obj.properties;
43906             return list.some(function (property) {
43907                 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
43908                 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
43909                 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
43910                 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
43911             });
43912         }
43913         function getAllPossiblePropertiesOfTypes(types) {
43914             var unionType = getUnionType(types);
43915             if (!(unionType.flags & 1048576 /* Union */)) {
43916                 return getAugmentedPropertiesOfType(unionType);
43917             }
43918             var props = ts.createSymbolTable();
43919             for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
43920                 var memberType = types_4[_i];
43921                 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
43922                     var escapedName = _b[_a].escapedName;
43923                     if (!props.has(escapedName)) {
43924                         var prop = createUnionOrIntersectionProperty(unionType, escapedName);
43925                         // May be undefined if the property is private
43926                         if (prop)
43927                             props.set(escapedName, prop);
43928                     }
43929                 }
43930             }
43931             return ts.arrayFrom(props.values());
43932         }
43933         function getConstraintOfType(type) {
43934             return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
43935                 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
43936                     type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
43937                         getBaseConstraintOfType(type);
43938         }
43939         function getConstraintOfTypeParameter(typeParameter) {
43940             return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
43941         }
43942         function getConstraintOfIndexedAccess(type) {
43943             return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
43944         }
43945         function getSimplifiedTypeOrConstraint(type) {
43946             var simplified = getSimplifiedType(type, /*writing*/ false);
43947             return simplified !== type ? simplified : getConstraintOfType(type);
43948         }
43949         function getConstraintFromIndexedAccess(type) {
43950             var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
43951             if (indexConstraint && indexConstraint !== type.indexType) {
43952                 var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint);
43953                 if (indexedAccess) {
43954                     return indexedAccess;
43955                 }
43956             }
43957             var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
43958             if (objectConstraint && objectConstraint !== type.objectType) {
43959                 return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType);
43960             }
43961             return undefined;
43962         }
43963         function getDefaultConstraintOfConditionalType(type) {
43964             if (!type.resolvedDefaultConstraint) {
43965                 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
43966                 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
43967                 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
43968                 // in effect treating `any` like `never` rather than `unknown` in this location.
43969                 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
43970                 var falseConstraint = getFalseTypeFromConditionalType(type);
43971                 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
43972             }
43973             return type.resolvedDefaultConstraint;
43974         }
43975         function getConstraintOfDistributiveConditionalType(type) {
43976             // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
43977             // type parameter. If so, create an instantiation of the conditional type where T is replaced
43978             // with its constraint. We do this because if the constraint is a union type it will be distributed
43979             // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
43980             // removes 'undefined' from T.
43981             // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
43982             // as the constraint for all type params (check type included) have been replace with `unknown`, which
43983             // is going to produce even more false positive/negative results than the distribute constraint already does.
43984             // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
43985             // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
43986             // likely doesn't need to exist.
43987             if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
43988                 var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
43989                 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
43990                 if (constraint && constraint !== type.checkType) {
43991                     var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
43992                     if (!(instantiated.flags & 131072 /* Never */)) {
43993                         return instantiated;
43994                     }
43995                 }
43996             }
43997             return undefined;
43998         }
43999         function getConstraintFromConditionalType(type) {
44000             return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
44001         }
44002         function getConstraintOfConditionalType(type) {
44003             return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
44004         }
44005         function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
44006             var constraints;
44007             var hasDisjointDomainType = false;
44008             for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
44009                 var t = types_5[_i];
44010                 if (t.flags & 63176704 /* Instantiable */) {
44011                     // We keep following constraints as long as we have an instantiable type that is known
44012                     // not to be circular or infinite (hence we stop on index access types).
44013                     var constraint = getConstraintOfType(t);
44014                     while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
44015                         constraint = getConstraintOfType(constraint);
44016                     }
44017                     if (constraint) {
44018                         constraints = ts.append(constraints, constraint);
44019                         if (targetIsUnion) {
44020                             constraints = ts.append(constraints, t);
44021                         }
44022                     }
44023                 }
44024                 else if (t.flags & 67238908 /* DisjointDomains */) {
44025                     hasDisjointDomainType = true;
44026                 }
44027             }
44028             // If the target is a union type or if we are intersecting with types belonging to one of the
44029             // disjoint domains, we may end up producing a constraint that hasn't been examined before.
44030             if (constraints && (targetIsUnion || hasDisjointDomainType)) {
44031                 if (hasDisjointDomainType) {
44032                     // We add any types belong to one of the disjoint domains because they might cause the final
44033                     // intersection operation to reduce the union constraints.
44034                     for (var _a = 0, types_6 = types; _a < types_6.length; _a++) {
44035                         var t = types_6[_a];
44036                         if (t.flags & 67238908 /* DisjointDomains */) {
44037                             constraints = ts.append(constraints, t);
44038                         }
44039                     }
44040                 }
44041                 return getIntersectionType(constraints);
44042             }
44043             return undefined;
44044         }
44045         function getBaseConstraintOfType(type) {
44046             if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) {
44047                 var constraint = getResolvedBaseConstraint(type);
44048                 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
44049             }
44050             return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
44051         }
44052         /**
44053          * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
44054          * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
44055          */
44056         function getBaseConstraintOrType(type) {
44057             return getBaseConstraintOfType(type) || type;
44058         }
44059         function hasNonCircularBaseConstraint(type) {
44060             return getResolvedBaseConstraint(type) !== circularConstraintType;
44061         }
44062         /**
44063          * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
44064          * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
44065          * circularly references the type variable.
44066          */
44067         function getResolvedBaseConstraint(type) {
44068             var nonTerminating = false;
44069             return type.resolvedBaseConstraint ||
44070                 (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type));
44071             function getImmediateBaseConstraint(t) {
44072                 if (!t.immediateBaseConstraint) {
44073                     if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
44074                         return circularConstraintType;
44075                     }
44076                     if (constraintDepth >= 50) {
44077                         // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
44078                         // very high likelihood we're dealing with an infinite generic type that perpetually generates
44079                         // new type identities as we descend into it. We stop the recursion here and mark this type
44080                         // and the outer types as having circular constraints.
44081                         error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
44082                         nonTerminating = true;
44083                         return t.immediateBaseConstraint = noConstraintType;
44084                     }
44085                     constraintDepth++;
44086                     var result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
44087                     constraintDepth--;
44088                     if (!popTypeResolution()) {
44089                         if (t.flags & 262144 /* TypeParameter */) {
44090                             var errorNode = getConstraintDeclaration(t);
44091                             if (errorNode) {
44092                                 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
44093                                 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
44094                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
44095                                 }
44096                             }
44097                         }
44098                         result = circularConstraintType;
44099                     }
44100                     if (nonTerminating) {
44101                         result = circularConstraintType;
44102                     }
44103                     t.immediateBaseConstraint = result || noConstraintType;
44104                 }
44105                 return t.immediateBaseConstraint;
44106             }
44107             function getBaseConstraint(t) {
44108                 var c = getImmediateBaseConstraint(t);
44109                 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
44110             }
44111             function computeBaseConstraint(t) {
44112                 if (t.flags & 262144 /* TypeParameter */) {
44113                     var constraint = getConstraintFromTypeParameter(t);
44114                     return t.isThisType || !constraint ?
44115                         constraint :
44116                         getBaseConstraint(constraint);
44117                 }
44118                 if (t.flags & 3145728 /* UnionOrIntersection */) {
44119                     var types = t.types;
44120                     var baseTypes = [];
44121                     for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
44122                         var type_2 = types_7[_i];
44123                         var baseType = getBaseConstraint(type_2);
44124                         if (baseType) {
44125                             baseTypes.push(baseType);
44126                         }
44127                     }
44128                     return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
44129                         t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
44130                             undefined;
44131                 }
44132                 if (t.flags & 4194304 /* Index */) {
44133                     return keyofConstraintType;
44134                 }
44135                 if (t.flags & 8388608 /* IndexedAccess */) {
44136                     var baseObjectType = getBaseConstraint(t.objectType);
44137                     var baseIndexType = getBaseConstraint(t.indexType);
44138                     var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType);
44139                     return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
44140                 }
44141                 if (t.flags & 16777216 /* Conditional */) {
44142                     var constraint = getConstraintFromConditionalType(t);
44143                     constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
44144                     var result = constraint && getBaseConstraint(constraint);
44145                     constraintDepth--;
44146                     return result;
44147                 }
44148                 if (t.flags & 33554432 /* Substitution */) {
44149                     return getBaseConstraint(t.substitute);
44150                 }
44151                 return t;
44152             }
44153         }
44154         function getApparentTypeOfIntersectionType(type) {
44155             return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
44156         }
44157         function getResolvedTypeParameterDefault(typeParameter) {
44158             if (!typeParameter.default) {
44159                 if (typeParameter.target) {
44160                     var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
44161                     typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
44162                 }
44163                 else {
44164                     // To block recursion, set the initial value to the resolvingDefaultType.
44165                     typeParameter.default = resolvingDefaultType;
44166                     var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
44167                     var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
44168                     if (typeParameter.default === resolvingDefaultType) {
44169                         // If we have not been called recursively, set the correct default type.
44170                         typeParameter.default = defaultType;
44171                     }
44172                 }
44173             }
44174             else if (typeParameter.default === resolvingDefaultType) {
44175                 // If we are called recursively for this type parameter, mark the default as circular.
44176                 typeParameter.default = circularConstraintType;
44177             }
44178             return typeParameter.default;
44179         }
44180         /**
44181          * Gets the default type for a type parameter.
44182          *
44183          * If the type parameter is the result of an instantiation, this gets the instantiated
44184          * default type of its target. If the type parameter has no default type or the default is
44185          * circular, `undefined` is returned.
44186          */
44187         function getDefaultFromTypeParameter(typeParameter) {
44188             var defaultType = getResolvedTypeParameterDefault(typeParameter);
44189             return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
44190         }
44191         function hasNonCircularTypeParameterDefault(typeParameter) {
44192             return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
44193         }
44194         /**
44195          * Indicates whether the declaration of a typeParameter has a default type.
44196          */
44197         function hasTypeParameterDefault(typeParameter) {
44198             return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
44199         }
44200         function getApparentTypeOfMappedType(type) {
44201             return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
44202         }
44203         function getResolvedApparentTypeOfMappedType(type) {
44204             var typeVariable = getHomomorphicTypeVariable(type);
44205             if (typeVariable) {
44206                 var constraint = getConstraintOfTypeParameter(typeVariable);
44207                 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
44208                     return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper));
44209                 }
44210             }
44211             return type;
44212         }
44213         /**
44214          * For a type parameter, return the base constraint of the type parameter. For the string, number,
44215          * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
44216          * type itself.
44217          */
44218         function getApparentType(type) {
44219             var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
44220             return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
44221                 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
44222                     t.flags & 132 /* StringLike */ ? globalStringType :
44223                         t.flags & 296 /* NumberLike */ ? globalNumberType :
44224                             t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) :
44225                                 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
44226                                     t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
44227                                         t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
44228                                             t.flags & 4194304 /* Index */ ? keyofConstraintType :
44229                                                 t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
44230                                                     t;
44231         }
44232         function getReducedApparentType(type) {
44233             // Since getApparentType may return a non-reduced union or intersection type, we need to perform
44234             // type reduction both before and after obtaining the apparent type. For example, given a type parameter
44235             // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and
44236             // that type may need futher reduction to remove empty intersections.
44237             return getReducedType(getApparentType(getReducedType(type)));
44238         }
44239         function createUnionOrIntersectionProperty(containingType, name) {
44240             var singleProp;
44241             var propSet;
44242             var indexTypes;
44243             var isUnion = containingType.flags & 1048576 /* Union */;
44244             // Flags we want to propagate to the result if they exist in all source symbols
44245             var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
44246             var syntheticFlag = 4 /* SyntheticMethod */;
44247             var checkFlags = 0;
44248             for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
44249                 var current = _a[_i];
44250                 var type = getApparentType(current);
44251                 if (!(type === errorType || type.flags & 131072 /* Never */)) {
44252                     var prop = getPropertyOfType(type, name);
44253                     var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
44254                     if (prop) {
44255                         if (isUnion) {
44256                             optionalFlag |= (prop.flags & 16777216 /* Optional */);
44257                         }
44258                         else {
44259                             optionalFlag &= prop.flags;
44260                         }
44261                         if (!singleProp) {
44262                             singleProp = prop;
44263                         }
44264                         else if (prop !== singleProp) {
44265                             if (!propSet) {
44266                                 propSet = ts.createMap();
44267                                 propSet.set("" + getSymbolId(singleProp), singleProp);
44268                             }
44269                             var id = "" + getSymbolId(prop);
44270                             if (!propSet.has(id)) {
44271                                 propSet.set(id, prop);
44272                             }
44273                         }
44274                         checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
44275                             (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
44276                             (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
44277                             (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
44278                             (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
44279                         if (!isPrototypeProperty(prop)) {
44280                             syntheticFlag = 2 /* SyntheticProperty */;
44281                         }
44282                     }
44283                     else if (isUnion) {
44284                         var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
44285                         if (indexInfo) {
44286                             checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
44287                             indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
44288                         }
44289                         else if (isObjectLiteralType(type)) {
44290                             checkFlags |= 32 /* WritePartial */;
44291                             indexTypes = ts.append(indexTypes, undefinedType);
44292                         }
44293                         else {
44294                             checkFlags |= 16 /* ReadPartial */;
44295                         }
44296                     }
44297                 }
44298             }
44299             if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) {
44300                 // No property was found, or, in a union, a property has a private or protected declaration in one
44301                 // constituent, but is missing or has a different declaration in another constituent.
44302                 return undefined;
44303             }
44304             if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
44305                 return singleProp;
44306             }
44307             var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp];
44308             var declarations;
44309             var firstType;
44310             var nameType;
44311             var propTypes = [];
44312             var firstValueDeclaration;
44313             var hasNonUniformValueDeclaration = false;
44314             for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
44315                 var prop = props_1[_b];
44316                 if (!firstValueDeclaration) {
44317                     firstValueDeclaration = prop.valueDeclaration;
44318                 }
44319                 else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
44320                     hasNonUniformValueDeclaration = true;
44321                 }
44322                 declarations = ts.addRange(declarations, prop.declarations);
44323                 var type = getTypeOfSymbol(prop);
44324                 if (!firstType) {
44325                     firstType = type;
44326                     nameType = getSymbolLinks(prop).nameType;
44327                 }
44328                 else if (type !== firstType) {
44329                     checkFlags |= 64 /* HasNonUniformType */;
44330                 }
44331                 if (isLiteralType(type)) {
44332                     checkFlags |= 128 /* HasLiteralType */;
44333                 }
44334                 if (type.flags & 131072 /* Never */) {
44335                     checkFlags |= 131072 /* HasNeverType */;
44336                 }
44337                 propTypes.push(type);
44338             }
44339             ts.addRange(propTypes, indexTypes);
44340             var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
44341             result.containingType = containingType;
44342             if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
44343                 result.valueDeclaration = firstValueDeclaration;
44344                 // Inherit information about parent type.
44345                 if (firstValueDeclaration.symbol.parent) {
44346                     result.parent = firstValueDeclaration.symbol.parent;
44347                 }
44348             }
44349             result.declarations = declarations;
44350             result.nameType = nameType;
44351             if (propTypes.length > 2) {
44352                 // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
44353                 result.checkFlags |= 65536 /* DeferredType */;
44354                 result.deferralParent = containingType;
44355                 result.deferralConstituents = propTypes;
44356             }
44357             else {
44358                 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
44359             }
44360             return result;
44361         }
44362         // Return the symbol for a given property in a union or intersection type, or undefined if the property
44363         // does not exist in any constituent type. Note that the returned property may only be present in some
44364         // constituents, in which case the isPartial flag is set when the containing type is union type. We need
44365         // these partial properties when identifying discriminant properties, but otherwise they are filtered out
44366         // and do not appear to be present in the union type.
44367         function getUnionOrIntersectionProperty(type, name) {
44368             var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
44369             var property = properties.get(name);
44370             if (!property) {
44371                 property = createUnionOrIntersectionProperty(type, name);
44372                 if (property) {
44373                     properties.set(name, property);
44374                 }
44375             }
44376             return property;
44377         }
44378         function getPropertyOfUnionOrIntersectionType(type, name) {
44379             var property = getUnionOrIntersectionProperty(type, name);
44380             // We need to filter out partial properties in union types
44381             return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
44382         }
44383         /**
44384          * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types.
44385          * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'.
44386          * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when
44387          * no constituent property has type 'never', but the intersection of the constituent property types is 'never'.
44388          */
44389         function getReducedType(type) {
44390             if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) {
44391                 return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
44392             }
44393             else if (type.flags & 2097152 /* Intersection */) {
44394                 if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) {
44395                     type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ |
44396                         (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0);
44397                 }
44398                 return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type;
44399             }
44400             return type;
44401         }
44402         function getReducedUnionType(unionType) {
44403             var reducedTypes = ts.sameMap(unionType.types, getReducedType);
44404             if (reducedTypes === unionType.types) {
44405                 return unionType;
44406             }
44407             var reduced = getUnionType(reducedTypes);
44408             if (reduced.flags & 1048576 /* Union */) {
44409                 reduced.resolvedReducedType = reduced;
44410             }
44411             return reduced;
44412         }
44413         function isNeverReducedProperty(prop) {
44414             return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
44415         }
44416         function isDiscriminantWithNeverType(prop) {
44417             // Return true for a synthetic non-optional property with non-uniform types, where at least one is
44418             // a literal type and none is never, that reduces to never.
44419             return !(prop.flags & 16777216 /* Optional */) &&
44420                 (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ &&
44421                 !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
44422         }
44423         function isConflictingPrivateProperty(prop) {
44424             // Return true for a synthetic property with multiple declarations, at least one of which is private.
44425             return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */);
44426         }
44427         function elaborateNeverIntersection(errorInfo, type) {
44428             if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) {
44429                 var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
44430                 if (neverProp) {
44431                     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));
44432                 }
44433                 var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
44434                 if (privateProp) {
44435                     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));
44436                 }
44437             }
44438             return errorInfo;
44439         }
44440         /**
44441          * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
44442          * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
44443          * Object and Function as appropriate.
44444          *
44445          * @param type a type to look up property from
44446          * @param name a name of property to look up in a given type
44447          */
44448         function getPropertyOfType(type, name) {
44449             type = getReducedApparentType(type);
44450             if (type.flags & 524288 /* Object */) {
44451                 var resolved = resolveStructuredTypeMembers(type);
44452                 var symbol = resolved.members.get(name);
44453                 if (symbol && symbolIsValue(symbol)) {
44454                     return symbol;
44455                 }
44456                 var functionType = resolved === anyFunctionType ? globalFunctionType :
44457                     resolved.callSignatures.length ? globalCallableFunctionType :
44458                         resolved.constructSignatures.length ? globalNewableFunctionType :
44459                             undefined;
44460                 if (functionType) {
44461                     var symbol_1 = getPropertyOfObjectType(functionType, name);
44462                     if (symbol_1) {
44463                         return symbol_1;
44464                     }
44465                 }
44466                 return getPropertyOfObjectType(globalObjectType, name);
44467             }
44468             if (type.flags & 3145728 /* UnionOrIntersection */) {
44469                 return getPropertyOfUnionOrIntersectionType(type, name);
44470             }
44471             return undefined;
44472         }
44473         function getSignaturesOfStructuredType(type, kind) {
44474             if (type.flags & 3670016 /* StructuredType */) {
44475                 var resolved = resolveStructuredTypeMembers(type);
44476                 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
44477             }
44478             return ts.emptyArray;
44479         }
44480         /**
44481          * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
44482          * maps primitive types and type parameters are to their apparent types.
44483          */
44484         function getSignaturesOfType(type, kind) {
44485             return getSignaturesOfStructuredType(getReducedApparentType(type), kind);
44486         }
44487         function getIndexInfoOfStructuredType(type, kind) {
44488             if (type.flags & 3670016 /* StructuredType */) {
44489                 var resolved = resolveStructuredTypeMembers(type);
44490                 return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
44491             }
44492         }
44493         function getIndexTypeOfStructuredType(type, kind) {
44494             var info = getIndexInfoOfStructuredType(type, kind);
44495             return info && info.type;
44496         }
44497         // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
44498         // maps primitive types and type parameters are to their apparent types.
44499         function getIndexInfoOfType(type, kind) {
44500             return getIndexInfoOfStructuredType(getReducedApparentType(type), kind);
44501         }
44502         // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
44503         // maps primitive types and type parameters are to their apparent types.
44504         function getIndexTypeOfType(type, kind) {
44505             return getIndexTypeOfStructuredType(getReducedApparentType(type), kind);
44506         }
44507         function getImplicitIndexTypeOfType(type, kind) {
44508             if (isObjectTypeWithInferableIndex(type)) {
44509                 var propTypes = [];
44510                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
44511                     var prop = _a[_i];
44512                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
44513                         propTypes.push(getTypeOfSymbol(prop));
44514                     }
44515                 }
44516                 if (kind === 0 /* String */) {
44517                     ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */));
44518                 }
44519                 if (propTypes.length) {
44520                     return getUnionType(propTypes);
44521                 }
44522             }
44523             return undefined;
44524         }
44525         // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
44526         // type checking functions).
44527         function getTypeParametersFromDeclaration(declaration) {
44528             var result;
44529             for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
44530                 var node = _a[_i];
44531                 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
44532             }
44533             return result;
44534         }
44535         function symbolsToArray(symbols) {
44536             var result = [];
44537             symbols.forEach(function (symbol, id) {
44538                 if (!isReservedMemberName(id)) {
44539                     result.push(symbol);
44540                 }
44541             });
44542             return result;
44543         }
44544         function isJSDocOptionalParameter(node) {
44545             return ts.isInJSFile(node) && (
44546             // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
44547             node.type && node.type.kind === 299 /* JSDocOptionalType */
44548                 || ts.getJSDocParameterTags(node).some(function (_a) {
44549                     var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
44550                     return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44551                 }));
44552         }
44553         function tryFindAmbientModule(moduleName, withAugmentations) {
44554             if (ts.isExternalModuleNameRelative(moduleName)) {
44555                 return undefined;
44556             }
44557             var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
44558             // merged symbol is module declaration symbol combined with all augmentations
44559             return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
44560         }
44561         function isOptionalParameter(node) {
44562             if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) {
44563                 return true;
44564             }
44565             if (node.initializer) {
44566                 var signature = getSignatureFromDeclaration(node.parent);
44567                 var parameterIndex = node.parent.parameters.indexOf(node);
44568                 ts.Debug.assert(parameterIndex >= 0);
44569                 return parameterIndex >= getMinArgumentCount(signature, /*strongArityForUntypedJS*/ true);
44570             }
44571             var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
44572             if (iife) {
44573                 return !node.type &&
44574                     !node.dotDotDotToken &&
44575                     node.parent.parameters.indexOf(node) >= iife.arguments.length;
44576             }
44577             return false;
44578         }
44579         function isOptionalJSDocParameterTag(node) {
44580             if (!ts.isJSDocParameterTag(node)) {
44581                 return false;
44582             }
44583             var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
44584             return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44585         }
44586         function createTypePredicate(kind, parameterName, parameterIndex, type) {
44587             return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
44588         }
44589         /**
44590          * Gets the minimum number of type arguments needed to satisfy all non-optional type
44591          * parameters.
44592          */
44593         function getMinTypeArgumentCount(typeParameters) {
44594             var minTypeArgumentCount = 0;
44595             if (typeParameters) {
44596                 for (var i = 0; i < typeParameters.length; i++) {
44597                     if (!hasTypeParameterDefault(typeParameters[i])) {
44598                         minTypeArgumentCount = i + 1;
44599                     }
44600                 }
44601             }
44602             return minTypeArgumentCount;
44603         }
44604         function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
44605             var numTypeParameters = ts.length(typeParameters);
44606             if (!numTypeParameters) {
44607                 return [];
44608             }
44609             var numTypeArguments = ts.length(typeArguments);
44610             if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
44611                 var result = typeArguments ? typeArguments.slice() : [];
44612                 // Map invalid forward references in default types to the error type
44613                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44614                     result[i] = errorType;
44615                 }
44616                 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
44617                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44618                     var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
44619                     if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
44620                         defaultType = anyType;
44621                     }
44622                     result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
44623                 }
44624                 result.length = typeParameters.length;
44625                 return result;
44626             }
44627             return typeArguments && typeArguments.slice();
44628         }
44629         function getSignatureFromDeclaration(declaration) {
44630             var links = getNodeLinks(declaration);
44631             if (!links.resolvedSignature) {
44632                 var parameters = [];
44633                 var flags = 0 /* None */;
44634                 var minArgumentCount = 0;
44635                 var thisParameter = void 0;
44636                 var hasThisParameter = false;
44637                 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
44638                 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
44639                 var isUntypedSignatureInJSFile = !iife &&
44640                     ts.isInJSFile(declaration) &&
44641                     ts.isValueSignatureDeclaration(declaration) &&
44642                     !ts.hasJSDocParameterTags(declaration) &&
44643                     !ts.getJSDocType(declaration);
44644                 if (isUntypedSignatureInJSFile) {
44645                     flags |= 16 /* IsUntypedSignatureInJSFile */;
44646                 }
44647                 // If this is a JSDoc construct signature, then skip the first parameter in the
44648                 // parameter list.  The first parameter represents the return type of the construct
44649                 // signature.
44650                 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
44651                     var param = declaration.parameters[i];
44652                     var paramSymbol = param.symbol;
44653                     var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
44654                     // Include parameter symbol instead of property symbol in the signature
44655                     if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
44656                         var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
44657                         paramSymbol = resolvedSymbol;
44658                     }
44659                     if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
44660                         hasThisParameter = true;
44661                         thisParameter = param.symbol;
44662                     }
44663                     else {
44664                         parameters.push(paramSymbol);
44665                     }
44666                     if (type && type.kind === 187 /* LiteralType */) {
44667                         flags |= 2 /* HasLiteralTypes */;
44668                     }
44669                     // Record a new minimum argument count if this is not an optional parameter
44670                     var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) ||
44671                         param.initializer || param.questionToken || param.dotDotDotToken ||
44672                         iife && parameters.length > iife.arguments.length && !type ||
44673                         isJSDocOptionalParameter(param);
44674                     if (!isOptionalParameter_1) {
44675                         minArgumentCount = parameters.length;
44676                     }
44677                 }
44678                 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
44679                 if ((declaration.kind === 163 /* GetAccessor */ || declaration.kind === 164 /* SetAccessor */) &&
44680                     !hasNonBindableDynamicName(declaration) &&
44681                     (!hasThisParameter || !thisParameter)) {
44682                     var otherKind = declaration.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
44683                     var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
44684                     if (other) {
44685                         thisParameter = getAnnotatedAccessorThisParameter(other);
44686                     }
44687                 }
44688                 var classType = declaration.kind === 162 /* Constructor */ ?
44689                     getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
44690                     : undefined;
44691                 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
44692                 if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
44693                     flags |= 1 /* HasRestParameter */;
44694                 }
44695                 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, 
44696                 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
44697             }
44698             return links.resolvedSignature;
44699         }
44700         /**
44701          * A JS function gets a synthetic rest parameter if it references `arguments` AND:
44702          * 1. It has no parameters but at least one `@param` with a type that starts with `...`
44703          * OR
44704          * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
44705          */
44706         function maybeAddJsSyntheticRestParameter(declaration, parameters) {
44707             if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
44708                 return false;
44709             }
44710             var lastParam = ts.lastOrUndefined(declaration.parameters);
44711             var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
44712             var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
44713                 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
44714             });
44715             var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
44716             syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
44717             if (lastParamVariadicType) {
44718                 // Replace the last parameter with a rest parameter.
44719                 parameters.pop();
44720             }
44721             parameters.push(syntheticArgsSymbol);
44722             return true;
44723         }
44724         function getSignatureOfTypeTag(node) {
44725             // should be attached to a function declaration or expression
44726             if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node)))
44727                 return undefined;
44728             var typeTag = ts.getJSDocTypeTag(node);
44729             var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
44730             return signature && getErasedSignature(signature);
44731         }
44732         function getReturnTypeOfTypeTag(node) {
44733             var signature = getSignatureOfTypeTag(node);
44734             return signature && getReturnTypeOfSignature(signature);
44735         }
44736         function containsArgumentsReference(declaration) {
44737             var links = getNodeLinks(declaration);
44738             if (links.containsArgumentsReference === undefined) {
44739                 if (links.flags & 8192 /* CaptureArguments */) {
44740                     links.containsArgumentsReference = true;
44741                 }
44742                 else {
44743                     links.containsArgumentsReference = traverse(declaration.body);
44744                 }
44745             }
44746             return links.containsArgumentsReference;
44747             function traverse(node) {
44748                 if (!node)
44749                     return false;
44750                 switch (node.kind) {
44751                     case 75 /* Identifier */:
44752                         return node.escapedText === "arguments" && ts.isExpressionNode(node);
44753                     case 159 /* PropertyDeclaration */:
44754                     case 161 /* MethodDeclaration */:
44755                     case 163 /* GetAccessor */:
44756                     case 164 /* SetAccessor */:
44757                         return node.name.kind === 154 /* ComputedPropertyName */
44758                             && traverse(node.name);
44759                     default:
44760                         return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
44761                 }
44762             }
44763         }
44764         function getSignaturesOfSymbol(symbol) {
44765             if (!symbol)
44766                 return ts.emptyArray;
44767             var result = [];
44768             for (var i = 0; i < symbol.declarations.length; i++) {
44769                 var decl = symbol.declarations[i];
44770                 if (!ts.isFunctionLike(decl))
44771                     continue;
44772                 // Don't include signature if node is the implementation of an overloaded function. A node is considered
44773                 // an implementation node if it has a body and the previous node is of the same kind and immediately
44774                 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
44775                 if (i > 0 && decl.body) {
44776                     var previous = symbol.declarations[i - 1];
44777                     if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
44778                         continue;
44779                     }
44780                 }
44781                 result.push(getSignatureFromDeclaration(decl));
44782             }
44783             return result;
44784         }
44785         function resolveExternalModuleTypeByLiteral(name) {
44786             var moduleSym = resolveExternalModuleName(name, name);
44787             if (moduleSym) {
44788                 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
44789                 if (resolvedModuleSymbol) {
44790                     return getTypeOfSymbol(resolvedModuleSymbol);
44791                 }
44792             }
44793             return anyType;
44794         }
44795         function getThisTypeOfSignature(signature) {
44796             if (signature.thisParameter) {
44797                 return getTypeOfSymbol(signature.thisParameter);
44798             }
44799         }
44800         function getTypePredicateOfSignature(signature) {
44801             if (!signature.resolvedTypePredicate) {
44802                 if (signature.target) {
44803                     var targetTypePredicate = getTypePredicateOfSignature(signature.target);
44804                     signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
44805                 }
44806                 else if (signature.unionSignatures) {
44807                     signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
44808                 }
44809                 else {
44810                     var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
44811                     var jsdocPredicate = void 0;
44812                     if (!type && ts.isInJSFile(signature.declaration)) {
44813                         var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
44814                         if (jsdocSignature && signature !== jsdocSignature) {
44815                             jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
44816                         }
44817                     }
44818                     signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
44819                         createTypePredicateFromTypePredicateNode(type, signature) :
44820                         jsdocPredicate || noTypePredicate;
44821                 }
44822                 ts.Debug.assert(!!signature.resolvedTypePredicate);
44823             }
44824             return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
44825         }
44826         function createTypePredicateFromTypePredicateNode(node, signature) {
44827             var parameterName = node.parameterName;
44828             var type = node.type && getTypeFromTypeNode(node.type);
44829             return parameterName.kind === 183 /* ThisType */ ?
44830                 createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
44831                 createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
44832         }
44833         function getReturnTypeOfSignature(signature) {
44834             if (!signature.resolvedReturnType) {
44835                 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
44836                     return errorType;
44837                 }
44838                 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
44839                     signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
44840                         getReturnTypeFromAnnotation(signature.declaration) ||
44841                             (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
44842                 if (signature.flags & 4 /* IsInnerCallChain */) {
44843                     type = addOptionalTypeMarker(type);
44844                 }
44845                 else if (signature.flags & 8 /* IsOuterCallChain */) {
44846                     type = getOptionalType(type);
44847                 }
44848                 if (!popTypeResolution()) {
44849                     if (signature.declaration) {
44850                         var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
44851                         if (typeNode) {
44852                             error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
44853                         }
44854                         else if (noImplicitAny) {
44855                             var declaration = signature.declaration;
44856                             var name = ts.getNameOfDeclaration(declaration);
44857                             if (name) {
44858                                 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));
44859                             }
44860                             else {
44861                                 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);
44862                             }
44863                         }
44864                     }
44865                     type = anyType;
44866                 }
44867                 signature.resolvedReturnType = type;
44868             }
44869             return signature.resolvedReturnType;
44870         }
44871         function getReturnTypeFromAnnotation(declaration) {
44872             if (declaration.kind === 162 /* Constructor */) {
44873                 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
44874             }
44875             if (ts.isJSDocConstructSignature(declaration)) {
44876                 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
44877             }
44878             var typeNode = ts.getEffectiveReturnTypeNode(declaration);
44879             if (typeNode) {
44880                 return getTypeFromTypeNode(typeNode);
44881             }
44882             if (declaration.kind === 163 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
44883                 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
44884                 if (jsDocType) {
44885                     return jsDocType;
44886                 }
44887                 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 164 /* SetAccessor */);
44888                 var setterType = getAnnotatedAccessorType(setter);
44889                 if (setterType) {
44890                     return setterType;
44891                 }
44892             }
44893             return getReturnTypeOfTypeTag(declaration);
44894         }
44895         function isResolvingReturnTypeOfSignature(signature) {
44896             return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
44897         }
44898         function getRestTypeOfSignature(signature) {
44899             return tryGetRestTypeOfSignature(signature) || anyType;
44900         }
44901         function tryGetRestTypeOfSignature(signature) {
44902             if (signatureHasRestParameter(signature)) {
44903                 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
44904                 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
44905                 return restType && getIndexTypeOfType(restType, 1 /* Number */);
44906             }
44907             return undefined;
44908         }
44909         function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
44910             var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
44911             if (inferredTypeParameters) {
44912                 var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
44913                 if (returnSignature) {
44914                     var newReturnSignature = cloneSignature(returnSignature);
44915                     newReturnSignature.typeParameters = inferredTypeParameters;
44916                     var newInstantiatedSignature = cloneSignature(instantiatedSignature);
44917                     newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
44918                     return newInstantiatedSignature;
44919                 }
44920             }
44921             return instantiatedSignature;
44922         }
44923         function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
44924             var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
44925             var id = getTypeListId(typeArguments);
44926             var instantiation = instantiations.get(id);
44927             if (!instantiation) {
44928                 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
44929             }
44930             return instantiation;
44931         }
44932         function createSignatureInstantiation(signature, typeArguments) {
44933             return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
44934         }
44935         function createSignatureTypeMapper(signature, typeArguments) {
44936             return createTypeMapper(signature.typeParameters, typeArguments);
44937         }
44938         function getErasedSignature(signature) {
44939             return signature.typeParameters ?
44940                 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
44941                 signature;
44942         }
44943         function createErasedSignature(signature) {
44944             // Create an instantiation of the signature where all type arguments are the any type.
44945             return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
44946         }
44947         function getCanonicalSignature(signature) {
44948             return signature.typeParameters ?
44949                 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
44950                 signature;
44951         }
44952         function createCanonicalSignature(signature) {
44953             // Create an instantiation of the signature where each unconstrained type parameter is replaced with
44954             // its original. When a generic class or interface is instantiated, each generic method in the class or
44955             // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
44956             // where different generations of the same type parameter are in scope). This leads to a lot of new type
44957             // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
44958             // that uses the original type identities for all unconstrained type parameters.
44959             return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
44960         }
44961         function getBaseSignature(signature) {
44962             var typeParameters = signature.typeParameters;
44963             if (typeParameters) {
44964                 var typeEraser_1 = createTypeEraser(typeParameters);
44965                 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; });
44966                 return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
44967             }
44968             return signature;
44969         }
44970         function getOrCreateTypeFromSignature(signature) {
44971             // There are two ways to declare a construct signature, one is by declaring a class constructor
44972             // using the constructor keyword, and the other is declaring a bare construct signature in an
44973             // object type literal or interface (using the new keyword). Each way of declaring a constructor
44974             // will result in a different declaration kind.
44975             if (!signature.isolatedSignatureType) {
44976                 var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
44977                 var isConstructor = kind === 162 /* Constructor */ || kind === 166 /* ConstructSignature */ || kind === 171 /* ConstructorType */;
44978                 var type = createObjectType(16 /* Anonymous */);
44979                 type.members = emptySymbols;
44980                 type.properties = ts.emptyArray;
44981                 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
44982                 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
44983                 signature.isolatedSignatureType = type;
44984             }
44985             return signature.isolatedSignatureType;
44986         }
44987         function getIndexSymbol(symbol) {
44988             return symbol.members.get("__index" /* Index */);
44989         }
44990         function getIndexDeclarationOfSymbol(symbol, kind) {
44991             var syntaxKind = kind === 1 /* Number */ ? 140 /* NumberKeyword */ : 143 /* StringKeyword */;
44992             var indexSymbol = getIndexSymbol(symbol);
44993             if (indexSymbol) {
44994                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
44995                     var decl = _a[_i];
44996                     var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
44997                     if (node.parameters.length === 1) {
44998                         var parameter = node.parameters[0];
44999                         if (parameter.type && parameter.type.kind === syntaxKind) {
45000                             return node;
45001                         }
45002                     }
45003                 }
45004             }
45005             return undefined;
45006         }
45007         function createIndexInfo(type, isReadonly, declaration) {
45008             return { type: type, isReadonly: isReadonly, declaration: declaration };
45009         }
45010         function getIndexInfoOfSymbol(symbol, kind) {
45011             var declaration = getIndexDeclarationOfSymbol(symbol, kind);
45012             if (declaration) {
45013                 return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration);
45014             }
45015             return undefined;
45016         }
45017         function getConstraintDeclaration(type) {
45018             return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
45019         }
45020         function getInferredTypeParameterConstraint(typeParameter) {
45021             var inferences;
45022             if (typeParameter.symbol) {
45023                 for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
45024                     var declaration = _a[_i];
45025                     if (declaration.parent.kind === 181 /* InferType */) {
45026                         // When an 'infer T' declaration is immediately contained in a type reference node
45027                         // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
45028                         // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
45029                         // present, we form an intersection of the inferred constraint types.
45030                         var grandParent = declaration.parent.parent;
45031                         if (grandParent.kind === 169 /* TypeReference */) {
45032                             var typeReference = grandParent;
45033                             var typeParameters = getTypeParametersForTypeReference(typeReference);
45034                             if (typeParameters) {
45035                                 var index = typeReference.typeArguments.indexOf(declaration.parent);
45036                                 if (index < typeParameters.length) {
45037                                     var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
45038                                     if (declaredConstraint) {
45039                                         // Type parameter constraints can reference other type parameters so
45040                                         // constraints need to be instantiated. If instantiation produces the
45041                                         // type parameter itself, we discard that inference. For example, in
45042                                         //   type Foo<T extends string, U extends T> = [T, U];
45043                                         //   type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
45044                                         // the instantiated constraint for U is X, so we discard that inference.
45045                                         var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
45046                                         var constraint = instantiateType(declaredConstraint, mapper);
45047                                         if (constraint !== typeParameter) {
45048                                             inferences = ts.append(inferences, constraint);
45049                                         }
45050                                     }
45051                                 }
45052                             }
45053                         }
45054                         // When an 'infer T' declaration is immediately contained in a rest parameter
45055                         // declaration, we infer an 'unknown[]' constraint.
45056                         else if (grandParent.kind === 156 /* Parameter */ && grandParent.dotDotDotToken) {
45057                             inferences = ts.append(inferences, createArrayType(unknownType));
45058                         }
45059                     }
45060                 }
45061             }
45062             return inferences && getIntersectionType(inferences);
45063         }
45064         /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
45065         function getConstraintFromTypeParameter(typeParameter) {
45066             if (!typeParameter.constraint) {
45067                 if (typeParameter.target) {
45068                     var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
45069                     typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
45070                 }
45071                 else {
45072                     var constraintDeclaration = getConstraintDeclaration(typeParameter);
45073                     if (!constraintDeclaration) {
45074                         typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
45075                     }
45076                     else {
45077                         var type = getTypeFromTypeNode(constraintDeclaration);
45078                         if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed
45079                             // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was),
45080                             // use unknown otherwise
45081                             type = constraintDeclaration.parent.parent.kind === 186 /* MappedType */ ? keyofConstraintType : unknownType;
45082                         }
45083                         typeParameter.constraint = type;
45084                     }
45085                 }
45086             }
45087             return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
45088         }
45089         function getParentSymbolOfTypeParameter(typeParameter) {
45090             var tp = ts.getDeclarationOfKind(typeParameter.symbol, 155 /* TypeParameter */);
45091             var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
45092             return host && getSymbolOfNode(host);
45093         }
45094         function getTypeListId(types) {
45095             var result = "";
45096             if (types) {
45097                 var length_4 = types.length;
45098                 var i = 0;
45099                 while (i < length_4) {
45100                     var startId = types[i].id;
45101                     var count = 1;
45102                     while (i + count < length_4 && types[i + count].id === startId + count) {
45103                         count++;
45104                     }
45105                     if (result.length) {
45106                         result += ",";
45107                     }
45108                     result += startId;
45109                     if (count > 1) {
45110                         result += ":" + count;
45111                     }
45112                     i += count;
45113                 }
45114             }
45115             return result;
45116         }
45117         // This function is used to propagate certain flags when creating new object type references and union types.
45118         // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
45119         // of an object literal or the anyFunctionType. This is because there are operations in the type checker
45120         // that care about the presence of such types at arbitrary depth in a containing type.
45121         function getPropagatingFlagsOfTypes(types, excludeKinds) {
45122             var result = 0;
45123             for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
45124                 var type = types_8[_i];
45125                 if (!(type.flags & excludeKinds)) {
45126                     result |= ts.getObjectFlags(type);
45127                 }
45128             }
45129             return result & 3670016 /* PropagatingFlags */;
45130         }
45131         function createTypeReference(target, typeArguments) {
45132             var id = getTypeListId(typeArguments);
45133             var type = target.instantiations.get(id);
45134             if (!type) {
45135                 type = createObjectType(4 /* Reference */, target.symbol);
45136                 target.instantiations.set(id, type);
45137                 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
45138                 type.target = target;
45139                 type.resolvedTypeArguments = typeArguments;
45140             }
45141             return type;
45142         }
45143         function cloneTypeReference(source) {
45144             var type = createType(source.flags);
45145             type.symbol = source.symbol;
45146             type.objectFlags = source.objectFlags;
45147             type.target = source.target;
45148             type.resolvedTypeArguments = source.resolvedTypeArguments;
45149             return type;
45150         }
45151         function createDeferredTypeReference(target, node, mapper) {
45152             var aliasSymbol = getAliasSymbolForTypeNode(node);
45153             var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
45154             var type = createObjectType(4 /* Reference */, target.symbol);
45155             type.target = target;
45156             type.node = node;
45157             type.mapper = mapper;
45158             type.aliasSymbol = aliasSymbol;
45159             type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments;
45160             return type;
45161         }
45162         function getTypeArguments(type) {
45163             var _a, _b;
45164             if (!type.resolvedTypeArguments) {
45165                 if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
45166                     return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
45167                 }
45168                 var node = type.node;
45169                 var typeArguments = !node ? ts.emptyArray :
45170                     node.kind === 169 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
45171                         node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
45172                             ts.map(node.elementTypes, getTypeFromTypeNode);
45173                 if (popTypeResolution()) {
45174                     type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
45175                 }
45176                 else {
45177                     type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
45178                     error(type.node || currentNode, type.target.symbol
45179                         ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves
45180                         : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol));
45181                 }
45182             }
45183             return type.resolvedTypeArguments;
45184         }
45185         function getTypeReferenceArity(type) {
45186             return ts.length(type.target.typeParameters);
45187         }
45188         /**
45189          * Get type from type-reference that reference to class or interface
45190          */
45191         function getTypeFromClassOrInterfaceReference(node, symbol) {
45192             var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
45193             var typeParameters = type.localTypeParameters;
45194             if (typeParameters) {
45195                 var numTypeArguments = ts.length(node.typeArguments);
45196                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45197                 var isJs = ts.isInJSFile(node);
45198                 var isJsImplicitAny = !noImplicitAny && isJs;
45199                 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
45200                     var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
45201                     var diag = minTypeArgumentCount === typeParameters.length ?
45202                         missingAugmentsTag ?
45203                             ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
45204                             ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45205                         missingAugmentsTag ?
45206                             ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
45207                             ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
45208                     var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
45209                     error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
45210                     if (!isJs) {
45211                         // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
45212                         return errorType;
45213                     }
45214                 }
45215                 if (node.kind === 169 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) {
45216                     return createDeferredTypeReference(type, node, /*mapper*/ undefined);
45217                 }
45218                 // In a type reference, the outer type parameters of the referenced class or interface are automatically
45219                 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
45220                 // of the class or interface.
45221                 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
45222                 return createTypeReference(type, typeArguments);
45223             }
45224             return checkNoTypeArguments(node, symbol) ? type : errorType;
45225         }
45226         function getTypeAliasInstantiation(symbol, typeArguments) {
45227             var type = getDeclaredTypeOfSymbol(symbol);
45228             var links = getSymbolLinks(symbol);
45229             var typeParameters = links.typeParameters;
45230             var id = getTypeListId(typeArguments);
45231             var instantiation = links.instantiations.get(id);
45232             if (!instantiation) {
45233                 links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
45234             }
45235             return instantiation;
45236         }
45237         /**
45238          * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
45239          * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
45240          * declared type. Instantiations are cached using the type identities of the type arguments as the key.
45241          */
45242         function getTypeFromTypeAliasReference(node, symbol) {
45243             var type = getDeclaredTypeOfSymbol(symbol);
45244             var typeParameters = getSymbolLinks(symbol).typeParameters;
45245             if (typeParameters) {
45246                 var numTypeArguments = ts.length(node.typeArguments);
45247                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45248                 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
45249                     error(node, minTypeArgumentCount === typeParameters.length ?
45250                         ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45251                         ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
45252                     return errorType;
45253                 }
45254                 return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node));
45255             }
45256             return checkNoTypeArguments(node, symbol) ? type : errorType;
45257         }
45258         function getTypeReferenceName(node) {
45259             switch (node.kind) {
45260                 case 169 /* TypeReference */:
45261                     return node.typeName;
45262                 case 216 /* ExpressionWithTypeArguments */:
45263                     // We only support expressions that are simple qualified names. For other
45264                     // expressions this produces undefined.
45265                     var expr = node.expression;
45266                     if (ts.isEntityNameExpression(expr)) {
45267                         return expr;
45268                     }
45269                 // fall through;
45270             }
45271             return undefined;
45272         }
45273         function resolveTypeReferenceName(typeReferenceName, meaning, ignoreErrors) {
45274             if (!typeReferenceName) {
45275                 return unknownSymbol;
45276             }
45277             return resolveEntityName(typeReferenceName, meaning, ignoreErrors) || unknownSymbol;
45278         }
45279         function getTypeReferenceType(node, symbol) {
45280             if (symbol === unknownSymbol) {
45281                 return errorType;
45282             }
45283             symbol = getExpandoSymbol(symbol) || symbol;
45284             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
45285                 return getTypeFromClassOrInterfaceReference(node, symbol);
45286             }
45287             if (symbol.flags & 524288 /* TypeAlias */) {
45288                 return getTypeFromTypeAliasReference(node, symbol);
45289             }
45290             // Get type from reference to named type that cannot be generic (enum or type parameter)
45291             var res = tryGetDeclaredTypeOfSymbol(symbol);
45292             if (res) {
45293                 return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
45294             }
45295             if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
45296                 var jsdocType = getTypeFromJSDocValueReference(node, symbol);
45297                 if (jsdocType) {
45298                     return jsdocType;
45299                 }
45300                 else {
45301                     // Resolve the type reference as a Type for the purpose of reporting errors.
45302                     resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */);
45303                     return getTypeOfSymbol(symbol);
45304                 }
45305             }
45306             return errorType;
45307         }
45308         /**
45309          * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
45310          * Note: If the value is imported from commonjs, it should really be an alias,
45311          * but this function's special-case code fakes alias resolution as well.
45312          */
45313         function getTypeFromJSDocValueReference(node, symbol) {
45314             var links = getNodeLinks(node);
45315             if (!links.resolvedJSDocType) {
45316                 var valueType = getTypeOfSymbol(symbol);
45317                 var typeType = valueType;
45318                 if (symbol.valueDeclaration) {
45319                     var decl = ts.getRootDeclaration(symbol.valueDeclaration);
45320                     var isRequireAlias = false;
45321                     if (ts.isVariableDeclaration(decl) && decl.initializer) {
45322                         var expr = decl.initializer;
45323                         // skip past entity names, eg `require("x").a.b.c`
45324                         while (ts.isPropertyAccessExpression(expr)) {
45325                             expr = expr.expression;
45326                         }
45327                         isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol;
45328                     }
45329                     var isImportTypeWithQualifier = node.kind === 188 /* ImportType */ && node.qualifier;
45330                     // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
45331                     if (valueType.symbol && (isRequireAlias || isImportTypeWithQualifier)) {
45332                         typeType = getTypeReferenceType(node, valueType.symbol);
45333                     }
45334                 }
45335                 links.resolvedJSDocType = typeType;
45336             }
45337             return links.resolvedJSDocType;
45338         }
45339         function getSubstitutionType(baseType, substitute) {
45340             if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) {
45341                 return baseType;
45342             }
45343             var id = getTypeId(baseType) + ">" + getTypeId(substitute);
45344             var cached = substitutionTypes.get(id);
45345             if (cached) {
45346                 return cached;
45347             }
45348             var result = createType(33554432 /* Substitution */);
45349             result.baseType = baseType;
45350             result.substitute = substitute;
45351             substitutionTypes.set(id, result);
45352             return result;
45353         }
45354         function isUnaryTupleTypeNode(node) {
45355             return node.kind === 175 /* TupleType */ && node.elementTypes.length === 1;
45356         }
45357         function getImpliedConstraint(type, checkNode, extendsNode) {
45358             return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elementTypes[0], extendsNode.elementTypes[0]) :
45359                 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) :
45360                     undefined;
45361         }
45362         function getConditionalFlowTypeOfType(type, node) {
45363             var constraints;
45364             while (node && !ts.isStatement(node) && node.kind !== 303 /* JSDocComment */) {
45365                 var parent = node.parent;
45366                 if (parent.kind === 180 /* ConditionalType */ && node === parent.trueType) {
45367                     var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
45368                     if (constraint) {
45369                         constraints = ts.append(constraints, constraint);
45370                     }
45371                 }
45372                 node = parent;
45373             }
45374             return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type;
45375         }
45376         function isJSDocTypeReference(node) {
45377             return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 169 /* TypeReference */ || node.kind === 188 /* ImportType */);
45378         }
45379         function checkNoTypeArguments(node, symbol) {
45380             if (node.typeArguments) {
45381                 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
45382                 return false;
45383             }
45384             return true;
45385         }
45386         function getIntendedTypeFromJSDocTypeReference(node) {
45387             if (ts.isIdentifier(node.typeName)) {
45388                 var typeArgs = node.typeArguments;
45389                 switch (node.typeName.escapedText) {
45390                     case "String":
45391                         checkNoTypeArguments(node);
45392                         return stringType;
45393                     case "Number":
45394                         checkNoTypeArguments(node);
45395                         return numberType;
45396                     case "Boolean":
45397                         checkNoTypeArguments(node);
45398                         return booleanType;
45399                     case "Void":
45400                         checkNoTypeArguments(node);
45401                         return voidType;
45402                     case "Undefined":
45403                         checkNoTypeArguments(node);
45404                         return undefinedType;
45405                     case "Null":
45406                         checkNoTypeArguments(node);
45407                         return nullType;
45408                     case "Function":
45409                     case "function":
45410                         checkNoTypeArguments(node);
45411                         return globalFunctionType;
45412                     case "array":
45413                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
45414                     case "promise":
45415                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
45416                     case "Object":
45417                         if (typeArgs && typeArgs.length === 2) {
45418                             if (ts.isJSDocIndexSignature(node)) {
45419                                 var indexed = getTypeFromTypeNode(typeArgs[0]);
45420                                 var target = getTypeFromTypeNode(typeArgs[1]);
45421                                 var index = createIndexInfo(target, /*isReadonly*/ false);
45422                                 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
45423                             }
45424                             return anyType;
45425                         }
45426                         checkNoTypeArguments(node);
45427                         return !noImplicitAny ? anyType : undefined;
45428                 }
45429             }
45430         }
45431         function getTypeFromJSDocNullableTypeNode(node) {
45432             var type = getTypeFromTypeNode(node.type);
45433             return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
45434         }
45435         function getTypeFromTypeReference(node) {
45436             var links = getNodeLinks(node);
45437             if (!links.resolvedType) {
45438                 // handle LS queries on the `const` in `x as const` by resolving to the type of `x`
45439                 if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) {
45440                     links.resolvedSymbol = unknownSymbol;
45441                     return links.resolvedType = checkExpressionCached(node.parent.expression);
45442                 }
45443                 var symbol = void 0;
45444                 var type = void 0;
45445                 var meaning = 788968 /* Type */;
45446                 if (isJSDocTypeReference(node)) {
45447                     type = getIntendedTypeFromJSDocTypeReference(node);
45448                     if (!type) {
45449                         symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning, /*ignoreErrors*/ true);
45450                         if (symbol === unknownSymbol) {
45451                             symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning | 111551 /* Value */);
45452                         }
45453                         else {
45454                             resolveTypeReferenceName(getTypeReferenceName(node), meaning); // Resolve again to mark errors, if any
45455                         }
45456                         type = getTypeReferenceType(node, symbol);
45457                     }
45458                 }
45459                 if (!type) {
45460                     symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
45461                     type = getTypeReferenceType(node, symbol);
45462                 }
45463                 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
45464                 // type reference in checkTypeReferenceNode.
45465                 links.resolvedSymbol = symbol;
45466                 links.resolvedType = type;
45467             }
45468             return links.resolvedType;
45469         }
45470         function typeArgumentsFromTypeReferenceNode(node) {
45471             return ts.map(node.typeArguments, getTypeFromTypeNode);
45472         }
45473         function getTypeFromTypeQueryNode(node) {
45474             var links = getNodeLinks(node);
45475             if (!links.resolvedType) {
45476                 // TypeScript 1.0 spec (April 2014): 3.6.3
45477                 // The expression is processed as an identifier expression (section 4.3)
45478                 // or property access expression(section 4.10),
45479                 // the widened type(section 3.9) of which becomes the result.
45480                 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
45481             }
45482             return links.resolvedType;
45483         }
45484         function getTypeOfGlobalSymbol(symbol, arity) {
45485             function getTypeDeclaration(symbol) {
45486                 var declarations = symbol.declarations;
45487                 for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
45488                     var declaration = declarations_3[_i];
45489                     switch (declaration.kind) {
45490                         case 245 /* ClassDeclaration */:
45491                         case 246 /* InterfaceDeclaration */:
45492                         case 248 /* EnumDeclaration */:
45493                             return declaration;
45494                     }
45495                 }
45496             }
45497             if (!symbol) {
45498                 return arity ? emptyGenericType : emptyObjectType;
45499             }
45500             var type = getDeclaredTypeOfSymbol(symbol);
45501             if (!(type.flags & 524288 /* Object */)) {
45502                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
45503                 return arity ? emptyGenericType : emptyObjectType;
45504             }
45505             if (ts.length(type.typeParameters) !== arity) {
45506                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
45507                 return arity ? emptyGenericType : emptyObjectType;
45508             }
45509             return type;
45510         }
45511         function getGlobalValueSymbol(name, reportErrors) {
45512             return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
45513         }
45514         function getGlobalTypeSymbol(name, reportErrors) {
45515             return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
45516         }
45517         function getGlobalSymbol(name, meaning, diagnostic) {
45518             // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
45519             return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
45520         }
45521         function getGlobalType(name, arity, reportErrors) {
45522             var symbol = getGlobalTypeSymbol(name, reportErrors);
45523             return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
45524         }
45525         function getGlobalTypedPropertyDescriptorType() {
45526             return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
45527         }
45528         function getGlobalTemplateStringsArrayType() {
45529             return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45530         }
45531         function getGlobalImportMetaType() {
45532             return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45533         }
45534         function getGlobalESSymbolConstructorSymbol(reportErrors) {
45535             return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
45536         }
45537         function getGlobalESSymbolType(reportErrors) {
45538             return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
45539         }
45540         function getGlobalPromiseType(reportErrors) {
45541             return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
45542         }
45543         function getGlobalPromiseLikeType(reportErrors) {
45544             return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
45545         }
45546         function getGlobalPromiseConstructorSymbol(reportErrors) {
45547             return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
45548         }
45549         function getGlobalPromiseConstructorLikeType(reportErrors) {
45550             return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
45551         }
45552         function getGlobalAsyncIterableType(reportErrors) {
45553             return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45554         }
45555         function getGlobalAsyncIteratorType(reportErrors) {
45556             return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45557         }
45558         function getGlobalAsyncIterableIteratorType(reportErrors) {
45559             return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45560         }
45561         function getGlobalAsyncGeneratorType(reportErrors) {
45562             return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45563         }
45564         function getGlobalIterableType(reportErrors) {
45565             return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45566         }
45567         function getGlobalIteratorType(reportErrors) {
45568             return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45569         }
45570         function getGlobalIterableIteratorType(reportErrors) {
45571             return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45572         }
45573         function getGlobalGeneratorType(reportErrors) {
45574             return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45575         }
45576         function getGlobalIteratorYieldResultType(reportErrors) {
45577             return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45578         }
45579         function getGlobalIteratorReturnResultType(reportErrors) {
45580             return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45581         }
45582         function getGlobalTypeOrUndefined(name, arity) {
45583             if (arity === void 0) { arity = 0; }
45584             var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
45585             return symbol && getTypeOfGlobalSymbol(symbol, arity);
45586         }
45587         function getGlobalExtractSymbol() {
45588             return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45589         }
45590         function getGlobalOmitSymbol() {
45591             return deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalSymbol("Omit", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45592         }
45593         function getGlobalBigIntType(reportErrors) {
45594             return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
45595         }
45596         /**
45597          * Instantiates a global type that is generic with some element type, and returns that instantiation.
45598          */
45599         function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
45600             return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
45601         }
45602         function createTypedPropertyDescriptorType(propertyType) {
45603             return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
45604         }
45605         function createIterableType(iteratedType) {
45606             return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
45607         }
45608         function createArrayType(elementType, readonly) {
45609             return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
45610         }
45611         function getArrayOrTupleTargetType(node) {
45612             var readonly = isReadonlyTypeOperator(node.parent);
45613             if (node.kind === 174 /* ArrayType */ || node.elementTypes.length === 1 && node.elementTypes[0].kind === 177 /* RestType */) {
45614                 return readonly ? globalReadonlyArrayType : globalArrayType;
45615             }
45616             var lastElement = ts.lastOrUndefined(node.elementTypes);
45617             var restElement = lastElement && lastElement.kind === 177 /* RestType */ ? lastElement : undefined;
45618             var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 176 /* OptionalType */ && n !== restElement; }) + 1;
45619             return getTupleTypeOfArity(node.elementTypes.length, minLength, !!restElement, readonly, /*associatedNames*/ undefined);
45620         }
45621         // Return true if the given type reference node is directly aliased or if it needs to be deferred
45622         // because it is possibly contained in a circular chain of eagerly resolved types.
45623         function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
45624             return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 174 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) :
45625                 node.kind === 175 /* TupleType */ ? ts.some(node.elementTypes, mayResolveTypeAlias) :
45626                     hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias));
45627         }
45628         // Return true when the given node is transitively contained in type constructs that eagerly
45629         // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
45630         // of type aliases are eagerly resolved.
45631         function isResolvedByTypeAlias(node) {
45632             var parent = node.parent;
45633             switch (parent.kind) {
45634                 case 182 /* ParenthesizedType */:
45635                 case 169 /* TypeReference */:
45636                 case 178 /* UnionType */:
45637                 case 179 /* IntersectionType */:
45638                 case 185 /* IndexedAccessType */:
45639                 case 180 /* ConditionalType */:
45640                 case 184 /* TypeOperator */:
45641                 case 174 /* ArrayType */:
45642                 case 175 /* TupleType */:
45643                     return isResolvedByTypeAlias(parent);
45644                 case 247 /* TypeAliasDeclaration */:
45645                     return true;
45646             }
45647             return false;
45648         }
45649         // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution
45650         // of a type alias.
45651         function mayResolveTypeAlias(node) {
45652             switch (node.kind) {
45653                 case 169 /* TypeReference */:
45654                     return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */);
45655                 case 172 /* TypeQuery */:
45656                     return true;
45657                 case 184 /* TypeOperator */:
45658                     return node.operator !== 147 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
45659                 case 182 /* ParenthesizedType */:
45660                 case 176 /* OptionalType */:
45661                 case 299 /* JSDocOptionalType */:
45662                 case 297 /* JSDocNullableType */:
45663                 case 298 /* JSDocNonNullableType */:
45664                 case 294 /* JSDocTypeExpression */:
45665                     return mayResolveTypeAlias(node.type);
45666                 case 177 /* RestType */:
45667                     return node.type.kind !== 174 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
45668                 case 178 /* UnionType */:
45669                 case 179 /* IntersectionType */:
45670                     return ts.some(node.types, mayResolveTypeAlias);
45671                 case 185 /* IndexedAccessType */:
45672                     return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
45673                 case 180 /* ConditionalType */:
45674                     return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) ||
45675                         mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
45676             }
45677             return false;
45678         }
45679         function getTypeFromArrayOrTupleTypeNode(node) {
45680             var links = getNodeLinks(node);
45681             if (!links.resolvedType) {
45682                 var target = getArrayOrTupleTargetType(node);
45683                 if (target === emptyGenericType) {
45684                     links.resolvedType = emptyObjectType;
45685                 }
45686                 else if (isDeferredTypeReferenceNode(node)) {
45687                     links.resolvedType = node.kind === 175 /* TupleType */ && node.elementTypes.length === 0 ? target :
45688                         createDeferredTypeReference(target, node, /*mapper*/ undefined);
45689                 }
45690                 else {
45691                     var elementTypes = node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode);
45692                     links.resolvedType = createTypeReference(target, elementTypes);
45693                 }
45694             }
45695             return links.resolvedType;
45696         }
45697         function isReadonlyTypeOperator(node) {
45698             return ts.isTypeOperatorNode(node) && node.operator === 138 /* ReadonlyKeyword */;
45699         }
45700         // We represent tuple types as type references to synthesized generic interface types created by
45701         // this function. The types are of the form:
45702         //
45703         //   interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
45704         //
45705         // Note that the generic type created by this function has no symbol associated with it. The same
45706         // is true for each of the synthesized type parameters.
45707         function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45708             var typeParameters;
45709             var properties = [];
45710             var maxLength = hasRestElement ? arity - 1 : arity;
45711             if (arity) {
45712                 typeParameters = new Array(arity);
45713                 for (var i = 0; i < arity; i++) {
45714                     var typeParameter = typeParameters[i] = createTypeParameter();
45715                     if (i < maxLength) {
45716                         var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
45717                         property.type = typeParameter;
45718                         properties.push(property);
45719                     }
45720                 }
45721             }
45722             var literalTypes = [];
45723             for (var i = minLength; i <= maxLength; i++)
45724                 literalTypes.push(getLiteralType(i));
45725             var lengthSymbol = createSymbol(4 /* Property */, "length");
45726             lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes);
45727             properties.push(lengthSymbol);
45728             var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
45729             type.typeParameters = typeParameters;
45730             type.outerTypeParameters = undefined;
45731             type.localTypeParameters = typeParameters;
45732             type.instantiations = ts.createMap();
45733             type.instantiations.set(getTypeListId(type.typeParameters), type);
45734             type.target = type;
45735             type.resolvedTypeArguments = type.typeParameters;
45736             type.thisType = createTypeParameter();
45737             type.thisType.isThisType = true;
45738             type.thisType.constraint = type;
45739             type.declaredProperties = properties;
45740             type.declaredCallSignatures = ts.emptyArray;
45741             type.declaredConstructSignatures = ts.emptyArray;
45742             type.declaredStringIndexInfo = undefined;
45743             type.declaredNumberIndexInfo = undefined;
45744             type.minLength = minLength;
45745             type.hasRestElement = hasRestElement;
45746             type.readonly = readonly;
45747             type.associatedNames = associatedNames;
45748             return type;
45749         }
45750         function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45751             var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
45752             var type = tupleTypes.get(key);
45753             if (!type) {
45754                 tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
45755             }
45756             return type;
45757         }
45758         function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
45759             if (minLength === void 0) { minLength = elementTypes.length; }
45760             if (hasRestElement === void 0) { hasRestElement = false; }
45761             if (readonly === void 0) { readonly = false; }
45762             var arity = elementTypes.length;
45763             if (arity === 1 && hasRestElement) {
45764                 return createArrayType(elementTypes[0], readonly);
45765             }
45766             var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
45767             return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
45768         }
45769         function sliceTupleType(type, index) {
45770             var tuple = type.target;
45771             if (tuple.hasRestElement) {
45772                 // don't slice off rest element
45773                 index = Math.min(index, getTypeReferenceArity(type) - 1);
45774             }
45775             return createTupleType(getTypeArguments(type).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
45776         }
45777         function getTypeFromOptionalTypeNode(node) {
45778             var type = getTypeFromTypeNode(node.type);
45779             return strictNullChecks ? getOptionalType(type) : type;
45780         }
45781         function getTypeId(type) {
45782             return type.id;
45783         }
45784         function containsType(types, type) {
45785             return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
45786         }
45787         function insertType(types, type) {
45788             var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
45789             if (index < 0) {
45790                 types.splice(~index, 0, type);
45791                 return true;
45792             }
45793             return false;
45794         }
45795         function addTypeToUnion(typeSet, includes, type) {
45796             var flags = type.flags;
45797             if (flags & 1048576 /* Union */) {
45798                 return addTypesToUnion(typeSet, includes, type.types);
45799             }
45800             // We ignore 'never' types in unions
45801             if (!(flags & 131072 /* Never */)) {
45802                 includes |= flags & 71041023 /* IncludesMask */;
45803                 if (flags & 66846720 /* StructuredOrInstantiable */)
45804                     includes |= 262144 /* IncludesStructuredOrInstantiable */;
45805                 if (type === wildcardType)
45806                     includes |= 8388608 /* IncludesWildcard */;
45807                 if (!strictNullChecks && flags & 98304 /* Nullable */) {
45808                     if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */))
45809                         includes |= 4194304 /* IncludesNonWideningType */;
45810                 }
45811                 else {
45812                     var len = typeSet.length;
45813                     var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
45814                     if (index < 0) {
45815                         typeSet.splice(~index, 0, type);
45816                     }
45817                 }
45818             }
45819             return includes;
45820         }
45821         // Add the given types to the given type set. Order is preserved, duplicates are removed,
45822         // and nested types of the given kind are flattened into the set.
45823         function addTypesToUnion(typeSet, includes, types) {
45824             for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
45825                 var type = types_9[_i];
45826                 includes = addTypeToUnion(typeSet, includes, type);
45827             }
45828             return includes;
45829         }
45830         function isSetOfLiteralsFromSameEnum(types) {
45831             var first = types[0];
45832             if (first.flags & 1024 /* EnumLiteral */) {
45833                 var firstEnum = getParentOfSymbol(first.symbol);
45834                 for (var i = 1; i < types.length; i++) {
45835                     var other = types[i];
45836                     if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
45837                         return false;
45838                     }
45839                 }
45840                 return true;
45841             }
45842             return false;
45843         }
45844         function removeSubtypes(types, primitivesOnly) {
45845             var len = types.length;
45846             if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
45847                 return true;
45848             }
45849             var i = len;
45850             var count = 0;
45851             while (i > 0) {
45852                 i--;
45853                 var source = types[i];
45854                 for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
45855                     var target = types_10[_i];
45856                     if (source !== target) {
45857                         if (count === 100000) {
45858                             // After 100000 subtype checks we estimate the remaining amount of work by assuming the
45859                             // same ratio of checks per element. If the estimated number of remaining type checks is
45860                             // greater than an upper limit we deem the union type too complex to represent. The
45861                             // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
45862                             // caps union types at 5000 unique literal types and 1000 unique object types.
45863                             var estimatedCount = (count / (len - i)) * len;
45864                             if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
45865                                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
45866                                 return false;
45867                             }
45868                         }
45869                         count++;
45870                         if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
45871                             !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
45872                             isTypeDerivedFrom(source, target))) {
45873                             ts.orderedRemoveItemAt(types, i);
45874                             break;
45875                         }
45876                     }
45877                 }
45878             }
45879             return true;
45880         }
45881         function removeRedundantLiteralTypes(types, includes) {
45882             var i = types.length;
45883             while (i > 0) {
45884                 i--;
45885                 var t = types[i];
45886                 var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
45887                     t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
45888                     t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
45889                     t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
45890                     isFreshLiteralType(t) && containsType(types, t.regularType);
45891                 if (remove) {
45892                     ts.orderedRemoveItemAt(types, i);
45893                 }
45894             }
45895         }
45896         // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
45897         // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
45898         // of other types. Subtype reduction is expensive for large union types and is possible only when union
45899         // types are known not to circularly reference themselves (as is the case with union types created by
45900         // expression constructs such as array literals and the || and ?: operators). Named types can
45901         // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
45902         // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
45903         function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
45904             if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
45905             if (types.length === 0) {
45906                 return neverType;
45907             }
45908             if (types.length === 1) {
45909                 return types[0];
45910             }
45911             var typeSet = [];
45912             var includes = addTypesToUnion(typeSet, 0, types);
45913             if (unionReduction !== 0 /* None */) {
45914                 if (includes & 3 /* AnyOrUnknown */) {
45915                     return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
45916                 }
45917                 switch (unionReduction) {
45918                     case 1 /* Literal */:
45919                         if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
45920                             removeRedundantLiteralTypes(typeSet, includes);
45921                         }
45922                         break;
45923                     case 2 /* Subtype */:
45924                         if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
45925                             return errorType;
45926                         }
45927                         break;
45928                 }
45929                 if (typeSet.length === 0) {
45930                     return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
45931                         includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
45932                             neverType;
45933                 }
45934             }
45935             var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
45936                 (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0);
45937             return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments);
45938         }
45939         function getUnionTypePredicate(signatures) {
45940             var first;
45941             var types = [];
45942             for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
45943                 var sig = signatures_6[_i];
45944                 var pred = getTypePredicateOfSignature(sig);
45945                 if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
45946                     continue;
45947                 }
45948                 if (first) {
45949                     if (!typePredicateKindsMatch(first, pred)) {
45950                         // No common type predicate.
45951                         return undefined;
45952                     }
45953                 }
45954                 else {
45955                     first = pred;
45956                 }
45957                 types.push(pred.type);
45958             }
45959             if (!first) {
45960                 // No union signatures had a type predicate.
45961                 return undefined;
45962             }
45963             var unionType = getUnionType(types);
45964             return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType);
45965         }
45966         function typePredicateKindsMatch(a, b) {
45967             return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
45968         }
45969         // This function assumes the constituent type list is sorted and deduplicated.
45970         function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
45971             if (types.length === 0) {
45972                 return neverType;
45973             }
45974             if (types.length === 1) {
45975                 return types[0];
45976             }
45977             var id = getTypeListId(types);
45978             var type = unionTypes.get(id);
45979             if (!type) {
45980                 type = createType(1048576 /* Union */);
45981                 unionTypes.set(id, type);
45982                 type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
45983                 type.types = types;
45984                 /*
45985                 Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
45986                 For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
45987                 (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
45988                 It's important that we create equivalent union types only once, so that's an unfortunate side effect.
45989                 */
45990                 type.aliasSymbol = aliasSymbol;
45991                 type.aliasTypeArguments = aliasTypeArguments;
45992             }
45993             return type;
45994         }
45995         function getTypeFromUnionTypeNode(node) {
45996             var links = getNodeLinks(node);
45997             if (!links.resolvedType) {
45998                 var aliasSymbol = getAliasSymbolForTypeNode(node);
45999                 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
46000             }
46001             return links.resolvedType;
46002         }
46003         function addTypeToIntersection(typeSet, includes, type) {
46004             var flags = type.flags;
46005             if (flags & 2097152 /* Intersection */) {
46006                 return addTypesToIntersection(typeSet, includes, type.types);
46007             }
46008             if (isEmptyAnonymousObjectType(type)) {
46009                 if (!(includes & 16777216 /* IncludesEmptyObject */)) {
46010                     includes |= 16777216 /* IncludesEmptyObject */;
46011                     typeSet.set(type.id.toString(), type);
46012                 }
46013             }
46014             else {
46015                 if (flags & 3 /* AnyOrUnknown */) {
46016                     if (type === wildcardType)
46017                         includes |= 8388608 /* IncludesWildcard */;
46018                 }
46019                 else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) {
46020                     if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
46021                         // We have seen two distinct unit types which means we should reduce to an
46022                         // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
46023                         includes |= 67108864 /* NonPrimitive */;
46024                     }
46025                     typeSet.set(type.id.toString(), type);
46026                 }
46027                 includes |= flags & 71041023 /* IncludesMask */;
46028             }
46029             return includes;
46030         }
46031         // Add the given types to the given type set. Order is preserved, freshness is removed from literal
46032         // types, duplicates are removed, and nested types of the given kind are flattened into the set.
46033         function addTypesToIntersection(typeSet, includes, types) {
46034             for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
46035                 var type = types_11[_i];
46036                 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
46037             }
46038             return includes;
46039         }
46040         function removeRedundantPrimitiveTypes(types, includes) {
46041             var i = types.length;
46042             while (i > 0) {
46043                 i--;
46044                 var t = types[i];
46045                 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46046                     t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46047                     t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46048                     t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
46049                 if (remove) {
46050                     ts.orderedRemoveItemAt(types, i);
46051                 }
46052             }
46053         }
46054         // Check that the given type has a match in every union. A given type is matched by
46055         // an identical type, and a literal type is additionally matched by its corresponding
46056         // primitive type.
46057         function eachUnionContains(unionTypes, type) {
46058             for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
46059                 var u = unionTypes_1[_i];
46060                 if (!containsType(u.types, type)) {
46061                     var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
46062                         type.flags & 256 /* NumberLiteral */ ? numberType :
46063                             type.flags & 2048 /* BigIntLiteral */ ? bigintType :
46064                                 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
46065                                     undefined;
46066                     if (!primitive || !containsType(u.types, primitive)) {
46067                         return false;
46068                     }
46069                 }
46070             }
46071             return true;
46072         }
46073         function extractIrreducible(types, flag) {
46074             if (ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); })) {
46075                 for (var i = 0; i < types.length; i++) {
46076                     types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
46077                 }
46078                 return true;
46079             }
46080             return false;
46081         }
46082         // If the given list of types contains more than one union of primitive types, replace the
46083         // first with a union containing an intersection of those primitive types, then remove the
46084         // other unions and return true. Otherwise, do nothing and return false.
46085         function intersectUnionsOfPrimitiveTypes(types) {
46086             var unionTypes;
46087             var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); });
46088             if (index < 0) {
46089                 return false;
46090             }
46091             var i = index + 1;
46092             // Remove all but the first union of primitive types and collect them in
46093             // the unionTypes array.
46094             while (i < types.length) {
46095                 var t = types[i];
46096                 if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) {
46097                     (unionTypes || (unionTypes = [types[index]])).push(t);
46098                     ts.orderedRemoveItemAt(types, i);
46099                 }
46100                 else {
46101                     i++;
46102                 }
46103             }
46104             // Return false if there was only one union of primitive types
46105             if (!unionTypes) {
46106                 return false;
46107             }
46108             // We have more than one union of primitive types, now intersect them. For each
46109             // type in each union we check if the type is matched in every union and if so
46110             // we include it in the result.
46111             var checked = [];
46112             var result = [];
46113             for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
46114                 var u = unionTypes_2[_i];
46115                 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
46116                     var t = _b[_a];
46117                     if (insertType(checked, t)) {
46118                         if (eachUnionContains(unionTypes, t)) {
46119                             insertType(result, t);
46120                         }
46121                     }
46122                 }
46123             }
46124             // Finally replace the first union with the result
46125             types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */);
46126             return true;
46127         }
46128         function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46129             var result = createType(2097152 /* Intersection */);
46130             result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
46131             result.types = types;
46132             result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
46133             result.aliasTypeArguments = aliasTypeArguments;
46134             return result;
46135         }
46136         // We normalize combinations of intersection and union types based on the distributive property of the '&'
46137         // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
46138         // types with union type constituents into equivalent union types with intersection type constituents and
46139         // effectively ensure that union types are always at the top level in type representations.
46140         //
46141         // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
46142         // type operator and we can't reduce those because we want to support recursive intersection types. For example,
46143         // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
46144         // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
46145         // for intersections of types with signatures can be deterministic.
46146         function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46147             var typeMembershipMap = ts.createMap();
46148             var includes = addTypesToIntersection(typeMembershipMap, 0, types);
46149             var typeSet = ts.arrayFrom(typeMembershipMap.values());
46150             // An intersection type is considered empty if it contains
46151             // the type never, or
46152             // more than one unit type or,
46153             // an object type and a nullable type (null or undefined), or
46154             // a string-like type and a type known to be non-string-like, or
46155             // a number-like type and a type known to be non-number-like, or
46156             // a symbol-like type and a type known to be non-symbol-like, or
46157             // a void-like type and a type known to be non-void-like, or
46158             // a non-primitive type and a type known to be primitive.
46159             if (includes & 131072 /* Never */ ||
46160                 strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) ||
46161                 includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
46162                 includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) ||
46163                 includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) ||
46164                 includes & 2112 /* BigIntLike */ && includes & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
46165                 includes & 12288 /* ESSymbolLike */ && includes & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
46166                 includes & 49152 /* VoidLike */ && includes & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
46167                 return neverType;
46168             }
46169             if (includes & 1 /* Any */) {
46170                 return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType;
46171             }
46172             if (!strictNullChecks && includes & 98304 /* Nullable */) {
46173                 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
46174             }
46175             if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46176                 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46177                 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46178                 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
46179                 removeRedundantPrimitiveTypes(typeSet, includes);
46180             }
46181             if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
46182                 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
46183             }
46184             if (typeSet.length === 0) {
46185                 return unknownType;
46186             }
46187             if (typeSet.length === 1) {
46188                 return typeSet[0];
46189             }
46190             var id = getTypeListId(typeSet);
46191             var result = intersectionTypes.get(id);
46192             if (!result) {
46193                 if (includes & 1048576 /* Union */) {
46194                     if (intersectUnionsOfPrimitiveTypes(typeSet)) {
46195                         // When the intersection creates a reduced set (which might mean that *all* union types have
46196                         // disappeared), we restart the operation to get a new set of combined flags. Once we have
46197                         // reduced we'll never reduce again, so this occurs at most once.
46198                         result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46199                     }
46200                     else if (extractIrreducible(typeSet, 32768 /* Undefined */)) {
46201                         result = getUnionType([getIntersectionType(typeSet), undefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46202                     }
46203                     else if (extractIrreducible(typeSet, 65536 /* Null */)) {
46204                         result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46205                     }
46206                     else {
46207                         // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
46208                         // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
46209                         // If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
46210                         var size = ts.reduceLeft(typeSet, function (n, t) { return n * (t.flags & 1048576 /* Union */ ? t.types.length : 1); }, 1);
46211                         if (size >= 100000) {
46212                             error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
46213                             return errorType;
46214                         }
46215                         var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
46216                         var unionType = typeSet[unionIndex_1];
46217                         result = getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46218                     }
46219                 }
46220                 else {
46221                     result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46222                 }
46223                 intersectionTypes.set(id, result);
46224             }
46225             return result;
46226         }
46227         function getTypeFromIntersectionTypeNode(node) {
46228             var links = getNodeLinks(node);
46229             if (!links.resolvedType) {
46230                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46231                 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
46232             }
46233             return links.resolvedType;
46234         }
46235         function createIndexType(type, stringsOnly) {
46236             var result = createType(4194304 /* Index */);
46237             result.type = type;
46238             result.stringsOnly = stringsOnly;
46239             return result;
46240         }
46241         function getIndexTypeForGenericType(type, stringsOnly) {
46242             return stringsOnly ?
46243                 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
46244                 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
46245         }
46246         function getLiteralTypeFromPropertyName(name) {
46247             if (ts.isPrivateIdentifier(name)) {
46248                 return neverType;
46249             }
46250             return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
46251                 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
46252         }
46253         function getBigIntLiteralType(node) {
46254             return getLiteralType({
46255                 negative: false,
46256                 base10Value: ts.parsePseudoBigInt(node.text)
46257             });
46258         }
46259         function getLiteralTypeFromProperty(prop, include) {
46260             if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
46261                 var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
46262                 if (!type && !ts.isKnownSymbol(prop)) {
46263                     if (prop.escapedName === "default" /* Default */) {
46264                         type = getLiteralType("default");
46265                     }
46266                     else {
46267                         var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
46268                         type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
46269                     }
46270                 }
46271                 if (type && type.flags & include) {
46272                     return type;
46273                 }
46274             }
46275             return neverType;
46276         }
46277         function getLiteralTypeFromProperties(type, include) {
46278             return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
46279         }
46280         function getNonEnumNumberIndexInfo(type) {
46281             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
46282             return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
46283         }
46284         function getIndexType(type, stringsOnly, noIndexSignatures) {
46285             if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
46286             type = getReducedType(type);
46287             return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46288                 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46289                     maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) :
46290                         ts.getObjectFlags(type) & 32 /* Mapped */ ? filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }) :
46291                             type === wildcardType ? wildcardType :
46292                                 type.flags & 2 /* Unknown */ ? neverType :
46293                                     type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
46294                                         stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
46295                                             !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
46296                                                 getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
46297                                                     getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
46298         }
46299         function getExtractStringType(type) {
46300             if (keyofStringsOnly) {
46301                 return type;
46302             }
46303             var extractTypeAlias = getGlobalExtractSymbol();
46304             return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
46305         }
46306         function getIndexTypeOrString(type) {
46307             var indexType = getExtractStringType(getIndexType(type));
46308             return indexType.flags & 131072 /* Never */ ? stringType : indexType;
46309         }
46310         function getTypeFromTypeOperatorNode(node) {
46311             var links = getNodeLinks(node);
46312             if (!links.resolvedType) {
46313                 switch (node.operator) {
46314                     case 134 /* KeyOfKeyword */:
46315                         links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
46316                         break;
46317                     case 147 /* UniqueKeyword */:
46318                         links.resolvedType = node.type.kind === 144 /* SymbolKeyword */
46319                             ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
46320                             : errorType;
46321                         break;
46322                     case 138 /* ReadonlyKeyword */:
46323                         links.resolvedType = getTypeFromTypeNode(node.type);
46324                         break;
46325                     default:
46326                         throw ts.Debug.assertNever(node.operator);
46327                 }
46328             }
46329             return links.resolvedType;
46330         }
46331         function createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments) {
46332             var type = createType(8388608 /* IndexedAccess */);
46333             type.objectType = objectType;
46334             type.indexType = indexType;
46335             type.aliasSymbol = aliasSymbol;
46336             type.aliasTypeArguments = aliasTypeArguments;
46337             return type;
46338         }
46339         /**
46340          * Returns if a type is or consists of a JSLiteral object type
46341          * In addition to objects which are directly literals,
46342          * * unions where every element is a jsliteral
46343          * * intersections where at least one element is a jsliteral
46344          * * and instantiable types constrained to a jsliteral
46345          * Should all count as literals and not print errors on access or assignment of possibly existing properties.
46346          * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
46347          */
46348         function isJSLiteralType(type) {
46349             if (noImplicitAny) {
46350                 return false; // Flag is meaningless under `noImplicitAny` mode
46351             }
46352             if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
46353                 return true;
46354             }
46355             if (type.flags & 1048576 /* Union */) {
46356                 return ts.every(type.types, isJSLiteralType);
46357             }
46358             if (type.flags & 2097152 /* Intersection */) {
46359                 return ts.some(type.types, isJSLiteralType);
46360             }
46361             if (type.flags & 63176704 /* Instantiable */) {
46362                 return isJSLiteralType(getResolvedBaseConstraint(type));
46363             }
46364             return false;
46365         }
46366         function getPropertyNameFromIndex(indexType, accessNode) {
46367             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46368             return isTypeUsableAsPropertyName(indexType) ?
46369                 getPropertyNameFromType(indexType) :
46370                 accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
46371                     ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
46372                     accessNode && ts.isPropertyName(accessNode) ?
46373                         // late bound names are handled in the first branch, so here we only need to handle normal names
46374                         ts.getPropertyNameForPropertyNameNode(accessNode) :
46375                         undefined;
46376         }
46377         function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags) {
46378             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46379             var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
46380             if (propName !== undefined) {
46381                 var prop = getPropertyOfType(objectType, propName);
46382                 if (prop) {
46383                     if (accessExpression) {
46384                         markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 104 /* ThisKeyword */);
46385                         if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
46386                             error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
46387                             return undefined;
46388                         }
46389                         if (accessFlags & 4 /* CacheSymbol */) {
46390                             getNodeLinks(accessNode).resolvedSymbol = prop;
46391                         }
46392                     }
46393                     var propType = getTypeOfSymbol(prop);
46394                     return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
46395                         getFlowTypeOfReference(accessExpression, propType) :
46396                         propType;
46397                 }
46398                 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
46399                     if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 8 /* NoTupleBoundsCheck */)) {
46400                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46401                         if (isTupleType(objectType)) {
46402                             error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
46403                         }
46404                         else {
46405                             error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46406                         }
46407                     }
46408                     errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, 1 /* Number */));
46409                     return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
46410                 }
46411             }
46412             if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
46413                 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
46414                     return objectType;
46415                 }
46416                 var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */);
46417                 var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || stringIndexInfo;
46418                 if (indexInfo) {
46419                     if (accessFlags & 1 /* NoIndexSignatures */ && indexInfo === stringIndexInfo) {
46420                         if (accessExpression) {
46421                             error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
46422                         }
46423                         return undefined;
46424                     }
46425                     if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46426                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46427                         error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46428                         return indexInfo.type;
46429                     }
46430                     errorIfWritingToReadonlyIndex(indexInfo);
46431                     return indexInfo.type;
46432                 }
46433                 if (indexType.flags & 131072 /* Never */) {
46434                     return neverType;
46435                 }
46436                 if (isJSLiteralType(objectType)) {
46437                     return anyType;
46438                 }
46439                 if (accessExpression && !isConstEnumObjectType(objectType)) {
46440                     if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
46441                         error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46442                     }
46443                     else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
46444                         if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
46445                             error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
46446                         }
46447                         else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
46448                             error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
46449                         }
46450                         else {
46451                             var suggestion = void 0;
46452                             if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
46453                                 if (suggestion !== undefined) {
46454                                     error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
46455                                 }
46456                             }
46457                             else {
46458                                 var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
46459                                 if (suggestion_1 !== undefined) {
46460                                     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);
46461                                 }
46462                                 else {
46463                                     var errorInfo = void 0;
46464                                     if (indexType.flags & 1024 /* EnumLiteral */) {
46465                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
46466                                     }
46467                                     else if (indexType.flags & 8192 /* UniqueESSymbol */) {
46468                                         var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
46469                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
46470                                     }
46471                                     else if (indexType.flags & 128 /* StringLiteral */) {
46472                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46473                                     }
46474                                     else if (indexType.flags & 256 /* NumberLiteral */) {
46475                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46476                                     }
46477                                     else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
46478                                         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));
46479                                     }
46480                                     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));
46481                                     diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
46482                                 }
46483                             }
46484                         }
46485                     }
46486                     return undefined;
46487                 }
46488             }
46489             if (isJSLiteralType(objectType)) {
46490                 return anyType;
46491             }
46492             if (accessNode) {
46493                 var indexNode = getIndexNodeForAccessExpression(accessNode);
46494                 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
46495                     error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
46496                 }
46497                 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
46498                     error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
46499                 }
46500                 else {
46501                     error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46502                 }
46503             }
46504             if (isTypeAny(indexType)) {
46505                 return indexType;
46506             }
46507             return undefined;
46508             function errorIfWritingToReadonlyIndex(indexInfo) {
46509                 if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
46510                     error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
46511                 }
46512             }
46513         }
46514         function getIndexNodeForAccessExpression(accessNode) {
46515             return accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode.argumentExpression :
46516                 accessNode.kind === 185 /* IndexedAccessType */ ? accessNode.indexType :
46517                     accessNode.kind === 154 /* ComputedPropertyName */ ? accessNode.expression :
46518                         accessNode;
46519         }
46520         function isGenericObjectType(type) {
46521             if (type.flags & 3145728 /* UnionOrIntersection */) {
46522                 if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) {
46523                     type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ |
46524                         (ts.some(type.types, isGenericObjectType) ? 8388608 /* IsGenericObjectType */ : 0);
46525                 }
46526                 return !!(type.objectFlags & 8388608 /* IsGenericObjectType */);
46527             }
46528             return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type);
46529         }
46530         function isGenericIndexType(type) {
46531             if (type.flags & 3145728 /* UnionOrIntersection */) {
46532                 if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) {
46533                     type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ |
46534                         (ts.some(type.types, isGenericIndexType) ? 33554432 /* IsGenericIndexType */ : 0);
46535                 }
46536                 return !!(type.objectFlags & 33554432 /* IsGenericIndexType */);
46537             }
46538             return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */));
46539         }
46540         function isThisTypeParameter(type) {
46541             return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
46542         }
46543         function getSimplifiedType(type, writing) {
46544             return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
46545                 type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
46546                     type;
46547         }
46548         function distributeIndexOverObjectType(objectType, indexType, writing) {
46549             // (T | U)[K] -> T[K] | U[K] (reading)
46550             // (T | U)[K] -> T[K] & U[K] (writing)
46551             // (T & U)[K] -> T[K] & U[K]
46552             if (objectType.flags & 3145728 /* UnionOrIntersection */) {
46553                 var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
46554                 return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
46555             }
46556         }
46557         function distributeObjectOverIndexType(objectType, indexType, writing) {
46558             // T[A | B] -> T[A] | T[B] (reading)
46559             // T[A | B] -> T[A] & T[B] (writing)
46560             if (indexType.flags & 1048576 /* Union */) {
46561                 var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
46562                 return writing ? getIntersectionType(types) : getUnionType(types);
46563             }
46564         }
46565         function unwrapSubstitution(type) {
46566             if (type.flags & 33554432 /* Substitution */) {
46567                 return type.substitute;
46568             }
46569             return type;
46570         }
46571         // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
46572         // the type itself if no transformation is possible. The writing flag indicates that the type is
46573         // the target of an assignment.
46574         function getSimplifiedIndexedAccessType(type, writing) {
46575             var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
46576             if (type[cache]) {
46577                 return type[cache] === circularConstraintType ? type : type[cache];
46578             }
46579             type[cache] = circularConstraintType;
46580             // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
46581             // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
46582             var objectType = unwrapSubstitution(getSimplifiedType(type.objectType, writing));
46583             var indexType = getSimplifiedType(type.indexType, writing);
46584             // T[A | B] -> T[A] | T[B] (reading)
46585             // T[A | B] -> T[A] & T[B] (writing)
46586             var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
46587             if (distributedOverIndex) {
46588                 return type[cache] = distributedOverIndex;
46589             }
46590             // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
46591             if (!(indexType.flags & 63176704 /* Instantiable */)) {
46592                 // (T | U)[K] -> T[K] | U[K] (reading)
46593                 // (T | U)[K] -> T[K] & U[K] (writing)
46594                 // (T & U)[K] -> T[K] & U[K]
46595                 var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
46596                 if (distributedOverObject) {
46597                     return type[cache] = distributedOverObject;
46598                 }
46599             }
46600             // So ultimately (reading):
46601             // ((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]
46602             // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
46603             // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
46604             // construct the type Box<T[X]>.
46605             if (isGenericMappedType(objectType)) {
46606                 return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
46607             }
46608             return type[cache] = type;
46609         }
46610         function getSimplifiedConditionalType(type, writing) {
46611             var checkType = type.checkType;
46612             var extendsType = type.extendsType;
46613             var trueType = getTrueTypeFromConditionalType(type);
46614             var falseType = getFalseTypeFromConditionalType(type);
46615             // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
46616             if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
46617                 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46618                     return getSimplifiedType(trueType, writing);
46619                 }
46620                 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
46621                     return neverType;
46622                 }
46623             }
46624             else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
46625                 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46626                     return neverType;
46627                 }
46628                 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
46629                     return getSimplifiedType(falseType, writing);
46630                 }
46631             }
46632             return type;
46633         }
46634         /**
46635          * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
46636          */
46637         function isIntersectionEmpty(type1, type2) {
46638             return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
46639         }
46640         function substituteIndexedMappedType(objectType, index) {
46641             var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
46642             var templateMapper = combineTypeMappers(objectType.mapper, mapper);
46643             return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
46644         }
46645         function getIndexedAccessType(objectType, indexType, accessNode, aliasSymbol, aliasTypeArguments) {
46646             return getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, 0 /* None */, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType);
46647         }
46648         function getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) {
46649             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
46650             if (objectType === wildcardType || indexType === wildcardType) {
46651                 return wildcardType;
46652             }
46653             // If the object type has a string index signature and no other members we know that the result will
46654             // always be the type of that index signature and we can simplify accordingly.
46655             if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46656                 indexType = stringType;
46657             }
46658             // If the index type is generic, or if the object type is generic and doesn't originate in an expression,
46659             // we are performing a higher-order index access where we cannot meaningfully access the properties of the
46660             // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
46661             // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]'
46662             // has always been resolved eagerly using the constraint type of 'this' at the given location.
46663             if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 185 /* IndexedAccessType */) && isGenericObjectType(objectType)) {
46664                 if (objectType.flags & 3 /* AnyOrUnknown */) {
46665                     return objectType;
46666                 }
46667                 // Defer the operation by creating an indexed access type.
46668                 var id = objectType.id + "," + indexType.id;
46669                 var type = indexedAccessTypes.get(id);
46670                 if (!type) {
46671                     indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments));
46672                 }
46673                 return type;
46674             }
46675             // In the following we resolve T[K] to the type of the property in T selected by K.
46676             // We treat boolean as different from other unions to improve errors;
46677             // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
46678             var apparentObjectType = getReducedApparentType(objectType);
46679             if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
46680                 var propTypes = [];
46681                 var wasMissingProp = false;
46682                 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
46683                     var t = _a[_i];
46684                     var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags);
46685                     if (propType) {
46686                         propTypes.push(propType);
46687                     }
46688                     else if (!accessNode) {
46689                         // If there's no error node, we can immeditely stop, since error reporting is off
46690                         return undefined;
46691                     }
46692                     else {
46693                         // Otherwise we set a flag and return at the end of the loop so we still mark all errors
46694                         wasMissingProp = true;
46695                     }
46696                 }
46697                 if (wasMissingProp) {
46698                     return undefined;
46699                 }
46700                 return accessFlags & 2 /* Writing */ ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46701             }
46702             return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | 4 /* CacheSymbol */);
46703         }
46704         function getTypeFromIndexedAccessTypeNode(node) {
46705             var links = getNodeLinks(node);
46706             if (!links.resolvedType) {
46707                 var objectType = getTypeFromTypeNode(node.objectType);
46708                 var indexType = getTypeFromTypeNode(node.indexType);
46709                 var potentialAlias = getAliasSymbolForTypeNode(node);
46710                 var resolved = getIndexedAccessType(objectType, indexType, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
46711                 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
46712                     resolved.objectType === objectType &&
46713                     resolved.indexType === indexType ?
46714                     getConditionalFlowTypeOfType(resolved, node) : resolved;
46715             }
46716             return links.resolvedType;
46717         }
46718         function getTypeFromMappedTypeNode(node) {
46719             var links = getNodeLinks(node);
46720             if (!links.resolvedType) {
46721                 var type = createObjectType(32 /* Mapped */, node.symbol);
46722                 type.declaration = node;
46723                 type.aliasSymbol = getAliasSymbolForTypeNode(node);
46724                 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
46725                 links.resolvedType = type;
46726                 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
46727                 // references itself through one or more type aliases.
46728                 getConstraintTypeFromMappedType(type);
46729             }
46730             return links.resolvedType;
46731         }
46732         function getActualTypeVariable(type) {
46733             if (type.flags & 33554432 /* Substitution */) {
46734                 return type.baseType;
46735             }
46736             if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
46737                 type.indexType.flags & 33554432 /* Substitution */)) {
46738                 return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
46739             }
46740             return type;
46741         }
46742         function getConditionalType(root, mapper) {
46743             var result;
46744             var extraTypes;
46745             var _loop_12 = function () {
46746                 var checkType = instantiateType(root.checkType, mapper);
46747                 var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType);
46748                 var extendsType = instantiateType(root.extendsType, mapper);
46749                 if (checkType === wildcardType || extendsType === wildcardType) {
46750                     return { value: wildcardType };
46751                 }
46752                 var combinedMapper = void 0;
46753                 if (root.inferTypeParameters) {
46754                     var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
46755                     // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
46756                     // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
46757                     // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
46758                     // so in those cases we refain from performing inference and retain the uninfered type parameter
46759                     if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) {
46760                         // We don't want inferences from constraints as they may cause us to eagerly resolve the
46761                         // conditional type instead of deferring resolution. Also, we always want strict function
46762                         // types rules (i.e. proper contravariance) for inferences.
46763                         inferTypes(context.inferences, checkType, extendsType, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
46764                     }
46765                     combinedMapper = mergeTypeMappers(mapper, context.mapper);
46766                 }
46767                 // Instantiate the extends type including inferences for 'infer T' type parameters
46768                 var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
46769                 // We attempt to resolve the conditional type only when the check and extends types are non-generic
46770                 if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) {
46771                     // Return falseType for a definitely false extends check. We check an instantiations of the two
46772                     // types with type parameters mapped to the wildcard type, the most permissive instantiations
46773                     // possible (the wildcard type is assignable to and from all types). If those are not related,
46774                     // then no instantiations will be and we can just return the false branch type.
46775                     if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
46776                         // Return union of trueType and falseType for 'any' since it matches anything
46777                         if (checkType.flags & 1 /* Any */) {
46778                             (extraTypes || (extraTypes = [])).push(instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper));
46779                         }
46780                         // If falseType is an immediately nested conditional type that isn't distributive or has an
46781                         // identical checkType, switch to that type and loop.
46782                         var falseType_1 = root.falseType;
46783                         if (falseType_1.flags & 16777216 /* Conditional */) {
46784                             var newRoot = falseType_1.root;
46785                             if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
46786                                 root = newRoot;
46787                                 return "continue";
46788                             }
46789                         }
46790                         result = instantiateTypeWithoutDepthIncrease(falseType_1, mapper);
46791                         return "break";
46792                     }
46793                     // Return trueType for a definitely true extends check. We check instantiations of the two
46794                     // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
46795                     // that has no constraint. This ensures that, for example, the type
46796                     //   type Foo<T extends { x: any }> = T extends { x: string } ? string : number
46797                     // doesn't immediately resolve to 'string' instead of being deferred.
46798                     if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
46799                         result = instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper);
46800                         return "break";
46801                     }
46802                 }
46803                 // Return a deferred type for a check that is neither definitely true nor definitely false
46804                 var erasedCheckType = getActualTypeVariable(checkType);
46805                 result = createType(16777216 /* Conditional */);
46806                 result.root = root;
46807                 result.checkType = erasedCheckType;
46808                 result.extendsType = extendsType;
46809                 result.mapper = mapper;
46810                 result.combinedMapper = combinedMapper;
46811                 result.aliasSymbol = root.aliasSymbol;
46812                 result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
46813                 return "break";
46814             };
46815             // We loop here for an immediately nested conditional type in the false position, effectively treating
46816             // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
46817             // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
46818             while (true) {
46819                 var state_4 = _loop_12();
46820                 if (typeof state_4 === "object")
46821                     return state_4.value;
46822                 if (state_4 === "break")
46823                     break;
46824             }
46825             return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
46826         }
46827         function getTrueTypeFromConditionalType(type) {
46828             return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
46829         }
46830         function getFalseTypeFromConditionalType(type) {
46831             return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
46832         }
46833         function getInferredTrueTypeFromConditionalType(type) {
46834             return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(type.root.trueType, type.combinedMapper) : getTrueTypeFromConditionalType(type));
46835         }
46836         function getInferTypeParameters(node) {
46837             var result;
46838             if (node.locals) {
46839                 node.locals.forEach(function (symbol) {
46840                     if (symbol.flags & 262144 /* TypeParameter */) {
46841                         result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
46842                     }
46843                 });
46844             }
46845             return result;
46846         }
46847         function getTypeFromConditionalTypeNode(node) {
46848             var links = getNodeLinks(node);
46849             if (!links.resolvedType) {
46850                 var checkType = getTypeFromTypeNode(node.checkType);
46851                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46852                 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
46853                 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
46854                 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
46855                 var root = {
46856                     node: node,
46857                     checkType: checkType,
46858                     extendsType: getTypeFromTypeNode(node.extendsType),
46859                     trueType: getTypeFromTypeNode(node.trueType),
46860                     falseType: getTypeFromTypeNode(node.falseType),
46861                     isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
46862                     inferTypeParameters: getInferTypeParameters(node),
46863                     outerTypeParameters: outerTypeParameters,
46864                     instantiations: undefined,
46865                     aliasSymbol: aliasSymbol,
46866                     aliasTypeArguments: aliasTypeArguments
46867                 };
46868                 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
46869                 if (outerTypeParameters) {
46870                     root.instantiations = ts.createMap();
46871                     root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
46872                 }
46873             }
46874             return links.resolvedType;
46875         }
46876         function getTypeFromInferTypeNode(node) {
46877             var links = getNodeLinks(node);
46878             if (!links.resolvedType) {
46879                 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
46880             }
46881             return links.resolvedType;
46882         }
46883         function getIdentifierChain(node) {
46884             if (ts.isIdentifier(node)) {
46885                 return [node];
46886             }
46887             else {
46888                 return ts.append(getIdentifierChain(node.left), node.right);
46889             }
46890         }
46891         function getTypeFromImportTypeNode(node) {
46892             var links = getNodeLinks(node);
46893             if (!links.resolvedType) {
46894                 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
46895                     error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
46896                     links.resolvedSymbol = unknownSymbol;
46897                     return links.resolvedType = errorType;
46898                 }
46899                 if (!ts.isLiteralImportTypeNode(node)) {
46900                     error(node.argument, ts.Diagnostics.String_literal_expected);
46901                     links.resolvedSymbol = unknownSymbol;
46902                     return links.resolvedType = errorType;
46903                 }
46904                 var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
46905                 // TODO: Future work: support unions/generics/whatever via a deferred import-type
46906                 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
46907                 if (!innerModuleSymbol) {
46908                     links.resolvedSymbol = unknownSymbol;
46909                     return links.resolvedType = errorType;
46910                 }
46911                 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
46912                 if (!ts.nodeIsMissing(node.qualifier)) {
46913                     var nameStack = getIdentifierChain(node.qualifier);
46914                     var currentNamespace = moduleSymbol;
46915                     var current = void 0;
46916                     while (current = nameStack.shift()) {
46917                         var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
46918                         var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning);
46919                         if (!next) {
46920                             error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
46921                             return links.resolvedType = errorType;
46922                         }
46923                         getNodeLinks(current).resolvedSymbol = next;
46924                         getNodeLinks(current.parent).resolvedSymbol = next;
46925                         currentNamespace = next;
46926                     }
46927                     links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
46928                 }
46929                 else {
46930                     if (moduleSymbol.flags & targetMeaning) {
46931                         links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
46932                     }
46933                     else {
46934                         var errorMessage = targetMeaning === 111551 /* Value */
46935                             ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
46936                             : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
46937                         error(node, errorMessage, node.argument.literal.text);
46938                         links.resolvedSymbol = unknownSymbol;
46939                         links.resolvedType = errorType;
46940                     }
46941                 }
46942             }
46943             return links.resolvedType;
46944         }
46945         function resolveImportSymbolType(node, links, symbol, meaning) {
46946             var resolvedSymbol = resolveSymbol(symbol);
46947             links.resolvedSymbol = resolvedSymbol;
46948             if (meaning === 111551 /* Value */) {
46949                 return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
46950             }
46951             else {
46952                 return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
46953             }
46954         }
46955         function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
46956             var links = getNodeLinks(node);
46957             if (!links.resolvedType) {
46958                 // Deferred resolution of members is handled by resolveObjectTypeMembers
46959                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46960                 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
46961                     links.resolvedType = emptyTypeLiteralType;
46962                 }
46963                 else {
46964                     var type = createObjectType(16 /* Anonymous */, node.symbol);
46965                     type.aliasSymbol = aliasSymbol;
46966                     type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
46967                     if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
46968                         type = createArrayType(type);
46969                     }
46970                     links.resolvedType = type;
46971                 }
46972             }
46973             return links.resolvedType;
46974         }
46975         function getAliasSymbolForTypeNode(node) {
46976             var host = node.parent;
46977             while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 138 /* ReadonlyKeyword */) {
46978                 host = host.parent;
46979             }
46980             return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
46981         }
46982         function getTypeArgumentsForAliasSymbol(symbol) {
46983             return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
46984         }
46985         function isNonGenericObjectType(type) {
46986             return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
46987         }
46988         function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
46989             return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
46990         }
46991         function isSinglePropertyAnonymousObjectType(type) {
46992             return !!(type.flags & 524288 /* Object */) &&
46993                 !!(ts.getObjectFlags(type) & 16 /* Anonymous */) &&
46994                 (ts.length(getPropertiesOfType(type)) === 1 || ts.every(getPropertiesOfType(type), function (p) { return !!(p.flags & 16777216 /* Optional */); }));
46995         }
46996         function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
46997             if (type.types.length === 2) {
46998                 var firstType = type.types[0];
46999                 var secondType = type.types[1];
47000                 if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
47001                     return isEmptyObjectType(firstType) ? firstType : isEmptyObjectType(secondType) ? secondType : emptyObjectType;
47002                 }
47003                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(firstType) && isSinglePropertyAnonymousObjectType(secondType)) {
47004                     return getAnonymousPartialType(secondType);
47005                 }
47006                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(secondType) && isSinglePropertyAnonymousObjectType(firstType)) {
47007                     return getAnonymousPartialType(firstType);
47008                 }
47009             }
47010             function getAnonymousPartialType(type) {
47011                 // gets the type as if it had been spread, but where everything in the spread is made optional
47012                 var members = ts.createSymbolTable();
47013                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
47014                     var prop = _a[_i];
47015                     if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
47016                         // do nothing, skip privates
47017                     }
47018                     else if (isSpreadableProperty(prop)) {
47019                         var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47020                         var flags = 4 /* Property */ | 16777216 /* Optional */;
47021                         var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47022                         result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47023                         result.declarations = prop.declarations;
47024                         result.nameType = getSymbolLinks(prop).nameType;
47025                         result.syntheticOrigin = prop;
47026                         members.set(prop.escapedName, result);
47027                     }
47028                 }
47029                 var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */));
47030                 spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
47031                 return spread;
47032             }
47033         }
47034         /**
47035          * Since the source of spread types are object literals, which are not binary,
47036          * this function should be called in a left folding style, with left = previous result of getSpreadType
47037          * and right = the new element to be spread.
47038          */
47039         function getSpreadType(left, right, symbol, objectFlags, readonly) {
47040             if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
47041                 return anyType;
47042             }
47043             if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
47044                 return unknownType;
47045             }
47046             if (left.flags & 131072 /* Never */) {
47047                 return right;
47048             }
47049             if (right.flags & 131072 /* Never */) {
47050                 return left;
47051             }
47052             if (left.flags & 1048576 /* Union */) {
47053                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
47054                 if (merged) {
47055                     return getSpreadType(merged, right, symbol, objectFlags, readonly);
47056                 }
47057                 return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
47058             }
47059             if (right.flags & 1048576 /* Union */) {
47060                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
47061                 if (merged) {
47062                     return getSpreadType(left, merged, symbol, objectFlags, readonly);
47063                 }
47064                 return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
47065             }
47066             if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
47067                 return left;
47068             }
47069             if (isGenericObjectType(left) || isGenericObjectType(right)) {
47070                 if (isEmptyObjectType(left)) {
47071                     return right;
47072                 }
47073                 // When the left type is an intersection, we may need to merge the last constituent of the
47074                 // intersection with the right type. For example when the left type is 'T & { a: string }'
47075                 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
47076                 if (left.flags & 2097152 /* Intersection */) {
47077                     var types = left.types;
47078                     var lastLeft = types[types.length - 1];
47079                     if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
47080                         return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
47081                     }
47082                 }
47083                 return getIntersectionType([left, right]);
47084             }
47085             var members = ts.createSymbolTable();
47086             var skippedPrivateMembers = ts.createUnderscoreEscapedMap();
47087             var stringIndexInfo;
47088             var numberIndexInfo;
47089             if (left === emptyObjectType) {
47090                 // for the first spread element, left === emptyObjectType, so take the right's string indexer
47091                 stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
47092                 numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
47093             }
47094             else {
47095                 stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
47096                 numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
47097             }
47098             for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
47099                 var rightProp = _a[_i];
47100                 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
47101                     skippedPrivateMembers.set(rightProp.escapedName, true);
47102                 }
47103                 else if (isSpreadableProperty(rightProp)) {
47104                     members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
47105                 }
47106             }
47107             for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
47108                 var leftProp = _c[_b];
47109                 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
47110                     continue;
47111                 }
47112                 if (members.has(leftProp.escapedName)) {
47113                     var rightProp = members.get(leftProp.escapedName);
47114                     var rightType = getTypeOfSymbol(rightProp);
47115                     if (rightProp.flags & 16777216 /* Optional */) {
47116                         var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
47117                         var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
47118                         var result = createSymbol(flags, leftProp.escapedName);
47119                         result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
47120                         result.leftSpread = leftProp;
47121                         result.rightSpread = rightProp;
47122                         result.declarations = declarations;
47123                         result.nameType = getSymbolLinks(leftProp).nameType;
47124                         members.set(leftProp.escapedName, result);
47125                     }
47126                 }
47127                 else {
47128                     members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
47129                 }
47130             }
47131             var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
47132             spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
47133             return spread;
47134         }
47135         /** We approximate own properties as non-methods plus methods that are inside the object literal */
47136         function isSpreadableProperty(prop) {
47137             return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) &&
47138                 (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
47139                     !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }));
47140         }
47141         function getSpreadSymbol(prop, readonly) {
47142             var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47143             if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
47144                 return prop;
47145             }
47146             var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
47147             var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47148             result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47149             result.declarations = prop.declarations;
47150             result.nameType = getSymbolLinks(prop).nameType;
47151             result.syntheticOrigin = prop;
47152             return result;
47153         }
47154         function getIndexInfoWithReadonly(info, readonly) {
47155             return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
47156         }
47157         function createLiteralType(flags, value, symbol) {
47158             var type = createType(flags);
47159             type.symbol = symbol;
47160             type.value = value;
47161             return type;
47162         }
47163         function getFreshTypeOfLiteralType(type) {
47164             if (type.flags & 2944 /* Literal */) {
47165                 if (!type.freshType) {
47166                     var freshType = createLiteralType(type.flags, type.value, type.symbol);
47167                     freshType.regularType = type;
47168                     freshType.freshType = freshType;
47169                     type.freshType = freshType;
47170                 }
47171                 return type.freshType;
47172             }
47173             return type;
47174         }
47175         function getRegularTypeOfLiteralType(type) {
47176             return type.flags & 2944 /* Literal */ ? type.regularType :
47177                 type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) :
47178                     type;
47179         }
47180         function isFreshLiteralType(type) {
47181             return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
47182         }
47183         function getLiteralType(value, enumId, symbol) {
47184             // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
47185             // where NNN is the text representation of a numeric literal and SSS are the characters
47186             // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
47187             // EEE is a unique id for the containing enum type.
47188             var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
47189             var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
47190             var type = literalTypes.get(key);
47191             if (!type) {
47192                 var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
47193                     typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
47194                     (enumId ? 1024 /* EnumLiteral */ : 0);
47195                 literalTypes.set(key, type = createLiteralType(flags, value, symbol));
47196                 type.regularType = type;
47197             }
47198             return type;
47199         }
47200         function getTypeFromLiteralTypeNode(node) {
47201             var links = getNodeLinks(node);
47202             if (!links.resolvedType) {
47203                 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
47204             }
47205             return links.resolvedType;
47206         }
47207         function createUniqueESSymbolType(symbol) {
47208             var type = createType(8192 /* UniqueESSymbol */);
47209             type.symbol = symbol;
47210             type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
47211             return type;
47212         }
47213         function getESSymbolLikeTypeForNode(node) {
47214             if (ts.isValidESSymbolDeclaration(node)) {
47215                 var symbol = getSymbolOfNode(node);
47216                 var links = getSymbolLinks(symbol);
47217                 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
47218             }
47219             return esSymbolType;
47220         }
47221         function getThisType(node) {
47222             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
47223             var parent = container && container.parent;
47224             if (parent && (ts.isClassLike(parent) || parent.kind === 246 /* InterfaceDeclaration */)) {
47225                 if (!ts.hasModifier(container, 32 /* Static */) &&
47226                     (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
47227                     return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
47228                 }
47229             }
47230             // inside x.prototype = { ... }
47231             if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
47232                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
47233             }
47234             // /** @return {this} */
47235             // x.prototype.m = function() { ... }
47236             var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
47237             if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
47238                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
47239             }
47240             // inside constructor function C() { ... }
47241             if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
47242                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
47243             }
47244             error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
47245             return errorType;
47246         }
47247         function getTypeFromThisTypeNode(node) {
47248             var links = getNodeLinks(node);
47249             if (!links.resolvedType) {
47250                 links.resolvedType = getThisType(node);
47251             }
47252             return links.resolvedType;
47253         }
47254         function getTypeFromTypeNode(node) {
47255             return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
47256         }
47257         function getTypeFromTypeNodeWorker(node) {
47258             switch (node.kind) {
47259                 case 125 /* AnyKeyword */:
47260                 case 295 /* JSDocAllType */:
47261                 case 296 /* JSDocUnknownType */:
47262                     return anyType;
47263                 case 148 /* UnknownKeyword */:
47264                     return unknownType;
47265                 case 143 /* StringKeyword */:
47266                     return stringType;
47267                 case 140 /* NumberKeyword */:
47268                     return numberType;
47269                 case 151 /* BigIntKeyword */:
47270                     return bigintType;
47271                 case 128 /* BooleanKeyword */:
47272                     return booleanType;
47273                 case 144 /* SymbolKeyword */:
47274                     return esSymbolType;
47275                 case 110 /* VoidKeyword */:
47276                     return voidType;
47277                 case 146 /* UndefinedKeyword */:
47278                     return undefinedType;
47279                 case 100 /* NullKeyword */:
47280                     return nullType;
47281                 case 137 /* NeverKeyword */:
47282                     return neverType;
47283                 case 141 /* ObjectKeyword */:
47284                     return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
47285                 case 183 /* ThisType */:
47286                 case 104 /* ThisKeyword */:
47287                     return getTypeFromThisTypeNode(node);
47288                 case 187 /* LiteralType */:
47289                     return getTypeFromLiteralTypeNode(node);
47290                 case 169 /* TypeReference */:
47291                     return getTypeFromTypeReference(node);
47292                 case 168 /* TypePredicate */:
47293                     return node.assertsModifier ? voidType : booleanType;
47294                 case 216 /* ExpressionWithTypeArguments */:
47295                     return getTypeFromTypeReference(node);
47296                 case 172 /* TypeQuery */:
47297                     return getTypeFromTypeQueryNode(node);
47298                 case 174 /* ArrayType */:
47299                 case 175 /* TupleType */:
47300                     return getTypeFromArrayOrTupleTypeNode(node);
47301                 case 176 /* OptionalType */:
47302                     return getTypeFromOptionalTypeNode(node);
47303                 case 178 /* UnionType */:
47304                     return getTypeFromUnionTypeNode(node);
47305                 case 179 /* IntersectionType */:
47306                     return getTypeFromIntersectionTypeNode(node);
47307                 case 297 /* JSDocNullableType */:
47308                     return getTypeFromJSDocNullableTypeNode(node);
47309                 case 299 /* JSDocOptionalType */:
47310                     return addOptionality(getTypeFromTypeNode(node.type));
47311                 case 182 /* ParenthesizedType */:
47312                 case 298 /* JSDocNonNullableType */:
47313                 case 294 /* JSDocTypeExpression */:
47314                     return getTypeFromTypeNode(node.type);
47315                 case 177 /* RestType */:
47316                     return getElementTypeOfArrayType(getTypeFromTypeNode(node.type)) || errorType;
47317                 case 301 /* JSDocVariadicType */:
47318                     return getTypeFromJSDocVariadicType(node);
47319                 case 170 /* FunctionType */:
47320                 case 171 /* ConstructorType */:
47321                 case 173 /* TypeLiteral */:
47322                 case 304 /* JSDocTypeLiteral */:
47323                 case 300 /* JSDocFunctionType */:
47324                 case 305 /* JSDocSignature */:
47325                     return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
47326                 case 184 /* TypeOperator */:
47327                     return getTypeFromTypeOperatorNode(node);
47328                 case 185 /* IndexedAccessType */:
47329                     return getTypeFromIndexedAccessTypeNode(node);
47330                 case 186 /* MappedType */:
47331                     return getTypeFromMappedTypeNode(node);
47332                 case 180 /* ConditionalType */:
47333                     return getTypeFromConditionalTypeNode(node);
47334                 case 181 /* InferType */:
47335                     return getTypeFromInferTypeNode(node);
47336                 case 188 /* ImportType */:
47337                     return getTypeFromImportTypeNode(node);
47338                 // This function assumes that an identifier or qualified name is a type expression
47339                 // Callers should first ensure this by calling isTypeNode
47340                 case 75 /* Identifier */:
47341                 case 153 /* QualifiedName */:
47342                     var symbol = getSymbolAtLocation(node);
47343                     return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
47344                 default:
47345                     return errorType;
47346             }
47347         }
47348         function instantiateList(items, mapper, instantiator) {
47349             if (items && items.length) {
47350                 for (var i = 0; i < items.length; i++) {
47351                     var item = items[i];
47352                     var mapped = instantiator(item, mapper);
47353                     if (item !== mapped) {
47354                         var result = i === 0 ? [] : items.slice(0, i);
47355                         result.push(mapped);
47356                         for (i++; i < items.length; i++) {
47357                             result.push(instantiator(items[i], mapper));
47358                         }
47359                         return result;
47360                     }
47361                 }
47362             }
47363             return items;
47364         }
47365         function instantiateTypes(types, mapper) {
47366             return instantiateList(types, mapper, instantiateType);
47367         }
47368         function instantiateSignatures(signatures, mapper) {
47369             return instantiateList(signatures, mapper, instantiateSignature);
47370         }
47371         function createTypeMapper(sources, targets) {
47372             return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
47373         }
47374         function getMappedType(type, mapper) {
47375             switch (mapper.kind) {
47376                 case 0 /* Simple */:
47377                     return type === mapper.source ? mapper.target : type;
47378                 case 1 /* Array */:
47379                     var sources = mapper.sources;
47380                     var targets = mapper.targets;
47381                     for (var i = 0; i < sources.length; i++) {
47382                         if (type === sources[i]) {
47383                             return targets ? targets[i] : anyType;
47384                         }
47385                     }
47386                     return type;
47387                 case 2 /* Function */:
47388                     return mapper.func(type);
47389                 case 3 /* Composite */:
47390                 case 4 /* Merged */:
47391                     var t1 = getMappedType(type, mapper.mapper1);
47392                     return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
47393             }
47394         }
47395         function makeUnaryTypeMapper(source, target) {
47396             return { kind: 0 /* Simple */, source: source, target: target };
47397         }
47398         function makeArrayTypeMapper(sources, targets) {
47399             return { kind: 1 /* Array */, sources: sources, targets: targets };
47400         }
47401         function makeFunctionTypeMapper(func) {
47402             return { kind: 2 /* Function */, func: func };
47403         }
47404         function makeCompositeTypeMapper(kind, mapper1, mapper2) {
47405             return { kind: kind, mapper1: mapper1, mapper2: mapper2 };
47406         }
47407         function createTypeEraser(sources) {
47408             return createTypeMapper(sources, /*targets*/ undefined);
47409         }
47410         /**
47411          * Maps forward-references to later types parameters to the empty object type.
47412          * This is used during inference when instantiating type parameter defaults.
47413          */
47414         function createBackreferenceMapper(context, index) {
47415             return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; });
47416         }
47417         function combineTypeMappers(mapper1, mapper2) {
47418             return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2;
47419         }
47420         function mergeTypeMappers(mapper1, mapper2) {
47421             return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2;
47422         }
47423         function prependTypeMapping(source, target, mapper) {
47424             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
47425         }
47426         function appendTypeMapping(mapper, source, target) {
47427             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target));
47428         }
47429         function getRestrictiveTypeParameter(tp) {
47430             return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
47431                 tp.restrictiveInstantiation.constraint = unknownType,
47432                 tp.restrictiveInstantiation);
47433         }
47434         function cloneTypeParameter(typeParameter) {
47435             var result = createTypeParameter(typeParameter.symbol);
47436             result.target = typeParameter;
47437             return result;
47438         }
47439         function instantiateTypePredicate(predicate, mapper) {
47440             return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
47441         }
47442         function instantiateSignature(signature, mapper, eraseTypeParameters) {
47443             var freshTypeParameters;
47444             if (signature.typeParameters && !eraseTypeParameters) {
47445                 // First create a fresh set of type parameters, then include a mapping from the old to the
47446                 // new type parameters in the mapper function. Finally store this mapper in the new type
47447                 // parameters such that we can use it when instantiating constraints.
47448                 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
47449                 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
47450                 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
47451                     var tp = freshTypeParameters_1[_i];
47452                     tp.mapper = mapper;
47453                 }
47454             }
47455             // Don't compute resolvedReturnType and resolvedTypePredicate now,
47456             // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
47457             // See GH#17600.
47458             var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), 
47459             /*resolvedReturnType*/ undefined, 
47460             /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */);
47461             result.target = signature;
47462             result.mapper = mapper;
47463             return result;
47464         }
47465         function instantiateSymbol(symbol, mapper) {
47466             var links = getSymbolLinks(symbol);
47467             if (links.type && !couldContainTypeVariables(links.type)) {
47468                 // If the type of the symbol is already resolved, and if that type could not possibly
47469                 // be affected by instantiation, simply return the symbol itself.
47470                 return symbol;
47471             }
47472             if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
47473                 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
47474                 // type mappers. This ensures that original type identities are properly preserved and that aliases
47475                 // always reference a non-aliases.
47476                 symbol = links.target;
47477                 mapper = combineTypeMappers(links.mapper, mapper);
47478             }
47479             // Keep the flags from the symbol we're instantiating.  Mark that is instantiated, and
47480             // also transient so that we can just store data on it directly.
47481             var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
47482             result.declarations = symbol.declarations;
47483             result.parent = symbol.parent;
47484             result.target = symbol;
47485             result.mapper = mapper;
47486             if (symbol.valueDeclaration) {
47487                 result.valueDeclaration = symbol.valueDeclaration;
47488             }
47489             if (links.nameType) {
47490                 result.nameType = links.nameType;
47491             }
47492             return result;
47493         }
47494         function getObjectTypeInstantiation(type, mapper) {
47495             var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type;
47496             var node = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
47497             var links = getNodeLinks(node);
47498             var typeParameters = links.outerTypeParameters;
47499             if (!typeParameters) {
47500                 // The first time an anonymous type is instantiated we compute and store a list of the type
47501                 // parameters that are in scope (and therefore potentially referenced). For type literals that
47502                 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
47503                 // set of type parameters to those that are possibly referenced in the literal.
47504                 var declaration_1 = node;
47505                 if (ts.isInJSFile(declaration_1)) {
47506                     var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag);
47507                     if (paramTag) {
47508                         var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag);
47509                         if (paramSymbol) {
47510                             declaration_1 = paramSymbol.valueDeclaration;
47511                         }
47512                     }
47513                 }
47514                 var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true);
47515                 if (isJSConstructor(declaration_1)) {
47516                     var templateTagParameters = getTypeParametersFromDeclaration(declaration_1);
47517                     outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
47518                 }
47519                 typeParameters = outerTypeParameters || ts.emptyArray;
47520                 typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
47521                     ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) :
47522                     typeParameters;
47523                 links.outerTypeParameters = typeParameters;
47524                 if (typeParameters.length) {
47525                     links.instantiations = ts.createMap();
47526                     links.instantiations.set(getTypeListId(typeParameters), target);
47527                 }
47528             }
47529             if (typeParameters.length) {
47530                 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
47531                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47532                 // instantiation cache key from the type IDs of the type arguments.
47533                 var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
47534                 var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
47535                 var id = getTypeListId(typeArguments);
47536                 var result = links.instantiations.get(id);
47537                 if (!result) {
47538                     var newMapper = createTypeMapper(typeParameters, typeArguments);
47539                     result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) :
47540                         target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) :
47541                             instantiateAnonymousType(target, newMapper);
47542                     links.instantiations.set(id, result);
47543                 }
47544                 return result;
47545             }
47546             return type;
47547         }
47548         function maybeTypeParameterReference(node) {
47549             return !(node.kind === 153 /* QualifiedName */ ||
47550                 node.parent.kind === 169 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
47551                 node.parent.kind === 188 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
47552         }
47553         function isTypeParameterPossiblyReferenced(tp, node) {
47554             // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
47555             // between the node and the type parameter declaration, if the node contains actual references to the
47556             // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
47557             if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
47558                 var container = tp.symbol.declarations[0].parent;
47559                 for (var n = node; n !== container; n = n.parent) {
47560                     if (!n || n.kind === 223 /* Block */ || n.kind === 180 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
47561                         return true;
47562                     }
47563                 }
47564                 return !!ts.forEachChild(node, containsReference);
47565             }
47566             return true;
47567             function containsReference(node) {
47568                 switch (node.kind) {
47569                     case 183 /* ThisType */:
47570                         return !!tp.isThisType;
47571                     case 75 /* Identifier */:
47572                         return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
47573                             getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality
47574                     case 172 /* TypeQuery */:
47575                         return true;
47576                 }
47577                 return !!ts.forEachChild(node, containsReference);
47578             }
47579         }
47580         function getHomomorphicTypeVariable(type) {
47581             var constraintType = getConstraintTypeFromMappedType(type);
47582             if (constraintType.flags & 4194304 /* Index */) {
47583                 var typeVariable = getActualTypeVariable(constraintType.type);
47584                 if (typeVariable.flags & 262144 /* TypeParameter */) {
47585                     return typeVariable;
47586                 }
47587             }
47588             return undefined;
47589         }
47590         function instantiateMappedType(type, mapper) {
47591             // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
47592             // operation depends on T as follows:
47593             // * If T is a primitive type no mapping is performed and the result is simply T.
47594             // * If T is a union type we distribute the mapped type over the union.
47595             // * If T is an array we map to an array where the element type has been transformed.
47596             // * If T is a tuple we map to a tuple where the element types have been transformed.
47597             // * Otherwise we map to an object type where the type of each property has been transformed.
47598             // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
47599             // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
47600             // { [P in keyof A]: X } | undefined.
47601             var typeVariable = getHomomorphicTypeVariable(type);
47602             if (typeVariable) {
47603                 var mappedTypeVariable = instantiateType(typeVariable, mapper);
47604                 if (typeVariable !== mappedTypeVariable) {
47605                     return mapType(getReducedType(mappedTypeVariable), function (t) {
47606                         if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
47607                             var replacementMapper = prependTypeMapping(typeVariable, t, mapper);
47608                             return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
47609                                 isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
47610                                     instantiateAnonymousType(type, replacementMapper);
47611                         }
47612                         return t;
47613                     });
47614                 }
47615             }
47616             return instantiateAnonymousType(type, mapper);
47617         }
47618         function getModifiedReadonlyState(state, modifiers) {
47619             return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
47620         }
47621         function instantiateMappedArrayType(arrayType, mappedType, mapper) {
47622             var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
47623             return elementType === errorType ? errorType :
47624                 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
47625         }
47626         function instantiateMappedTupleType(tupleType, mappedType, mapper) {
47627             var minLength = tupleType.target.minLength;
47628             var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
47629                 return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper);
47630             });
47631             var modifiers = getMappedTypeModifiers(mappedType);
47632             var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 :
47633                 modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) :
47634                     minLength;
47635             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
47636             return ts.contains(elementTypes, errorType) ? errorType :
47637                 createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
47638         }
47639         function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
47640             var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
47641             var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
47642             var modifiers = getMappedTypeModifiers(type);
47643             return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
47644                 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
47645                     propType;
47646         }
47647         function instantiateAnonymousType(type, mapper) {
47648             var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
47649             if (type.objectFlags & 32 /* Mapped */) {
47650                 result.declaration = type.declaration;
47651                 // C.f. instantiateSignature
47652                 var origTypeParameter = getTypeParameterFromMappedType(type);
47653                 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
47654                 result.typeParameter = freshTypeParameter;
47655                 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
47656                 freshTypeParameter.mapper = mapper;
47657             }
47658             result.target = type;
47659             result.mapper = mapper;
47660             result.aliasSymbol = type.aliasSymbol;
47661             result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
47662             return result;
47663         }
47664         function getConditionalTypeInstantiation(type, mapper) {
47665             var root = type.root;
47666             if (root.outerTypeParameters) {
47667                 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
47668                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47669                 // instantiation cache key from the type IDs of the type arguments.
47670                 var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
47671                 var id = getTypeListId(typeArguments);
47672                 var result = root.instantiations.get(id);
47673                 if (!result) {
47674                     var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
47675                     result = instantiateConditionalType(root, newMapper);
47676                     root.instantiations.set(id, result);
47677                 }
47678                 return result;
47679             }
47680             return type;
47681         }
47682         function instantiateConditionalType(root, mapper) {
47683             // Check if we have a conditional type where the check type is a naked type parameter. If so,
47684             // the conditional type is distributive over union types and when T is instantiated to a union
47685             // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
47686             if (root.isDistributive) {
47687                 var checkType_1 = root.checkType;
47688                 var instantiatedType = getMappedType(checkType_1, mapper);
47689                 if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
47690                     return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); });
47691                 }
47692             }
47693             return getConditionalType(root, mapper);
47694         }
47695         function instantiateType(type, mapper) {
47696             if (!type || !mapper) {
47697                 return type;
47698             }
47699             if (instantiationDepth === 50 || instantiationCount >= 5000000) {
47700                 // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
47701                 // with a combination of infinite generic types that perpetually generate new type identities. We stop
47702                 // the recursion here by yielding the error type.
47703                 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
47704                 return errorType;
47705             }
47706             totalInstantiationCount++;
47707             instantiationCount++;
47708             instantiationDepth++;
47709             var result = instantiateTypeWorker(type, mapper);
47710             instantiationDepth--;
47711             return result;
47712         }
47713         /**
47714          * This can be used to avoid the penalty on instantiation depth for types which result from immediate
47715          * simplification. It essentially removes the depth increase done in `instantiateType`.
47716          */
47717         function instantiateTypeWithoutDepthIncrease(type, mapper) {
47718             instantiationDepth--;
47719             var result = instantiateType(type, mapper);
47720             instantiationDepth++;
47721             return result;
47722         }
47723         function instantiateTypeWorker(type, mapper) {
47724             var flags = type.flags;
47725             if (flags & 262144 /* TypeParameter */) {
47726                 return getMappedType(type, mapper);
47727             }
47728             if (flags & 524288 /* Object */) {
47729                 var objectFlags = type.objectFlags;
47730                 if (objectFlags & 16 /* Anonymous */) {
47731                     // If the anonymous type originates in a declaration of a function, method, class, or
47732                     // interface, in an object type literal, or in an object literal expression, we may need
47733                     // to instantiate the type because it might reference a type parameter.
47734                     return couldContainTypeVariables(type) ?
47735                         getObjectTypeInstantiation(type, mapper) : type;
47736                 }
47737                 if (objectFlags & 32 /* Mapped */) {
47738                     return getObjectTypeInstantiation(type, mapper);
47739                 }
47740                 if (objectFlags & 4 /* Reference */) {
47741                     if (type.node) {
47742                         return getObjectTypeInstantiation(type, mapper);
47743                     }
47744                     var resolvedTypeArguments = type.resolvedTypeArguments;
47745                     var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
47746                     return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type;
47747                 }
47748                 return type;
47749             }
47750             if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) {
47751                 if (!couldContainTypeVariables(type)) {
47752                     return type;
47753                 }
47754                 var types = type.types;
47755                 var newTypes = instantiateTypes(types, mapper);
47756                 return newTypes === types
47757                     ? type
47758                     : (flags & 2097152 /* Intersection */)
47759                         ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper))
47760                         : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
47761             }
47762             if (flags & 4194304 /* Index */) {
47763                 return getIndexType(instantiateType(type.type, mapper));
47764             }
47765             if (flags & 8388608 /* IndexedAccess */) {
47766                 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
47767             }
47768             if (flags & 16777216 /* Conditional */) {
47769                 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
47770             }
47771             if (flags & 33554432 /* Substitution */) {
47772                 var maybeVariable = instantiateType(type.baseType, mapper);
47773                 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
47774                     return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
47775                 }
47776                 else {
47777                     var sub = instantiateType(type.substitute, mapper);
47778                     if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
47779                         return maybeVariable;
47780                     }
47781                     return sub;
47782                 }
47783             }
47784             return type;
47785         }
47786         function getPermissiveInstantiation(type) {
47787             return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
47788                 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
47789         }
47790         function getRestrictiveInstantiation(type) {
47791             if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
47792                 return type;
47793             }
47794             if (type.restrictiveInstantiation) {
47795                 return type.restrictiveInstantiation;
47796             }
47797             type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
47798             // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
47799             // which is redundant - we'll produce new type identities, but all type params have already been mapped.
47800             // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
47801             // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
47802             // are constrained to `unknown` and produce tons of false positives/negatives!
47803             type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
47804             return type.restrictiveInstantiation;
47805         }
47806         function instantiateIndexInfo(info, mapper) {
47807             return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
47808         }
47809         // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
47810         // that is subject to contextual typing.
47811         function isContextSensitive(node) {
47812             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
47813             switch (node.kind) {
47814                 case 201 /* FunctionExpression */:
47815                 case 202 /* ArrowFunction */:
47816                 case 161 /* MethodDeclaration */:
47817                 case 244 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
47818                     return isContextSensitiveFunctionLikeDeclaration(node);
47819                 case 193 /* ObjectLiteralExpression */:
47820                     return ts.some(node.properties, isContextSensitive);
47821                 case 192 /* ArrayLiteralExpression */:
47822                     return ts.some(node.elements, isContextSensitive);
47823                 case 210 /* ConditionalExpression */:
47824                     return isContextSensitive(node.whenTrue) ||
47825                         isContextSensitive(node.whenFalse);
47826                 case 209 /* BinaryExpression */:
47827                     return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
47828                         (isContextSensitive(node.left) || isContextSensitive(node.right));
47829                 case 281 /* PropertyAssignment */:
47830                     return isContextSensitive(node.initializer);
47831                 case 200 /* ParenthesizedExpression */:
47832                     return isContextSensitive(node.expression);
47833                 case 274 /* JsxAttributes */:
47834                     return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
47835                 case 273 /* JsxAttribute */: {
47836                     // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
47837                     var initializer = node.initializer;
47838                     return !!initializer && isContextSensitive(initializer);
47839                 }
47840                 case 276 /* JsxExpression */: {
47841                     // It is possible to that node.expression is undefined (e.g <div x={} />)
47842                     var expression = node.expression;
47843                     return !!expression && isContextSensitive(expression);
47844                 }
47845             }
47846             return false;
47847         }
47848         function isContextSensitiveFunctionLikeDeclaration(node) {
47849             return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
47850                 (hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
47851         }
47852         function hasContextSensitiveParameters(node) {
47853             // Functions with type parameters are not context sensitive.
47854             if (!node.typeParameters) {
47855                 // Functions with any parameters that lack type annotations are context sensitive.
47856                 if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
47857                     return true;
47858                 }
47859                 if (node.kind !== 202 /* ArrowFunction */) {
47860                     // If the first parameter is not an explicit 'this' parameter, then the function has
47861                     // an implicit 'this' parameter which is subject to contextual typing.
47862                     var parameter = ts.firstOrUndefined(node.parameters);
47863                     if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
47864                         return true;
47865                     }
47866                 }
47867             }
47868             return false;
47869         }
47870         function hasContextSensitiveReturnExpression(node) {
47871             // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
47872             return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body);
47873         }
47874         function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
47875             return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
47876                 isContextSensitiveFunctionLikeDeclaration(func);
47877         }
47878         function getTypeWithoutSignatures(type) {
47879             if (type.flags & 524288 /* Object */) {
47880                 var resolved = resolveStructuredTypeMembers(type);
47881                 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
47882                     var result = createObjectType(16 /* Anonymous */, type.symbol);
47883                     result.members = resolved.members;
47884                     result.properties = resolved.properties;
47885                     result.callSignatures = ts.emptyArray;
47886                     result.constructSignatures = ts.emptyArray;
47887                     return result;
47888                 }
47889             }
47890             else if (type.flags & 2097152 /* Intersection */) {
47891                 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
47892             }
47893             return type;
47894         }
47895         // TYPE CHECKING
47896         function isTypeIdenticalTo(source, target) {
47897             return isTypeRelatedTo(source, target, identityRelation);
47898         }
47899         function compareTypesIdentical(source, target) {
47900             return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
47901         }
47902         function compareTypesAssignable(source, target) {
47903             return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
47904         }
47905         function compareTypesSubtypeOf(source, target) {
47906             return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
47907         }
47908         function isTypeSubtypeOf(source, target) {
47909             return isTypeRelatedTo(source, target, subtypeRelation);
47910         }
47911         function isTypeAssignableTo(source, target) {
47912             return isTypeRelatedTo(source, target, assignableRelation);
47913         }
47914         // An object type S is considered to be derived from an object type T if
47915         // S is a union type and every constituent of S is derived from T,
47916         // T is a union type and S is derived from at least one constituent of T, or
47917         // S is a type variable with a base constraint that is derived from T,
47918         // T is one of the global types Object and Function and S is a subtype of T, or
47919         // T occurs directly or indirectly in an 'extends' clause of S.
47920         // Note that this check ignores type parameters and only considers the
47921         // inheritance hierarchy.
47922         function isTypeDerivedFrom(source, target) {
47923             return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
47924                 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
47925                     source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
47926                         target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
47927                             target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
47928                                 hasBaseType(source, getTargetType(target));
47929         }
47930         /**
47931          * This is *not* a bi-directional relationship.
47932          * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
47933          *
47934          * 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.
47935          * It is used to check following cases:
47936          *   - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
47937          *   - the types of `case` clause expressions and their respective `switch` expressions.
47938          *   - the type of an expression in a type assertion with the type being asserted.
47939          */
47940         function isTypeComparableTo(source, target) {
47941             return isTypeRelatedTo(source, target, comparableRelation);
47942         }
47943         function areTypesComparable(type1, type2) {
47944             return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
47945         }
47946         function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
47947             return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
47948         }
47949         /**
47950          * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
47951          * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
47952          */
47953         function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
47954             return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
47955         }
47956         function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
47957             if (isTypeRelatedTo(source, target, relation))
47958                 return true;
47959             if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
47960                 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
47961             }
47962             return false;
47963         }
47964         function isOrHasGenericConditional(type) {
47965             return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
47966         }
47967         function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
47968             if (!node || isOrHasGenericConditional(target))
47969                 return false;
47970             if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
47971                 && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
47972                 return true;
47973             }
47974             switch (node.kind) {
47975                 case 276 /* JsxExpression */:
47976                 case 200 /* ParenthesizedExpression */:
47977                     return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
47978                 case 209 /* BinaryExpression */:
47979                     switch (node.operatorToken.kind) {
47980                         case 62 /* EqualsToken */:
47981                         case 27 /* CommaToken */:
47982                             return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
47983                     }
47984                     break;
47985                 case 193 /* ObjectLiteralExpression */:
47986                     return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
47987                 case 192 /* ArrayLiteralExpression */:
47988                     return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
47989                 case 274 /* JsxAttributes */:
47990                     return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
47991                 case 202 /* ArrowFunction */:
47992                     return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
47993             }
47994             return false;
47995         }
47996         function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
47997             var callSignatures = getSignaturesOfType(source, 0 /* Call */);
47998             var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
47999             for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
48000                 var signatures = _a[_i];
48001                 if (ts.some(signatures, function (s) {
48002                     var returnType = getReturnTypeOfSignature(s);
48003                     return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
48004                 })) {
48005                     var resultObj = errorOutputContainer || {};
48006                     checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
48007                     var diagnostic = resultObj.errors[resultObj.errors.length - 1];
48008                     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));
48009                     return true;
48010                 }
48011             }
48012             return false;
48013         }
48014         function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48015             // Don't elaborate blocks
48016             if (ts.isBlock(node.body)) {
48017                 return false;
48018             }
48019             // Or functions with annotated parameter types
48020             if (ts.some(node.parameters, ts.hasType)) {
48021                 return false;
48022             }
48023             var sourceSig = getSingleCallSignature(source);
48024             if (!sourceSig) {
48025                 return false;
48026             }
48027             var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
48028             if (!ts.length(targetSignatures)) {
48029                 return false;
48030             }
48031             var returnExpression = node.body;
48032             var sourceReturn = getReturnTypeOfSignature(sourceSig);
48033             var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
48034             if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
48035                 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48036                 if (elaborated) {
48037                     return elaborated;
48038                 }
48039                 var resultObj = errorOutputContainer || {};
48040                 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
48041                 if (resultObj.errors) {
48042                     if (target.symbol && ts.length(target.symbol.declarations)) {
48043                         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));
48044                     }
48045                     if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0
48046                         // exclude cases where source itself is promisy - this way we don't make a suggestion when relating
48047                         // an IPromise and a Promise that are slightly different
48048                         && !getTypeOfPropertyOfType(sourceReturn, "then")
48049                         && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) {
48050                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async));
48051                     }
48052                     return true;
48053                 }
48054             }
48055             return false;
48056         }
48057         function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
48058             var idx = getIndexedAccessTypeOrUndefined(target, nameType);
48059             if (idx) {
48060                 return idx;
48061             }
48062             if (target.flags & 1048576 /* Union */) {
48063                 var best = getBestMatchingType(source, target);
48064                 if (best) {
48065                     return getIndexedAccessTypeOrUndefined(best, nameType);
48066                 }
48067             }
48068         }
48069         function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
48070             next.contextualType = sourcePropType;
48071             try {
48072                 return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType);
48073             }
48074             finally {
48075                 next.contextualType = undefined;
48076             }
48077         }
48078         /**
48079          * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
48080          * 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`
48081          * Otherwise, we issue an error on _every_ element which fail the assignability check
48082          */
48083         function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
48084             // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
48085             var reportedError = false;
48086             for (var status = iterator.next(); !status.done; status = iterator.next()) {
48087                 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
48088                 var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
48089                 if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
48090                     continue; // Don't elaborate on indexes on generic variables
48091                 var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
48092                 if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
48093                     var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48094                     if (elaborated) {
48095                         reportedError = true;
48096                     }
48097                     else {
48098                         // Issue error on the prop itself, since the prop couldn't elaborate the error
48099                         var resultObj = errorOutputContainer || {};
48100                         // Use the expression type, if available
48101                         var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
48102                         var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48103                         if (result && specificSource !== sourcePropType) {
48104                             // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
48105                             checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48106                         }
48107                         if (resultObj.errors) {
48108                             var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
48109                             var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
48110                             var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
48111                             var issuedElaboration = false;
48112                             if (!targetProp) {
48113                                 var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
48114                                     getIndexInfoOfType(target, 0 /* String */) ||
48115                                     undefined;
48116                                 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
48117                                     issuedElaboration = true;
48118                                     ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
48119                                 }
48120                             }
48121                             if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
48122                                 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
48123                                 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
48124                                     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)));
48125                                 }
48126                             }
48127                         }
48128                         reportedError = true;
48129                     }
48130                 }
48131             }
48132             return reportedError;
48133         }
48134         function generateJsxAttributes(node) {
48135             var _i, _a, prop;
48136             return __generator(this, function (_b) {
48137                 switch (_b.label) {
48138                     case 0:
48139                         if (!ts.length(node.properties))
48140                             return [2 /*return*/];
48141                         _i = 0, _a = node.properties;
48142                         _b.label = 1;
48143                     case 1:
48144                         if (!(_i < _a.length)) return [3 /*break*/, 4];
48145                         prop = _a[_i];
48146                         if (ts.isJsxSpreadAttribute(prop))
48147                             return [3 /*break*/, 3];
48148                         return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
48149                     case 2:
48150                         _b.sent();
48151                         _b.label = 3;
48152                     case 3:
48153                         _i++;
48154                         return [3 /*break*/, 1];
48155                     case 4: return [2 /*return*/];
48156                 }
48157             });
48158         }
48159         function generateJsxChildren(node, getInvalidTextDiagnostic) {
48160             var memberOffset, i, child, nameType, elem;
48161             return __generator(this, function (_a) {
48162                 switch (_a.label) {
48163                     case 0:
48164                         if (!ts.length(node.children))
48165                             return [2 /*return*/];
48166                         memberOffset = 0;
48167                         i = 0;
48168                         _a.label = 1;
48169                     case 1:
48170                         if (!(i < node.children.length)) return [3 /*break*/, 5];
48171                         child = node.children[i];
48172                         nameType = getLiteralType(i - memberOffset);
48173                         elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
48174                         if (!elem) return [3 /*break*/, 3];
48175                         return [4 /*yield*/, elem];
48176                     case 2:
48177                         _a.sent();
48178                         return [3 /*break*/, 4];
48179                     case 3:
48180                         memberOffset++;
48181                         _a.label = 4;
48182                     case 4:
48183                         i++;
48184                         return [3 /*break*/, 1];
48185                     case 5: return [2 /*return*/];
48186                 }
48187             });
48188         }
48189         function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
48190             switch (child.kind) {
48191                 case 276 /* JsxExpression */:
48192                     // child is of the type of the expression
48193                     return { errorNode: child, innerExpression: child.expression, nameType: nameType };
48194                 case 11 /* JsxText */:
48195                     if (child.containsOnlyTriviaWhiteSpaces) {
48196                         break; // Whitespace only jsx text isn't real jsx text
48197                     }
48198                     // child is a string
48199                     return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
48200                 case 266 /* JsxElement */:
48201                 case 267 /* JsxSelfClosingElement */:
48202                 case 270 /* JsxFragment */:
48203                     // child is of type JSX.Element
48204                     return { errorNode: child, innerExpression: child, nameType: nameType };
48205                 default:
48206                     return ts.Debug.assertNever(child, "Found invalid jsx child");
48207             }
48208         }
48209         function getSemanticJsxChildren(children) {
48210             return ts.filter(children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
48211         }
48212         function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48213             var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
48214             var invalidTextDiagnostic;
48215             if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
48216                 var containingElement = node.parent.parent;
48217                 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48218                 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48219                 var childrenNameType = getLiteralType(childrenPropName);
48220                 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
48221                 var validChildren = getSemanticJsxChildren(containingElement.children);
48222                 if (!ts.length(validChildren)) {
48223                     return result;
48224                 }
48225                 var moreThanOneRealChildren = ts.length(validChildren) > 1;
48226                 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
48227                 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
48228                 if (moreThanOneRealChildren) {
48229                     if (arrayLikeTargetParts !== neverType) {
48230                         var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
48231                         var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
48232                         result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
48233                     }
48234                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48235                         // arity mismatch
48236                         result = true;
48237                         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));
48238                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48239                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48240                         }
48241                     }
48242                 }
48243                 else {
48244                     if (nonArrayLikeTargetParts !== neverType) {
48245                         var child = validChildren[0];
48246                         var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
48247                         if (elem_1) {
48248                             result = elaborateElementwise((function () { return __generator(this, function (_a) {
48249                                 switch (_a.label) {
48250                                     case 0: return [4 /*yield*/, elem_1];
48251                                     case 1:
48252                                         _a.sent();
48253                                         return [2 /*return*/];
48254                                 }
48255                             }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
48256                         }
48257                     }
48258                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48259                         // arity mismatch
48260                         result = true;
48261                         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));
48262                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48263                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48264                         }
48265                     }
48266                 }
48267             }
48268             return result;
48269             function getInvalidTextualChildDiagnostic() {
48270                 if (!invalidTextDiagnostic) {
48271                     var tagNameText = ts.getTextOfNode(node.parent.tagName);
48272                     var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48273                     var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48274                     var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
48275                     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;
48276                     invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
48277                 }
48278                 return invalidTextDiagnostic;
48279             }
48280         }
48281         function generateLimitedTupleElements(node, target) {
48282             var len, i, elem, nameType;
48283             return __generator(this, function (_a) {
48284                 switch (_a.label) {
48285                     case 0:
48286                         len = ts.length(node.elements);
48287                         if (!len)
48288                             return [2 /*return*/];
48289                         i = 0;
48290                         _a.label = 1;
48291                     case 1:
48292                         if (!(i < len)) return [3 /*break*/, 4];
48293                         // 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
48294                         if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
48295                             return [3 /*break*/, 3];
48296                         elem = node.elements[i];
48297                         if (ts.isOmittedExpression(elem))
48298                             return [3 /*break*/, 3];
48299                         nameType = getLiteralType(i);
48300                         return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
48301                     case 2:
48302                         _a.sent();
48303                         _a.label = 3;
48304                     case 3:
48305                         i++;
48306                         return [3 /*break*/, 1];
48307                     case 4: return [2 /*return*/];
48308                 }
48309             });
48310         }
48311         function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48312             if (target.flags & 131068 /* Primitive */)
48313                 return false;
48314             if (isTupleLikeType(source)) {
48315                 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
48316             }
48317             // recreate a tuple from the elements, if possible
48318             // Since we're re-doing the expression type, we need to reapply the contextual type
48319             var oldContext = node.contextualType;
48320             node.contextualType = target;
48321             try {
48322                 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
48323                 node.contextualType = oldContext;
48324                 if (isTupleLikeType(tupleizedType)) {
48325                     return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
48326                 }
48327                 return false;
48328             }
48329             finally {
48330                 node.contextualType = oldContext;
48331             }
48332         }
48333         function generateObjectLiteralElements(node) {
48334             var _i, _a, prop, type, _b;
48335             return __generator(this, function (_c) {
48336                 switch (_c.label) {
48337                     case 0:
48338                         if (!ts.length(node.properties))
48339                             return [2 /*return*/];
48340                         _i = 0, _a = node.properties;
48341                         _c.label = 1;
48342                     case 1:
48343                         if (!(_i < _a.length)) return [3 /*break*/, 8];
48344                         prop = _a[_i];
48345                         if (ts.isSpreadAssignment(prop))
48346                             return [3 /*break*/, 7];
48347                         type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
48348                         if (!type || (type.flags & 131072 /* Never */)) {
48349                             return [3 /*break*/, 7];
48350                         }
48351                         _b = prop.kind;
48352                         switch (_b) {
48353                             case 164 /* SetAccessor */: return [3 /*break*/, 2];
48354                             case 163 /* GetAccessor */: return [3 /*break*/, 2];
48355                             case 161 /* MethodDeclaration */: return [3 /*break*/, 2];
48356                             case 282 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
48357                             case 281 /* PropertyAssignment */: return [3 /*break*/, 4];
48358                         }
48359                         return [3 /*break*/, 6];
48360                     case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
48361                     case 3:
48362                         _c.sent();
48363                         return [3 /*break*/, 7];
48364                     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 }];
48365                     case 5:
48366                         _c.sent();
48367                         return [3 /*break*/, 7];
48368                     case 6:
48369                         ts.Debug.assertNever(prop);
48370                         _c.label = 7;
48371                     case 7:
48372                         _i++;
48373                         return [3 /*break*/, 1];
48374                     case 8: return [2 /*return*/];
48375                 }
48376             });
48377         }
48378         function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48379             if (target.flags & 131068 /* Primitive */)
48380                 return false;
48381             return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
48382         }
48383         /**
48384          * This is *not* a bi-directional relationship.
48385          * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
48386          */
48387         function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
48388             return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
48389         }
48390         function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
48391             return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false, 
48392             /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
48393         }
48394         /**
48395          * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
48396          */
48397         function isAnySignature(s) {
48398             return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
48399                 signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
48400                 isTypeAny(getReturnTypeOfSignature(s));
48401         }
48402         /**
48403          * See signatureRelatedTo, compareSignaturesIdentical
48404          */
48405         function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
48406             // TODO (drosen): De-duplicate code between related functions.
48407             if (source === target) {
48408                 return -1 /* True */;
48409             }
48410             if (isAnySignature(target)) {
48411                 return -1 /* True */;
48412             }
48413             var targetCount = getParameterCount(target);
48414             var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
48415                 (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
48416             if (sourceHasMoreParameters) {
48417                 return 0 /* False */;
48418             }
48419             if (source.typeParameters && source.typeParameters !== target.typeParameters) {
48420                 target = getCanonicalSignature(target);
48421                 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
48422             }
48423             var sourceCount = getParameterCount(source);
48424             var sourceRestType = getNonArrayRestType(source);
48425             var targetRestType = getNonArrayRestType(target);
48426             if (sourceRestType || targetRestType) {
48427                 void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
48428             }
48429             if (sourceRestType && targetRestType && sourceCount !== targetCount) {
48430                 // We're not able to relate misaligned complex rest parameters
48431                 return 0 /* False */;
48432             }
48433             var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
48434             var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 161 /* MethodDeclaration */ &&
48435                 kind !== 160 /* MethodSignature */ && kind !== 162 /* Constructor */;
48436             var result = -1 /* True */;
48437             var sourceThisType = getThisTypeOfSignature(source);
48438             if (sourceThisType && sourceThisType !== voidType) {
48439                 var targetThisType = getThisTypeOfSignature(target);
48440                 if (targetThisType) {
48441                     // void sources are assignable to anything.
48442                     var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
48443                         || compareTypes(targetThisType, sourceThisType, reportErrors);
48444                     if (!related) {
48445                         if (reportErrors) {
48446                             errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
48447                         }
48448                         return 0 /* False */;
48449                     }
48450                     result &= related;
48451                 }
48452             }
48453             var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
48454             var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
48455             for (var i = 0; i < paramCount; i++) {
48456                 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i);
48457                 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i);
48458                 // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
48459                 // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
48460                 // they naturally relate only contra-variantly). However, if the source and target parameters both have
48461                 // function types with a single call signature, we know we are relating two callback parameters. In
48462                 // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
48463                 // similar to return values, callback parameters are output positions. This means that a Promise<T>,
48464                 // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
48465                 // with respect to T.
48466                 var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
48467                 var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
48468                 var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
48469                     (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
48470                 var related = callbacks ?
48471                     compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
48472                     !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
48473                 // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
48474                 if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
48475                     related = 0 /* False */;
48476                 }
48477                 if (!related) {
48478                     if (reportErrors) {
48479                         errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
48480                     }
48481                     return 0 /* False */;
48482                 }
48483                 result &= related;
48484             }
48485             if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
48486                 // If a signature resolution is already in-flight, skip issuing a circularity error
48487                 // here and just use the `any` type directly
48488                 var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
48489                     : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
48490                         : getReturnTypeOfSignature(target);
48491                 if (targetReturnType === voidType) {
48492                     return result;
48493                 }
48494                 var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
48495                     : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
48496                         : getReturnTypeOfSignature(source);
48497                 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
48498                 var targetTypePredicate = getTypePredicateOfSignature(target);
48499                 if (targetTypePredicate) {
48500                     var sourceTypePredicate = getTypePredicateOfSignature(source);
48501                     if (sourceTypePredicate) {
48502                         result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
48503                     }
48504                     else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
48505                         if (reportErrors) {
48506                             errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
48507                         }
48508                         return 0 /* False */;
48509                     }
48510                 }
48511                 else {
48512                     // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
48513                     // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
48514                     // wouldn't be co-variant for T without this rule.
48515                     result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
48516                         compareTypes(sourceReturnType, targetReturnType, reportErrors);
48517                     if (!result && reportErrors && incompatibleErrorReporter) {
48518                         incompatibleErrorReporter(sourceReturnType, targetReturnType);
48519                     }
48520                 }
48521             }
48522             return result;
48523         }
48524         function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
48525             if (source.kind !== target.kind) {
48526                 if (reportErrors) {
48527                     errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
48528                     errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48529                 }
48530                 return 0 /* False */;
48531             }
48532             if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
48533                 if (source.parameterIndex !== target.parameterIndex) {
48534                     if (reportErrors) {
48535                         errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
48536                         errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48537                     }
48538                     return 0 /* False */;
48539                 }
48540             }
48541             var related = source.type === target.type ? -1 /* True */ :
48542                 source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
48543                     0 /* False */;
48544             if (related === 0 /* False */ && reportErrors) {
48545                 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48546             }
48547             return related;
48548         }
48549         function isImplementationCompatibleWithOverload(implementation, overload) {
48550             var erasedSource = getErasedSignature(implementation);
48551             var erasedTarget = getErasedSignature(overload);
48552             // First see if the return types are compatible in either direction.
48553             var sourceReturnType = getReturnTypeOfSignature(erasedSource);
48554             var targetReturnType = getReturnTypeOfSignature(erasedTarget);
48555             if (targetReturnType === voidType
48556                 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
48557                 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
48558                 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
48559             }
48560             return false;
48561         }
48562         function isEmptyResolvedType(t) {
48563             return t !== anyFunctionType &&
48564                 t.properties.length === 0 &&
48565                 t.callSignatures.length === 0 &&
48566                 t.constructSignatures.length === 0 &&
48567                 !t.stringIndexInfo &&
48568                 !t.numberIndexInfo;
48569         }
48570         function isEmptyObjectType(type) {
48571             return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
48572                 type.flags & 67108864 /* NonPrimitive */ ? true :
48573                     type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
48574                         type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
48575                             false;
48576         }
48577         function isEmptyAnonymousObjectType(type) {
48578             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type);
48579         }
48580         function isStringIndexSignatureOnlyType(type) {
48581             return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, 0 /* String */) && !getIndexInfoOfType(type, 1 /* Number */) ||
48582                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
48583                 false;
48584         }
48585         function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
48586             if (sourceSymbol === targetSymbol) {
48587                 return true;
48588             }
48589             var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
48590             var entry = enumRelation.get(id);
48591             if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
48592                 return !!(entry & 1 /* Succeeded */);
48593             }
48594             if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
48595                 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48596                 return false;
48597             }
48598             var targetEnumType = getTypeOfSymbol(targetSymbol);
48599             for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
48600                 var property = _a[_i];
48601                 if (property.flags & 8 /* EnumMember */) {
48602                     var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
48603                     if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
48604                         if (errorReporter) {
48605                             errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
48606                             enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48607                         }
48608                         else {
48609                             enumRelation.set(id, 2 /* Failed */);
48610                         }
48611                         return false;
48612                     }
48613                 }
48614             }
48615             enumRelation.set(id, 1 /* Succeeded */);
48616             return true;
48617         }
48618         function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
48619             var s = source.flags;
48620             var t = target.flags;
48621             if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
48622                 return true;
48623             if (t & 131072 /* Never */)
48624                 return false;
48625             if (s & 132 /* StringLike */ && t & 4 /* String */)
48626                 return true;
48627             if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
48628                 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48629                 source.value === target.value)
48630                 return true;
48631             if (s & 296 /* NumberLike */ && t & 8 /* Number */)
48632                 return true;
48633             if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
48634                 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48635                 source.value === target.value)
48636                 return true;
48637             if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
48638                 return true;
48639             if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
48640                 return true;
48641             if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
48642                 return true;
48643             if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48644                 return true;
48645             if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
48646                 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48647                     return true;
48648                 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
48649                     source.value === target.value &&
48650                     isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
48651                     return true;
48652             }
48653             if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
48654                 return true;
48655             if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
48656                 return true;
48657             if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
48658                 return true;
48659             if (relation === assignableRelation || relation === comparableRelation) {
48660                 if (s & 1 /* Any */)
48661                     return true;
48662                 // Type number or any numeric literal type is assignable to any numeric enum type or any
48663                 // numeric enum literal type. This rule exists for backwards compatibility reasons because
48664                 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
48665                 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
48666                     return true;
48667             }
48668             return false;
48669         }
48670         function isTypeRelatedTo(source, target, relation) {
48671             if (isFreshLiteralType(source)) {
48672                 source = source.regularType;
48673             }
48674             if (isFreshLiteralType(target)) {
48675                 target = target.regularType;
48676             }
48677             if (source === target) {
48678                 return true;
48679             }
48680             if (relation !== identityRelation) {
48681                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
48682                     return true;
48683                 }
48684             }
48685             else {
48686                 if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) &&
48687                     source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */))
48688                     return false;
48689             }
48690             if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
48691                 var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
48692                 if (related !== undefined) {
48693                     return !!(related & 1 /* Succeeded */);
48694                 }
48695             }
48696             if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) {
48697                 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
48698             }
48699             return false;
48700         }
48701         function isIgnoredJsxProperty(source, sourceProp) {
48702             return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName);
48703         }
48704         function getNormalizedType(type, writing) {
48705             while (true) {
48706                 var t = isFreshLiteralType(type) ? type.regularType :
48707                     ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
48708                         type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) :
48709                             type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute :
48710                                 type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
48711                                     type;
48712                 if (t === type)
48713                     break;
48714                 type = t;
48715             }
48716             return type;
48717         }
48718         /**
48719          * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
48720          * @param source The left-hand-side of the relation.
48721          * @param target The right-hand-side of the relation.
48722          * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
48723          * Used as both to determine which checks are performed and as a cache of previously computed results.
48724          * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
48725          * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
48726          * @param containingMessageChain A chain of errors to prepend any new errors found.
48727          * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
48728          */
48729         function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
48730             var errorInfo;
48731             var relatedInfo;
48732             var maybeKeys;
48733             var sourceStack;
48734             var targetStack;
48735             var maybeCount = 0;
48736             var depth = 0;
48737             var expandingFlags = 0 /* None */;
48738             var overflow = false;
48739             var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
48740             var lastSkippedInfo;
48741             var incompatibleStack = [];
48742             var inPropertyCheck = false;
48743             ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
48744             var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
48745             if (incompatibleStack.length) {
48746                 reportIncompatibleStack();
48747             }
48748             if (overflow) {
48749                 var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
48750                 if (errorOutputContainer) {
48751                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48752                 }
48753             }
48754             else if (errorInfo) {
48755                 if (containingMessageChain) {
48756                     var chain = containingMessageChain();
48757                     if (chain) {
48758                         ts.concatenateDiagnosticMessageChains(chain, errorInfo);
48759                         errorInfo = chain;
48760                     }
48761                 }
48762                 var relatedInformation = void 0;
48763                 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
48764                 if (headMessage && errorNode && !result && source.symbol) {
48765                     var links = getSymbolLinks(source.symbol);
48766                     if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
48767                         var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
48768                         if (helpfulRetry) {
48769                             // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
48770                             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);
48771                             relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
48772                         }
48773                     }
48774                 }
48775                 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
48776                 if (relatedInfo) {
48777                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInfo));
48778                 }
48779                 if (errorOutputContainer) {
48780                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48781                 }
48782                 if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
48783                     diagnostics.add(diag);
48784                 }
48785             }
48786             if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
48787                 ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
48788             }
48789             return result !== 0 /* False */;
48790             function resetErrorInfo(saved) {
48791                 errorInfo = saved.errorInfo;
48792                 lastSkippedInfo = saved.lastSkippedInfo;
48793                 incompatibleStack = saved.incompatibleStack;
48794                 overrideNextErrorInfo = saved.overrideNextErrorInfo;
48795                 relatedInfo = saved.relatedInfo;
48796             }
48797             function captureErrorCalculationState() {
48798                 return {
48799                     errorInfo: errorInfo,
48800                     lastSkippedInfo: lastSkippedInfo,
48801                     incompatibleStack: incompatibleStack.slice(),
48802                     overrideNextErrorInfo: overrideNextErrorInfo,
48803                     relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
48804                 };
48805             }
48806             function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
48807                 overrideNextErrorInfo++; // Suppress the next relation error
48808                 lastSkippedInfo = undefined; // Reset skipped info cache
48809                 incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
48810             }
48811             function reportIncompatibleStack() {
48812                 var stack = incompatibleStack;
48813                 incompatibleStack = [];
48814                 var info = lastSkippedInfo;
48815                 lastSkippedInfo = undefined;
48816                 if (stack.length === 1) {
48817                     reportError.apply(void 0, stack[0]);
48818                     if (info) {
48819                         // Actually do the last relation error
48820                         reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
48821                     }
48822                     return;
48823                 }
48824                 // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
48825                 // we can build from left to right
48826                 var path = "";
48827                 var secondaryRootErrors = [];
48828                 while (stack.length) {
48829                     var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
48830                     switch (msg.code) {
48831                         case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
48832                             // Parenthesize a `new` if there is one
48833                             if (path.indexOf("new ") === 0) {
48834                                 path = "(" + path + ")";
48835                             }
48836                             var str = "" + args[0];
48837                             // If leading, just print back the arg (irrespective of if it's a valid identifier)
48838                             if (path.length === 0) {
48839                                 path = "" + str;
48840                             }
48841                             // Otherwise write a dotted name if possible
48842                             else if (ts.isIdentifierText(str, compilerOptions.target)) {
48843                                 path = path + "." + str;
48844                             }
48845                             // Failing that, check if the name is already a computed name
48846                             else if (str[0] === "[" && str[str.length - 1] === "]") {
48847                                 path = "" + path + str;
48848                             }
48849                             // And finally write out a computed name as a last resort
48850                             else {
48851                                 path = path + "[" + str + "]";
48852                             }
48853                             break;
48854                         }
48855                         case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
48856                         case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
48857                         case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
48858                         case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
48859                             if (path.length === 0) {
48860                                 // Don't flatten signature compatability errors at the start of a chain - instead prefer
48861                                 // to unify (the with no arguments bit is excessive for printback) and print them back
48862                                 var mappedMsg = msg;
48863                                 if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
48864                                     mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
48865                                 }
48866                                 else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
48867                                     mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
48868                                 }
48869                                 secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
48870                             }
48871                             else {
48872                                 var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
48873                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
48874                                     ? "new "
48875                                     : "";
48876                                 var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
48877                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
48878                                     ? ""
48879                                     : "...";
48880                                 path = "" + prefix + path + "(" + params + ")";
48881                             }
48882                             break;
48883                         }
48884                         default:
48885                             return ts.Debug.fail("Unhandled Diagnostic: " + msg.code);
48886                     }
48887                 }
48888                 if (path) {
48889                     reportError(path[path.length - 1] === ")"
48890                         ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
48891                         : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
48892                 }
48893                 else {
48894                     // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
48895                     secondaryRootErrors.shift();
48896                 }
48897                 for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
48898                     var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
48899                     var originalValue = msg.elidedInCompatabilityPyramid;
48900                     msg.elidedInCompatabilityPyramid = false; // Teporarily override elision to ensure error is reported
48901                     reportError.apply(void 0, __spreadArrays([msg], args));
48902                     msg.elidedInCompatabilityPyramid = originalValue;
48903                 }
48904                 if (info) {
48905                     // Actually do the last relation error
48906                     reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
48907                 }
48908             }
48909             function reportError(message, arg0, arg1, arg2, arg3) {
48910                 ts.Debug.assert(!!errorNode);
48911                 if (incompatibleStack.length)
48912                     reportIncompatibleStack();
48913                 if (message.elidedInCompatabilityPyramid)
48914                     return;
48915                 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
48916             }
48917             function associateRelatedInfo(info) {
48918                 ts.Debug.assert(!!errorInfo);
48919                 if (!relatedInfo) {
48920                     relatedInfo = [info];
48921                 }
48922                 else {
48923                     relatedInfo.push(info);
48924                 }
48925             }
48926             function reportRelationError(message, source, target) {
48927                 if (incompatibleStack.length)
48928                     reportIncompatibleStack();
48929                 var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
48930                 if (target.flags & 262144 /* TypeParameter */) {
48931                     var constraint = getBaseConstraintOfType(target);
48932                     var constraintElab = constraint && isTypeAssignableTo(source, constraint);
48933                     if (constraintElab) {
48934                         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));
48935                     }
48936                     else {
48937                         reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, sourceType);
48938                     }
48939                 }
48940                 if (!message) {
48941                     if (relation === comparableRelation) {
48942                         message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
48943                     }
48944                     else if (sourceType === targetType) {
48945                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
48946                     }
48947                     else {
48948                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
48949                     }
48950                 }
48951                 reportError(message, sourceType, targetType);
48952             }
48953             function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
48954                 var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
48955                 var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
48956                 if ((globalStringType === source && stringType === target) ||
48957                     (globalNumberType === source && numberType === target) ||
48958                     (globalBooleanType === source && booleanType === target) ||
48959                     (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
48960                     reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
48961                 }
48962             }
48963             /**
48964              * Try and elaborate array and tuple errors. Returns false
48965              * if we have found an elaboration, or we should ignore
48966              * any other elaborations when relating the `source` and
48967              * `target` types.
48968              */
48969             function tryElaborateArrayLikeErrors(source, target, reportErrors) {
48970                 /**
48971                  * The spec for elaboration is:
48972                  * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
48973                  * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
48974                  * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
48975                  * - If the source an array then skip property elaborations if the target is a tuple.
48976                  */
48977                 if (isTupleType(source)) {
48978                     if (source.target.readonly && isMutableArrayOrTuple(target)) {
48979                         if (reportErrors) {
48980                             reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
48981                         }
48982                         return false;
48983                     }
48984                     return isTupleType(target) || isArrayType(target);
48985                 }
48986                 if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
48987                     if (reportErrors) {
48988                         reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
48989                     }
48990                     return false;
48991                 }
48992                 if (isTupleType(target)) {
48993                     return isArrayType(source);
48994                 }
48995                 return true;
48996             }
48997             /**
48998              * Compare two types and return
48999              * * Ternary.True if they are related with no assumptions,
49000              * * Ternary.Maybe if they are related with assumptions of other relationships, or
49001              * * Ternary.False if they are not related.
49002              */
49003             function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) {
49004                 if (reportErrors === void 0) { reportErrors = false; }
49005                 if (intersectionState === void 0) { intersectionState = 0 /* None */; }
49006                 // Before normalization: if `source` is type an object type, and `target` is primitive,
49007                 // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result
49008                 if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) {
49009                     if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
49010                         return -1 /* True */;
49011                     }
49012                     reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */));
49013                     return 0 /* False */;
49014                 }
49015                 // Normalize the source and target types: Turn fresh literal types into regular literal types,
49016                 // turn deferred type references into regular type references, simplify indexed access and
49017                 // conditional types, and resolve substitution types to either the substitution (on the source
49018                 // side) or the type variable (on the target side).
49019                 var source = getNormalizedType(originalSource, /*writing*/ false);
49020                 var target = getNormalizedType(originalTarget, /*writing*/ true);
49021                 if (source === target)
49022                     return -1 /* True */;
49023                 if (relation === identityRelation) {
49024                     return isIdenticalTo(source, target);
49025                 }
49026                 // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
49027                 // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
49028                 // as we break down the _target_ union first, _then_ get the source constraint - so for every
49029                 // member of the target, we attempt to find a match in the source. This avoids that in cases where
49030                 // the target is exactly the constraint.
49031                 if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
49032                     return -1 /* True */;
49033                 }
49034                 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
49035                 // If so, reporting the `null` and `undefined` in the type is hardly useful.
49036                 // First, see if we're even relating an object type to a union.
49037                 // Then see if the target is stripped down to a single non-union type.
49038                 // Note
49039                 //  * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
49040                 //    since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
49041                 //    when dealing with generics.
49042                 //  * We also don't deal with primitive source types, since we already halt elaboration below.
49043                 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
49044                     target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
49045                     var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
49046                     if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
49047                         if (source === nullStrippedTarget)
49048                             return -1 /* True */;
49049                         target = nullStrippedTarget;
49050                     }
49051                 }
49052                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
49053                     isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
49054                     return -1 /* True */;
49055                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49056                 var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */);
49057                 if (isPerformingExcessPropertyChecks) {
49058                     if (hasExcessProperties(source, target, reportErrors)) {
49059                         if (reportErrors) {
49060                             reportRelationError(headMessage, source, target);
49061                         }
49062                         return 0 /* False */;
49063                     }
49064                 }
49065                 var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
49066                     source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
49067                     target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
49068                     (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
49069                 if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
49070                     if (reportErrors) {
49071                         var calls = getSignaturesOfType(source, 0 /* Call */);
49072                         var constructs = getSignaturesOfType(source, 1 /* Construct */);
49073                         if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
49074                             constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
49075                             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));
49076                         }
49077                         else {
49078                             reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
49079                         }
49080                     }
49081                     return 0 /* False */;
49082                 }
49083                 var result = 0 /* False */;
49084                 var saveErrorInfo = captureErrorCalculationState();
49085                 // Note that these checks are specifically ordered to produce correct results. In particular,
49086                 // we need to deconstruct unions before intersections (because unions are always at the top),
49087                 // and we need to handle "each" relations before "some" relations for the same kind of type.
49088                 if (source.flags & 1048576 /* Union */) {
49089                     result = relation === comparableRelation ?
49090                         someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
49091                         eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState);
49092                 }
49093                 else {
49094                     if (target.flags & 1048576 /* Union */) {
49095                         result = typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
49096                     }
49097                     else if (target.flags & 2097152 /* Intersection */) {
49098                         result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
49099                     }
49100                     else if (source.flags & 2097152 /* Intersection */) {
49101                         // Check to see if any constituents of the intersection are immediately related to the target.
49102                         //
49103                         // Don't report errors though. Checking whether a constituent is related to the source is not actually
49104                         // useful and leads to some confusing error messages. Instead it is better to let the below checks
49105                         // take care of this, or to not elaborate at all. For instance,
49106                         //
49107                         //    - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
49108                         //
49109                         //    - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
49110                         //          than to report that 'D' is not assignable to 'A' or 'B'.
49111                         //
49112                         //    - For a primitive type or type parameter (such as 'number = A & B') there is no point in
49113                         //          breaking the intersection apart.
49114                         result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
49115                     }
49116                     if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) {
49117                         if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
49118                             resetErrorInfo(saveErrorInfo);
49119                         }
49120                     }
49121                 }
49122                 if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
49123                     // The combined constraint of an intersection type is the intersection of the constraints of
49124                     // the constituents. When an intersection type contains instantiable types with union type
49125                     // constraints, there are situations where we need to examine the combined constraint. One is
49126                     // when the target is a union type. Another is when the intersection contains types belonging
49127                     // to one of the disjoint domains. For example, given type variables T and U, each with the
49128                     // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
49129                     // we need to check this constraint against a union on the target side. Also, given a type
49130                     // variable V constrained to 'string | number', 'V & number' has a combined constraint of
49131                     // 'string & number | number & number' which reduces to just 'number'.
49132                     // This also handles type parameters, as a type parameter with a union constraint compared against a union
49133                     // needs to have its constraint hoisted into an intersection with said type parameter, this way
49134                     // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
49135                     // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
49136                     var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
49137                     if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
49138                         if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
49139                             // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
49140                             if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49141                                 resetErrorInfo(saveErrorInfo);
49142                             }
49143                         }
49144                     }
49145                 }
49146                 // For certain combinations involving intersections and optional, excess, or mismatched properties we need
49147                 // an extra property check where the intersection is viewed as a single object. The following are motivating
49148                 // examples that all should be errors, but aren't without this extra property check:
49149                 //
49150                 //   let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 };  // Nested excess property
49151                 //
49152                 //   declare let wrong: { a: { y: string } };
49153                 //   let weak: { a?: { x?: number } } & { c?: string } = wrong;  // Nested weak object type
49154                 //
49155                 //   function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
49156                 //     x = y;  // Mismatched property in source intersection
49157                 //   }
49158                 //
49159                 // We suppress recursive intersection property checks because they can generate lots of work when relating
49160                 // recursive intersections that are structurally similar but not exactly identical. See #37854.
49161                 if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
49162                     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 */); }))) {
49163                     inPropertyCheck = true;
49164                     result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */);
49165                     inPropertyCheck = false;
49166                 }
49167                 reportErrorResults(source, target, result, isComparingJsxAttributes);
49168                 return result;
49169                 function reportErrorResults(source, target, result, isComparingJsxAttributes) {
49170                     if (!result && reportErrors) {
49171                         source = originalSource.aliasSymbol ? originalSource : source;
49172                         target = originalTarget.aliasSymbol ? originalTarget : target;
49173                         var maybeSuppress = overrideNextErrorInfo > 0;
49174                         if (maybeSuppress) {
49175                             overrideNextErrorInfo--;
49176                         }
49177                         if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
49178                             var currentError = errorInfo;
49179                             tryElaborateArrayLikeErrors(source, target, reportErrors);
49180                             if (errorInfo !== currentError) {
49181                                 maybeSuppress = !!errorInfo;
49182                             }
49183                         }
49184                         if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
49185                             tryElaborateErrorsForPrimitivesAndObjects(source, target);
49186                         }
49187                         else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
49188                             reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
49189                         }
49190                         else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
49191                             var targetTypes = target.types;
49192                             var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
49193                             var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
49194                             if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
49195                                 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
49196                                 // do not report top error
49197                                 return result;
49198                             }
49199                         }
49200                         else {
49201                             errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
49202                         }
49203                         if (!headMessage && maybeSuppress) {
49204                             lastSkippedInfo = [source, target];
49205                             // Used by, eg, missing property checking to replace the top-level message with a more informative one
49206                             return result;
49207                         }
49208                         reportRelationError(headMessage, source, target);
49209                     }
49210                 }
49211             }
49212             function isIdenticalTo(source, target) {
49213                 var flags = source.flags & target.flags;
49214                 if (!(flags & 66584576 /* Substructure */)) {
49215                     return 0 /* False */;
49216                 }
49217                 if (flags & 3145728 /* UnionOrIntersection */) {
49218                     var result_5 = eachTypeRelatedToSomeType(source, target);
49219                     if (result_5) {
49220                         result_5 &= eachTypeRelatedToSomeType(target, source);
49221                     }
49222                     return result_5;
49223                 }
49224                 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */);
49225             }
49226             function getTypeOfPropertyInTypes(types, name) {
49227                 var appendPropType = function (propTypes, type) {
49228                     type = getApparentType(type);
49229                     var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
49230                     var propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || undefinedType;
49231                     return ts.append(propTypes, propType);
49232                 };
49233                 return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
49234             }
49235             function hasExcessProperties(source, target, reportErrors) {
49236                 if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
49237                     return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
49238                 }
49239                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49240                 if ((relation === assignableRelation || relation === comparableRelation) &&
49241                     (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
49242                     return false;
49243                 }
49244                 var reducedTarget = target;
49245                 var checkTypes;
49246                 if (target.flags & 1048576 /* Union */) {
49247                     reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
49248                     checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
49249                 }
49250                 var _loop_13 = function (prop) {
49251                     if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
49252                         if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
49253                             if (reportErrors) {
49254                                 // Report error in terms of object types in the target as those are the only ones
49255                                 // we check in isKnownProperty.
49256                                 var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
49257                                 // We know *exactly* where things went wrong when comparing the types.
49258                                 // Use this property as the error node as this will be more helpful in
49259                                 // reasoning about what went wrong.
49260                                 if (!errorNode)
49261                                     return { value: ts.Debug.fail() };
49262                                 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
49263                                     // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
49264                                     // However, using an object-literal error message will be very confusing to the users so we give different a message.
49265                                     // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages)
49266                                     if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
49267                                         // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
49268                                         // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
49269                                         errorNode = prop.valueDeclaration.name;
49270                                     }
49271                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget));
49272                                 }
49273                                 else {
49274                                     // use the property's value declaration if the property is assigned inside the literal itself
49275                                     var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
49276                                     var suggestion = void 0;
49277                                     if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
49278                                         var propDeclaration = prop.valueDeclaration;
49279                                         ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
49280                                         errorNode = propDeclaration;
49281                                         var name = propDeclaration.name;
49282                                         if (ts.isIdentifier(name)) {
49283                                             suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
49284                                         }
49285                                     }
49286                                     if (suggestion !== undefined) {
49287                                         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);
49288                                     }
49289                                     else {
49290                                         reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
49291                                     }
49292                                 }
49293                             }
49294                             return { value: true };
49295                         }
49296                         if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), reportErrors)) {
49297                             if (reportErrors) {
49298                                 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
49299                             }
49300                             return { value: true };
49301                         }
49302                     }
49303                 };
49304                 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
49305                     var prop = _a[_i];
49306                     var state_5 = _loop_13(prop);
49307                     if (typeof state_5 === "object")
49308                         return state_5.value;
49309                 }
49310                 return false;
49311             }
49312             function shouldCheckAsExcessProperty(prop, container) {
49313                 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
49314             }
49315             function eachTypeRelatedToSomeType(source, target) {
49316                 var result = -1 /* True */;
49317                 var sourceTypes = source.types;
49318                 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
49319                     var sourceType = sourceTypes_1[_i];
49320                     var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
49321                     if (!related) {
49322                         return 0 /* False */;
49323                     }
49324                     result &= related;
49325                 }
49326                 return result;
49327             }
49328             function typeRelatedToSomeType(source, target, reportErrors) {
49329                 var targetTypes = target.types;
49330                 if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
49331                     return -1 /* True */;
49332                 }
49333                 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
49334                     var type = targetTypes_1[_i];
49335                     var related = isRelatedTo(source, type, /*reportErrors*/ false);
49336                     if (related) {
49337                         return related;
49338                     }
49339                 }
49340                 if (reportErrors) {
49341                     var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
49342                     isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
49343                 }
49344                 return 0 /* False */;
49345             }
49346             function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
49347                 var result = -1 /* True */;
49348                 var targetTypes = target.types;
49349                 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
49350                     var targetType = targetTypes_2[_i];
49351                     var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, intersectionState);
49352                     if (!related) {
49353                         return 0 /* False */;
49354                     }
49355                     result &= related;
49356                 }
49357                 return result;
49358             }
49359             function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
49360                 var sourceTypes = source.types;
49361                 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
49362                     return -1 /* True */;
49363                 }
49364                 var len = sourceTypes.length;
49365                 for (var i = 0; i < len; i++) {
49366                     var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
49367                     if (related) {
49368                         return related;
49369                     }
49370                 }
49371                 return 0 /* False */;
49372             }
49373             function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
49374                 var result = -1 /* True */;
49375                 var sourceTypes = source.types;
49376                 for (var i = 0; i < sourceTypes.length; i++) {
49377                     var sourceType = sourceTypes[i];
49378                     if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) {
49379                         // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
49380                         var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
49381                         if (related_1) {
49382                             result &= related_1;
49383                             continue;
49384                         }
49385                     }
49386                     var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState);
49387                     if (!related) {
49388                         return 0 /* False */;
49389                     }
49390                     result &= related;
49391                 }
49392                 return result;
49393             }
49394             function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
49395                 if (sources === void 0) { sources = ts.emptyArray; }
49396                 if (targets === void 0) { targets = ts.emptyArray; }
49397                 if (variances === void 0) { variances = ts.emptyArray; }
49398                 if (sources.length !== targets.length && relation === identityRelation) {
49399                     return 0 /* False */;
49400                 }
49401                 var length = sources.length <= targets.length ? sources.length : targets.length;
49402                 var result = -1 /* True */;
49403                 for (var i = 0; i < length; i++) {
49404                     // When variance information isn't available we default to covariance. This happens
49405                     // in the process of computing variance information for recursive types and when
49406                     // comparing 'this' type arguments.
49407                     var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
49408                     var variance = varianceFlags & 7 /* VarianceMask */;
49409                     // We ignore arguments for independent type parameters (because they're never witnessed).
49410                     if (variance !== 4 /* Independent */) {
49411                         var s = sources[i];
49412                         var t = targets[i];
49413                         var related = -1 /* True */;
49414                         if (varianceFlags & 8 /* Unmeasurable */) {
49415                             // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
49416                             // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
49417                             // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
49418                             related = relation === identityRelation ? isRelatedTo(s, t, /*reportErrors*/ false) : compareTypesIdentical(s, t);
49419                         }
49420                         else if (variance === 1 /* Covariant */) {
49421                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49422                         }
49423                         else if (variance === 2 /* Contravariant */) {
49424                             related = isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49425                         }
49426                         else if (variance === 3 /* Bivariant */) {
49427                             // In the bivariant case we first compare contravariantly without reporting
49428                             // errors. Then, if that doesn't succeed, we compare covariantly with error
49429                             // reporting. Thus, error elaboration will be based on the the covariant check,
49430                             // which is generally easier to reason about.
49431                             related = isRelatedTo(t, s, /*reportErrors*/ false);
49432                             if (!related) {
49433                                 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49434                             }
49435                         }
49436                         else {
49437                             // In the invariant case we first compare covariantly, and only when that
49438                             // succeeds do we proceed to compare contravariantly. Thus, error elaboration
49439                             // will typically be based on the covariant check.
49440                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49441                             if (related) {
49442                                 related &= isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49443                             }
49444                         }
49445                         if (!related) {
49446                             return 0 /* False */;
49447                         }
49448                         result &= related;
49449                     }
49450                 }
49451                 return result;
49452             }
49453             // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
49454             // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
49455             // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
49456             // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
49457             // and issue an error. Otherwise, actually compare the structure of the two types.
49458             function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState) {
49459                 if (overflow) {
49460                     return 0 /* False */;
49461                 }
49462                 var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation);
49463                 var entry = relation.get(id);
49464                 if (entry !== undefined) {
49465                     if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
49466                         // We are elaborating errors and the cached result is an unreported failure. The result will be reported
49467                         // as a failure, and should be updated as a reported failure by the bottom of this function.
49468                     }
49469                     else {
49470                         if (outofbandVarianceMarkerHandler) {
49471                             // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
49472                             var saved = entry & 24 /* ReportsMask */;
49473                             if (saved & 8 /* ReportsUnmeasurable */) {
49474                                 instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers));
49475                             }
49476                             if (saved & 16 /* ReportsUnreliable */) {
49477                                 instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
49478                             }
49479                         }
49480                         return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
49481                     }
49482                 }
49483                 if (!maybeKeys) {
49484                     maybeKeys = [];
49485                     sourceStack = [];
49486                     targetStack = [];
49487                 }
49488                 else {
49489                     for (var i = 0; i < maybeCount; i++) {
49490                         // If source and target are already being compared, consider them related with assumptions
49491                         if (id === maybeKeys[i]) {
49492                             return 1 /* Maybe */;
49493                         }
49494                     }
49495                     if (depth === 100) {
49496                         overflow = true;
49497                         return 0 /* False */;
49498                     }
49499                 }
49500                 var maybeStart = maybeCount;
49501                 maybeKeys[maybeCount] = id;
49502                 maybeCount++;
49503                 sourceStack[depth] = source;
49504                 targetStack[depth] = target;
49505                 depth++;
49506                 var saveExpandingFlags = expandingFlags;
49507                 if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
49508                     expandingFlags |= 1 /* Source */;
49509                 if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
49510                     expandingFlags |= 2 /* Target */;
49511                 var originalHandler;
49512                 var propagatingVarianceFlags = 0;
49513                 if (outofbandVarianceMarkerHandler) {
49514                     originalHandler = outofbandVarianceMarkerHandler;
49515                     outofbandVarianceMarkerHandler = function (onlyUnreliable) {
49516                         propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
49517                         return originalHandler(onlyUnreliable);
49518                     };
49519                 }
49520                 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 1 /* Maybe */;
49521                 if (outofbandVarianceMarkerHandler) {
49522                     outofbandVarianceMarkerHandler = originalHandler;
49523                 }
49524                 expandingFlags = saveExpandingFlags;
49525                 depth--;
49526                 if (result) {
49527                     if (result === -1 /* True */ || depth === 0) {
49528                         // If result is definitely true, record all maybe keys as having succeeded
49529                         for (var i = maybeStart; i < maybeCount; i++) {
49530                             relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
49531                         }
49532                         maybeCount = maybeStart;
49533                     }
49534                 }
49535                 else {
49536                     // A false result goes straight into global cache (when something is false under
49537                     // assumptions it will also be false without assumptions)
49538                     relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
49539                     maybeCount = maybeStart;
49540                 }
49541                 return result;
49542             }
49543             function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
49544                 if (intersectionState & 4 /* PropertyCheck */) {
49545                     return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
49546                 }
49547                 var flags = source.flags & target.flags;
49548                 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
49549                     if (flags & 4194304 /* Index */) {
49550                         return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
49551                     }
49552                     var result_6 = 0 /* False */;
49553                     if (flags & 8388608 /* IndexedAccess */) {
49554                         if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
49555                             if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
49556                                 return result_6;
49557                             }
49558                         }
49559                     }
49560                     if (flags & 16777216 /* Conditional */) {
49561                         if (source.root.isDistributive === target.root.isDistributive) {
49562                             if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
49563                                 if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
49564                                     if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
49565                                         if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
49566                                             return result_6;
49567                                         }
49568                                     }
49569                                 }
49570                             }
49571                         }
49572                     }
49573                     if (flags & 33554432 /* Substitution */) {
49574                         return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
49575                     }
49576                     return 0 /* False */;
49577                 }
49578                 var result;
49579                 var originalErrorInfo;
49580                 var varianceCheckFailed = false;
49581                 var saveErrorInfo = captureErrorCalculationState();
49582                 // We limit alias variance probing to only object and conditional types since their alias behavior
49583                 // is more predictable than other, interned types, which may or may not have an alias depending on
49584                 // the order in which things were checked.
49585                 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
49586                     source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
49587                     !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
49588                     var variances = getAliasVariances(source.aliasSymbol);
49589                     if (variances === ts.emptyArray) {
49590                         return 1 /* Maybe */;
49591                     }
49592                     var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
49593                     if (varianceResult !== undefined) {
49594                         return varianceResult;
49595                     }
49596                 }
49597                 if (target.flags & 262144 /* TypeParameter */) {
49598                     // 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].
49599                     if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
49600                         if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
49601                             var templateType = getTemplateTypeFromMappedType(source);
49602                             var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
49603                             if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
49604                                 return result;
49605                             }
49606                         }
49607                     }
49608                 }
49609                 else if (target.flags & 4194304 /* Index */) {
49610                     // A keyof S is related to a keyof T if T is related to S.
49611                     if (source.flags & 4194304 /* Index */) {
49612                         if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) {
49613                             return result;
49614                         }
49615                     }
49616                     // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
49617                     // simplified form of T or, if T doesn't simplify, the constraint of T.
49618                     var constraint = getSimplifiedTypeOrConstraint(target.type);
49619                     if (constraint) {
49620                         // We require Ternary.True here such that circular constraints don't cause
49621                         // false positives. For example, given 'T extends { [K in keyof T]: string }',
49622                         // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
49623                         // related to other types.
49624                         if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
49625                             return -1 /* True */;
49626                         }
49627                     }
49628                 }
49629                 else if (target.flags & 8388608 /* IndexedAccess */) {
49630                     // A type S is related to a type T[K] if S is related to C, where C is the base
49631                     // constraint of T[K] for writing.
49632                     if (relation !== identityRelation) {
49633                         var objectType = target.objectType;
49634                         var indexType = target.indexType;
49635                         var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
49636                         var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
49637                         if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
49638                             var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0);
49639                             var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, /*accessNode*/ undefined, accessFlags);
49640                             if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) {
49641                                 return result;
49642                             }
49643                         }
49644                     }
49645                 }
49646                 else if (isGenericMappedType(target)) {
49647                     // A source type T is related to a target type { [P in X]: T[P] }
49648                     var template = getTemplateTypeFromMappedType(target);
49649                     var modifiers = getMappedTypeModifiers(target);
49650                     if (!(modifiers & 8 /* ExcludeOptional */)) {
49651                         if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
49652                             template.indexType === getTypeParameterFromMappedType(target)) {
49653                             return -1 /* True */;
49654                         }
49655                         if (!isGenericMappedType(source)) {
49656                             var targetConstraint = getConstraintTypeFromMappedType(target);
49657                             var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
49658                             var includeOptional = modifiers & 4 /* IncludeOptional */;
49659                             var filteredByApplicability = includeOptional ? intersectTypes(targetConstraint, sourceKeys) : undefined;
49660                             // 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.
49661                             // 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.
49662                             if (includeOptional
49663                                 ? !(filteredByApplicability.flags & 131072 /* Never */)
49664                                 : isRelatedTo(targetConstraint, sourceKeys)) {
49665                                 var typeParameter = getTypeParameterFromMappedType(target);
49666                                 var indexingType = filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
49667                                 var indexedAccessType = getIndexedAccessType(source, indexingType);
49668                                 var templateType = getTemplateTypeFromMappedType(target);
49669                                 if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
49670                                     return result;
49671                                 }
49672                             }
49673                             originalErrorInfo = errorInfo;
49674                             resetErrorInfo(saveErrorInfo);
49675                         }
49676                     }
49677                 }
49678                 if (source.flags & 8650752 /* TypeVariable */) {
49679                     if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
49680                         // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
49681                         if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
49682                             result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
49683                         }
49684                         if (result) {
49685                             resetErrorInfo(saveErrorInfo);
49686                             return result;
49687                         }
49688                     }
49689                     else {
49690                         var constraint = getConstraintOfType(source);
49691                         if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
49692                             // A type variable with no constraint is not related to the non-primitive object type.
49693                             if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
49694                                 resetErrorInfo(saveErrorInfo);
49695                                 return result;
49696                             }
49697                         }
49698                         // 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
49699                         else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49700                             resetErrorInfo(saveErrorInfo);
49701                             return result;
49702                         }
49703                         // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
49704                         else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) {
49705                             resetErrorInfo(saveErrorInfo);
49706                             return result;
49707                         }
49708                     }
49709                 }
49710                 else if (source.flags & 4194304 /* Index */) {
49711                     if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
49712                         resetErrorInfo(saveErrorInfo);
49713                         return result;
49714                     }
49715                 }
49716                 else if (source.flags & 16777216 /* Conditional */) {
49717                     if (target.flags & 16777216 /* Conditional */) {
49718                         // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
49719                         // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
49720                         // and Y1 is related to Y2.
49721                         var sourceParams = source.root.inferTypeParameters;
49722                         var sourceExtends = source.extendsType;
49723                         var mapper = void 0;
49724                         if (sourceParams) {
49725                             // If the source has infer type parameters, we instantiate them in the context of the target
49726                             var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo);
49727                             inferTypes(ctx.inferences, target.extendsType, sourceExtends, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
49728                             sourceExtends = instantiateType(sourceExtends, ctx.mapper);
49729                             mapper = ctx.mapper;
49730                         }
49731                         if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
49732                             (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
49733                             if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) {
49734                                 result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
49735                             }
49736                             if (result) {
49737                                 resetErrorInfo(saveErrorInfo);
49738                                 return result;
49739                             }
49740                         }
49741                     }
49742                     else {
49743                         // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way
49744                         // more assignments than are desirable (since it maps the source check type to its constraint, it loses information)
49745                         var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
49746                         if (distributiveConstraint) {
49747                             if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
49748                                 resetErrorInfo(saveErrorInfo);
49749                                 return result;
49750                             }
49751                         }
49752                     }
49753                     // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O`
49754                     // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!).
49755                     var defaultConstraint = getDefaultConstraintOfConditionalType(source);
49756                     if (defaultConstraint) {
49757                         if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
49758                             resetErrorInfo(saveErrorInfo);
49759                             return result;
49760                         }
49761                     }
49762                 }
49763                 else {
49764                     // An empty object type is related to any mapped type that includes a '?' modifier.
49765                     if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
49766                         return -1 /* True */;
49767                     }
49768                     if (isGenericMappedType(target)) {
49769                         if (isGenericMappedType(source)) {
49770                             if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
49771                                 resetErrorInfo(saveErrorInfo);
49772                                 return result;
49773                             }
49774                         }
49775                         return 0 /* False */;
49776                     }
49777                     var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
49778                     if (relation !== identityRelation) {
49779                         source = getApparentType(source);
49780                     }
49781                     else if (isGenericMappedType(source)) {
49782                         return 0 /* False */;
49783                     }
49784                     if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
49785                         !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
49786                         // We have type references to the same generic type, and the type references are not marker
49787                         // type references (which are intended by be compared structurally). Obtain the variance
49788                         // information for the type parameters and relate the type arguments accordingly.
49789                         var variances = getVariances(source.target);
49790                         // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
49791                         // effectively means we measure variance only from type parameter occurrences that aren't nested in
49792                         // recursive instantiations of the generic type.
49793                         if (variances === ts.emptyArray) {
49794                             return 1 /* Maybe */;
49795                         }
49796                         var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
49797                         if (varianceResult !== undefined) {
49798                             return varianceResult;
49799                         }
49800                     }
49801                     else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
49802                         if (relation !== identityRelation) {
49803                             return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
49804                         }
49805                         else {
49806                             // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
49807                             // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
49808                             return 0 /* False */;
49809                         }
49810                     }
49811                     // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
49812                     // and not `{} <- fresh({}) <- {[idx: string]: any}`
49813                     else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
49814                         return 0 /* False */;
49815                     }
49816                     // Even if relationship doesn't hold for unions, intersections, or generic type references,
49817                     // it may hold in a structural comparison.
49818                     // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
49819                     // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
49820                     // relates to X. Thus, we include intersection types on the source side here.
49821                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
49822                         // Report structural errors only if we haven't reported any errors yet
49823                         var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
49824                         result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
49825                         if (result) {
49826                             result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
49827                             if (result) {
49828                                 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
49829                                 if (result) {
49830                                     result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49831                                     if (result) {
49832                                         result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49833                                     }
49834                                 }
49835                             }
49836                         }
49837                         if (varianceCheckFailed && result) {
49838                             errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
49839                         }
49840                         else if (result) {
49841                             return result;
49842                         }
49843                     }
49844                     // If S is an object type and T is a discriminated union, S may be related to T if
49845                     // there exists a constituent of T for every combination of the discriminants of S
49846                     // with respect to T. We do not report errors here, as we will use the existing
49847                     // error result from checking each constituent of the union.
49848                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
49849                         var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
49850                         if (objectOnlyTarget.flags & 1048576 /* Union */) {
49851                             var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
49852                             if (result_7) {
49853                                 return result_7;
49854                             }
49855                         }
49856                     }
49857                 }
49858                 return 0 /* False */;
49859                 function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
49860                     if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
49861                         return result;
49862                     }
49863                     if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
49864                         // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
49865                         // have to allow a structural fallback check
49866                         // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
49867                         // be assuming identity of the type parameter.
49868                         originalErrorInfo = undefined;
49869                         resetErrorInfo(saveErrorInfo);
49870                         return undefined;
49871                     }
49872                     var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
49873                     varianceCheckFailed = !allowStructuralFallback;
49874                     // The type arguments did not relate appropriately, but it may be because we have no variance
49875                     // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
49876                     // arguments). It might also be the case that the target type has a 'void' type argument for
49877                     // a covariant type parameter that is only used in return positions within the generic type
49878                     // (in which case any type argument is permitted on the source side). In those cases we proceed
49879                     // with a structural comparison. Otherwise, we know for certain the instantiations aren't
49880                     // related and we can return here.
49881                     if (variances !== ts.emptyArray && !allowStructuralFallback) {
49882                         // In some cases generic types that are covariant in regular type checking mode become
49883                         // invariant in --strictFunctionTypes mode because one or more type parameters are used in
49884                         // both co- and contravariant positions. In order to make it easier to diagnose *why* such
49885                         // types are invariant, if any of the type parameters are invariant we reset the reported
49886                         // errors and instead force a structural comparison (which will include elaborations that
49887                         // reveal the reason).
49888                         // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
49889                         // we can return `False` early here to skip calculating the structural error message we don't need.
49890                         if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
49891                             return 0 /* False */;
49892                         }
49893                         // We remember the original error information so we can restore it in case the structural
49894                         // comparison unexpectedly succeeds. This can happen when the structural comparison result
49895                         // is a Ternary.Maybe for example caused by the recursion depth limiter.
49896                         originalErrorInfo = errorInfo;
49897                         resetErrorInfo(saveErrorInfo);
49898                     }
49899                 }
49900             }
49901             function reportUnmeasurableMarkers(p) {
49902                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
49903                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
49904                 }
49905                 return p;
49906             }
49907             function reportUnreliableMarkers(p) {
49908                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
49909                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
49910                 }
49911                 return p;
49912             }
49913             // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
49914             // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
49915             // that S and T are contra-variant whereas X and Y are co-variant.
49916             function mappedTypeRelatedTo(source, target, reportErrors) {
49917                 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
49918                     getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
49919                 if (modifiersRelated) {
49920                     var result_8;
49921                     var targetConstraint = getConstraintTypeFromMappedType(target);
49922                     var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers));
49923                     if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) {
49924                         var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
49925                         return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
49926                     }
49927                 }
49928                 return 0 /* False */;
49929             }
49930             function typeRelatedToDiscriminatedType(source, target) {
49931                 // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
49932                 //    a. If the number of combinations is above a set limit, the comparison is too complex.
49933                 // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
49934                 //    a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
49935                 // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
49936                 //    'target' are related to a property in 'source'.
49937                 //
49938                 // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
49939                 //       for examples.
49940                 var sourceProperties = getPropertiesOfType(source);
49941                 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
49942                 if (!sourcePropertiesFiltered)
49943                     return 0 /* False */;
49944                 // Though we could compute the number of combinations as we generate
49945                 // the matrix, this would incur additional memory overhead due to
49946                 // array allocations. To reduce this overhead, we first compute
49947                 // the number of combinations to ensure we will not surpass our
49948                 // fixed limit before incurring the cost of any allocations:
49949                 var numCombinations = 1;
49950                 for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
49951                     var sourceProperty = sourcePropertiesFiltered_1[_i];
49952                     numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
49953                     if (numCombinations > 25) {
49954                         // We've reached the complexity limit.
49955                         return 0 /* False */;
49956                     }
49957                 }
49958                 // Compute the set of types for each discriminant property.
49959                 var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
49960                 var excludedProperties = ts.createUnderscoreEscapedMap();
49961                 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
49962                     var sourceProperty = sourcePropertiesFiltered[i];
49963                     var sourcePropertyType = getTypeOfSymbol(sourceProperty);
49964                     sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
49965                         ? sourcePropertyType.types
49966                         : [sourcePropertyType];
49967                     excludedProperties.set(sourceProperty.escapedName, true);
49968                 }
49969                 // Match each combination of the cartesian product of discriminant properties to one or more
49970                 // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
49971                 var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
49972                 var matchingTypes = [];
49973                 var _loop_14 = function (combination) {
49974                     var hasMatch = false;
49975                     outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) {
49976                         var type = _a[_i];
49977                         var _loop_15 = function (i) {
49978                             var sourceProperty = sourcePropertiesFiltered[i];
49979                             var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
49980                             if (!targetProperty)
49981                                 return "continue-outer";
49982                             if (sourceProperty === targetProperty)
49983                                 return "continue";
49984                             // We compare the source property to the target in the context of a single discriminant type.
49985                             var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation);
49986                             // If the target property could not be found, or if the properties were not related,
49987                             // then this constituent is not a match.
49988                             if (!related) {
49989                                 return "continue-outer";
49990                             }
49991                         };
49992                         for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
49993                             var state_7 = _loop_15(i);
49994                             switch (state_7) {
49995                                 case "continue-outer": continue outer;
49996                             }
49997                         }
49998                         ts.pushIfUnique(matchingTypes, type, ts.equateValues);
49999                         hasMatch = true;
50000                     }
50001                     if (!hasMatch) {
50002                         return { value: 0 /* False */ };
50003                     }
50004                 };
50005                 for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
50006                     var combination = discriminantCombinations_1[_a];
50007                     var state_6 = _loop_14(combination);
50008                     if (typeof state_6 === "object")
50009                         return state_6.value;
50010                 }
50011                 // Compare the remaining non-discriminant properties of each match.
50012                 var result = -1 /* True */;
50013                 for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
50014                     var type = matchingTypes_1[_b];
50015                     result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
50016                     if (result) {
50017                         result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
50018                         if (result) {
50019                             result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
50020                             if (result) {
50021                                 result &= indexTypesRelatedTo(source, type, 0 /* String */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50022                                 if (result) {
50023                                     result &= indexTypesRelatedTo(source, type, 1 /* Number */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50024                                 }
50025                             }
50026                         }
50027                     }
50028                     if (!result) {
50029                         return result;
50030                     }
50031                 }
50032                 return result;
50033             }
50034             function excludeProperties(properties, excludedProperties) {
50035                 if (!excludedProperties || properties.length === 0)
50036                     return properties;
50037                 var result;
50038                 for (var i = 0; i < properties.length; i++) {
50039                     if (!excludedProperties.has(properties[i].escapedName)) {
50040                         if (result) {
50041                             result.push(properties[i]);
50042                         }
50043                     }
50044                     else if (!result) {
50045                         result = properties.slice(0, i);
50046                     }
50047                 }
50048                 return result || properties;
50049             }
50050             function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
50051                 var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
50052                 var source = getTypeOfSourceProperty(sourceProp);
50053                 if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) {
50054                     // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
50055                     var links = getSymbolLinks(targetProp);
50056                     ts.Debug.assertIsDefined(links.deferralParent);
50057                     ts.Debug.assertIsDefined(links.deferralConstituents);
50058                     var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */);
50059                     var result_9 = unionParent ? 0 /* False */ : -1 /* True */;
50060                     var targetTypes = links.deferralConstituents;
50061                     for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) {
50062                         var targetType = targetTypes_3[_i];
50063                         var related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : 2 /* Target */);
50064                         if (!unionParent) {
50065                             if (!related) {
50066                                 // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
50067                                 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50068                             }
50069                             result_9 &= related;
50070                         }
50071                         else {
50072                             if (related) {
50073                                 return related;
50074                             }
50075                         }
50076                     }
50077                     if (unionParent && !result_9 && targetIsOptional) {
50078                         result_9 = isRelatedTo(source, undefinedType);
50079                     }
50080                     if (unionParent && !result_9 && reportErrors) {
50081                         // The easiest way to get the right errors here is to un-defer (which may be costly)
50082                         // If it turns out this is too costly too often, we can replicate the error handling logic within
50083                         // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
50084                         // type on which to hand discriminable properties, which we are expressly trying to avoid here)
50085                         return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50086                     }
50087                     return result_9;
50088                 }
50089                 else {
50090                     return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
50091                 }
50092             }
50093             function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
50094                 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
50095                 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
50096                 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
50097                     if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
50098                         if (reportErrors) {
50099                             if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
50100                                 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
50101                             }
50102                             else {
50103                                 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));
50104                             }
50105                         }
50106                         return 0 /* False */;
50107                     }
50108                 }
50109                 else if (targetPropFlags & 16 /* Protected */) {
50110                     if (!isValidOverrideOf(sourceProp, targetProp)) {
50111                         if (reportErrors) {
50112                             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));
50113                         }
50114                         return 0 /* False */;
50115                     }
50116                 }
50117                 else if (sourcePropFlags & 16 /* Protected */) {
50118                     if (reportErrors) {
50119                         reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50120                     }
50121                     return 0 /* False */;
50122                 }
50123                 // If the target comes from a partial union prop, allow `undefined` in the target type
50124                 var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
50125                 if (!related) {
50126                     if (reportErrors) {
50127                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
50128                     }
50129                     return 0 /* False */;
50130                 }
50131                 // When checking for comparability, be more lenient with optional properties.
50132                 if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
50133                     // TypeScript 1.0 spec (April 2014): 3.8.3
50134                     // S is a subtype of a type T, and T is a supertype of S if ...
50135                     // S' and T are object types and, for each member M in T..
50136                     // M is a property and S' contains a property N where
50137                     // if M is a required property, N is also a required property
50138                     // (M - property in T)
50139                     // (N - property in S)
50140                     if (reportErrors) {
50141                         reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50142                     }
50143                     return 0 /* False */;
50144                 }
50145                 return related;
50146             }
50147             function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
50148                 var shouldSkipElaboration = false;
50149                 // give specific error in case where private names have the same description
50150                 if (unmatchedProperty.valueDeclaration
50151                     && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
50152                     && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
50153                     && source.symbol
50154                     && source.symbol.flags & 32 /* Class */) {
50155                     var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
50156                     var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
50157                     if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
50158                         var sourceName = ts.getDeclarationName(source.symbol.valueDeclaration);
50159                         var targetName = ts.getDeclarationName(target.symbol.valueDeclaration);
50160                         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));
50161                         return;
50162                     }
50163                 }
50164                 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
50165                 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
50166                     headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
50167                     shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
50168                 }
50169                 if (props.length === 1) {
50170                     var propName = symbolToString(unmatchedProperty);
50171                     reportError.apply(void 0, __spreadArrays([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
50172                     if (ts.length(unmatchedProperty.declarations)) {
50173                         associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
50174                     }
50175                     if (shouldSkipElaboration && errorInfo) {
50176                         overrideNextErrorInfo++;
50177                     }
50178                 }
50179                 else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
50180                     if (props.length > 5) { // arbitrary cutoff for too-long list form
50181                         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);
50182                     }
50183                     else {
50184                         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(", "));
50185                     }
50186                     if (shouldSkipElaboration && errorInfo) {
50187                         overrideNextErrorInfo++;
50188                     }
50189                 }
50190                 // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
50191             }
50192             function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
50193                 if (relation === identityRelation) {
50194                     return propertiesIdenticalTo(source, target, excludedProperties);
50195                 }
50196                 var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
50197                 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
50198                 if (unmatchedProperty) {
50199                     if (reportErrors) {
50200                         reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
50201                     }
50202                     return 0 /* False */;
50203                 }
50204                 if (isObjectLiteralType(target)) {
50205                     for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
50206                         var sourceProp = _a[_i];
50207                         if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
50208                             var sourceType = getTypeOfSymbol(sourceProp);
50209                             if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
50210                                 if (reportErrors) {
50211                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
50212                                 }
50213                                 return 0 /* False */;
50214                             }
50215                         }
50216                     }
50217                 }
50218                 var result = -1 /* True */;
50219                 if (isTupleType(target)) {
50220                     var targetRestType = getRestTypeOfTupleType(target);
50221                     if (targetRestType) {
50222                         if (!isTupleType(source)) {
50223                             return 0 /* False */;
50224                         }
50225                         var sourceRestType = getRestTypeOfTupleType(source);
50226                         if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) {
50227                             if (reportErrors) {
50228                                 reportError(ts.Diagnostics.Rest_signatures_are_incompatible);
50229                             }
50230                             return 0 /* False */;
50231                         }
50232                         var targetCount = getTypeReferenceArity(target) - 1;
50233                         var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0);
50234                         var sourceTypeArguments = getTypeArguments(source);
50235                         for (var i = targetCount; i < sourceCount; i++) {
50236                             var related = isRelatedTo(sourceTypeArguments[i], targetRestType, reportErrors);
50237                             if (!related) {
50238                                 if (reportErrors) {
50239                                     reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i);
50240                                 }
50241                                 return 0 /* False */;
50242                             }
50243                             result &= related;
50244                         }
50245                     }
50246                 }
50247                 // 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_
50248                 // from the target union, across all members
50249                 var properties = getPropertiesOfType(target);
50250                 var numericNamesOnly = isTupleType(source) && isTupleType(target);
50251                 for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
50252                     var targetProp = _c[_b];
50253                     var name = targetProp.escapedName;
50254                     if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
50255                         var sourceProp = getPropertyOfType(source, name);
50256                         if (sourceProp && sourceProp !== targetProp) {
50257                             var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
50258                             if (!related) {
50259                                 return 0 /* False */;
50260                             }
50261                             result &= related;
50262                         }
50263                     }
50264                 }
50265                 return result;
50266             }
50267             function propertiesIdenticalTo(source, target, excludedProperties) {
50268                 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
50269                     return 0 /* False */;
50270                 }
50271                 var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
50272                 var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
50273                 if (sourceProperties.length !== targetProperties.length) {
50274                     return 0 /* False */;
50275                 }
50276                 var result = -1 /* True */;
50277                 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
50278                     var sourceProp = sourceProperties_1[_i];
50279                     var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
50280                     if (!targetProp) {
50281                         return 0 /* False */;
50282                     }
50283                     var related = compareProperties(sourceProp, targetProp, isRelatedTo);
50284                     if (!related) {
50285                         return 0 /* False */;
50286                     }
50287                     result &= related;
50288                 }
50289                 return result;
50290             }
50291             function signaturesRelatedTo(source, target, kind, reportErrors) {
50292                 if (relation === identityRelation) {
50293                     return signaturesIdenticalTo(source, target, kind);
50294                 }
50295                 if (target === anyFunctionType || source === anyFunctionType) {
50296                     return -1 /* True */;
50297                 }
50298                 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
50299                 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
50300                 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
50301                     0 /* Call */ : kind);
50302                 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
50303                     0 /* Call */ : kind);
50304                 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
50305                     if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
50306                         // An abstract constructor type is not assignable to a non-abstract constructor type
50307                         // as it would otherwise be possible to new an abstract class. Note that the assignability
50308                         // check we perform for an extends clause excludes construct signatures from the target,
50309                         // so this check never proceeds.
50310                         if (reportErrors) {
50311                             reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
50312                         }
50313                         return 0 /* False */;
50314                     }
50315                     if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
50316                         return 0 /* False */;
50317                     }
50318                 }
50319                 var result = -1 /* True */;
50320                 var saveErrorInfo = captureErrorCalculationState();
50321                 var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
50322                 if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) {
50323                     // We have instantiations of the same anonymous type (which typically will be the type of a
50324                     // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
50325                     // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
50326                     // as they are known to always be the same.
50327                     for (var i = 0; i < targetSignatures.length; i++) {
50328                         var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
50329                         if (!related) {
50330                             return 0 /* False */;
50331                         }
50332                         result &= related;
50333                     }
50334                 }
50335                 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
50336                     // For simple functions (functions with a single signature) we only erase type parameters for
50337                     // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
50338                     // in the context of the target signature before checking the relationship. Ideally we'd do
50339                     // this regardless of the number of signatures, but the potential costs are prohibitive due
50340                     // to the quadratic nature of the logic below.
50341                     var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
50342                     result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors, incompatibleReporter(sourceSignatures[0], targetSignatures[0]));
50343                 }
50344                 else {
50345                     outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
50346                         var t = targetSignatures_1[_i];
50347                         // Only elaborate errors from the first failure
50348                         var shouldElaborateErrors = reportErrors;
50349                         for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) {
50350                             var s = sourceSignatures_1[_a];
50351                             var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
50352                             if (related) {
50353                                 result &= related;
50354                                 resetErrorInfo(saveErrorInfo);
50355                                 continue outer;
50356                             }
50357                             shouldElaborateErrors = false;
50358                         }
50359                         if (shouldElaborateErrors) {
50360                             reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
50361                         }
50362                         return 0 /* False */;
50363                     }
50364                 }
50365                 return result;
50366             }
50367             function reportIncompatibleCallSignatureReturn(siga, sigb) {
50368                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50369                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50370                 }
50371                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50372             }
50373             function reportIncompatibleConstructSignatureReturn(siga, sigb) {
50374                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50375                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50376                 }
50377                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50378             }
50379             /**
50380              * See signatureAssignableTo, compareSignaturesIdentical
50381              */
50382             function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
50383                 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, makeFunctionTypeMapper(reportUnreliableMarkers));
50384             }
50385             function signaturesIdenticalTo(source, target, kind) {
50386                 var sourceSignatures = getSignaturesOfType(source, kind);
50387                 var targetSignatures = getSignaturesOfType(target, kind);
50388                 if (sourceSignatures.length !== targetSignatures.length) {
50389                     return 0 /* False */;
50390                 }
50391                 var result = -1 /* True */;
50392                 for (var i = 0; i < sourceSignatures.length; i++) {
50393                     var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
50394                     if (!related) {
50395                         return 0 /* False */;
50396                     }
50397                     result &= related;
50398                 }
50399                 return result;
50400             }
50401             function eachPropertyRelatedTo(source, target, kind, reportErrors) {
50402                 var result = -1 /* True */;
50403                 var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
50404                 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
50405                     var prop = props_2[_i];
50406                     // Skip over ignored JSX and symbol-named members
50407                     if (isIgnoredJsxProperty(source, prop)) {
50408                         continue;
50409                     }
50410                     var nameType = getSymbolLinks(prop).nameType;
50411                     if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) {
50412                         continue;
50413                     }
50414                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
50415                         var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
50416                         if (!related) {
50417                             if (reportErrors) {
50418                                 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
50419                             }
50420                             return 0 /* False */;
50421                         }
50422                         result &= related;
50423                     }
50424                 }
50425                 return result;
50426             }
50427             function indexTypeRelatedTo(sourceType, targetType, reportErrors) {
50428                 var related = isRelatedTo(sourceType, targetType, reportErrors);
50429                 if (!related && reportErrors) {
50430                     reportError(ts.Diagnostics.Index_signatures_are_incompatible);
50431                 }
50432                 return related;
50433             }
50434             function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors, intersectionState) {
50435                 if (relation === identityRelation) {
50436                     return indexTypesIdenticalTo(source, target, kind);
50437                 }
50438                 var targetType = getIndexTypeOfType(target, kind);
50439                 if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) {
50440                     // Index signature of type any permits assignment from everything but primitives
50441                     return -1 /* True */;
50442                 }
50443                 if (isGenericMappedType(source)) {
50444                     // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U }
50445                     // if T is related to U.
50446                     return kind === 0 /* String */ ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0 /* False */;
50447                 }
50448                 var indexType = getIndexTypeOfType(source, kind) || kind === 1 /* Number */ && getIndexTypeOfType(source, 0 /* String */);
50449                 if (indexType) {
50450                     return indexTypeRelatedTo(indexType, targetType, reportErrors);
50451                 }
50452                 if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
50453                     // Intersection constituents are never considered to have an inferred index signature
50454                     var related = eachPropertyRelatedTo(source, targetType, kind, reportErrors);
50455                     if (related && kind === 0 /* String */) {
50456                         var numberIndexType = getIndexTypeOfType(source, 1 /* Number */);
50457                         if (numberIndexType) {
50458                             related &= indexTypeRelatedTo(numberIndexType, targetType, reportErrors);
50459                         }
50460                     }
50461                     return related;
50462                 }
50463                 if (reportErrors) {
50464                     reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
50465                 }
50466                 return 0 /* False */;
50467             }
50468             function indexTypesIdenticalTo(source, target, indexKind) {
50469                 var targetInfo = getIndexInfoOfType(target, indexKind);
50470                 var sourceInfo = getIndexInfoOfType(source, indexKind);
50471                 if (!sourceInfo && !targetInfo) {
50472                     return -1 /* True */;
50473                 }
50474                 if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
50475                     return isRelatedTo(sourceInfo.type, targetInfo.type);
50476                 }
50477                 return 0 /* False */;
50478             }
50479             function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
50480                 if (!sourceSignature.declaration || !targetSignature.declaration) {
50481                     return true;
50482                 }
50483                 var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50484                 var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50485                 // A public, protected and private signature is assignable to a private signature.
50486                 if (targetAccessibility === 8 /* Private */) {
50487                     return true;
50488                 }
50489                 // A public and protected signature is assignable to a protected signature.
50490                 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
50491                     return true;
50492                 }
50493                 // Only a public signature is assignable to public signature.
50494                 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
50495                     return true;
50496                 }
50497                 if (reportErrors) {
50498                     reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
50499                 }
50500                 return false;
50501             }
50502         }
50503         function getBestMatchingType(source, target, isRelatedTo) {
50504             if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
50505             return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) ||
50506                 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
50507                 findBestTypeForObjectLiteral(source, target) ||
50508                 findBestTypeForInvokable(source, target) ||
50509                 findMostOverlappyType(source, target);
50510         }
50511         function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) {
50512             // undefined=unknown, true=discriminated, false=not discriminated
50513             // The state of each type progresses from left to right. Discriminated types stop at 'true'.
50514             var discriminable = target.types.map(function (_) { return undefined; });
50515             for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
50516                 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
50517                 var targetProp = getUnionOrIntersectionProperty(target, propertyName);
50518                 if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) {
50519                     continue;
50520                 }
50521                 var i = 0;
50522                 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
50523                     var type = _c[_b];
50524                     var targetType = getTypeOfPropertyOfType(type, propertyName);
50525                     if (targetType && related(getDiscriminatingType(), targetType)) {
50526                         discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
50527                     }
50528                     else {
50529                         discriminable[i] = false;
50530                     }
50531                     i++;
50532                 }
50533             }
50534             var match = discriminable.indexOf(/*searchElement*/ true);
50535             // make sure exactly 1 matches before returning it
50536             return match === -1 || discriminable.indexOf(/*searchElement*/ true, match + 1) !== -1 ? defaultValue : target.types[match];
50537         }
50538         /**
50539          * A type is 'weak' if it is an object type with at least one optional property
50540          * and no required properties, call/construct signatures or index signatures
50541          */
50542         function isWeakType(type) {
50543             if (type.flags & 524288 /* Object */) {
50544                 var resolved = resolveStructuredTypeMembers(type);
50545                 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
50546                     !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
50547                     resolved.properties.length > 0 &&
50548                     ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
50549             }
50550             if (type.flags & 2097152 /* Intersection */) {
50551                 return ts.every(type.types, isWeakType);
50552             }
50553             return false;
50554         }
50555         function hasCommonProperties(source, target, isComparingJsxAttributes) {
50556             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
50557                 var prop = _a[_i];
50558                 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
50559                     return true;
50560                 }
50561             }
50562             return false;
50563         }
50564         // Return a type reference where the source type parameter is replaced with the target marker
50565         // type, and flag the result as a marker type reference.
50566         function getMarkerTypeReference(type, source, target) {
50567             var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
50568             result.objectFlags |= 8192 /* MarkerType */;
50569             return result;
50570         }
50571         function getAliasVariances(symbol) {
50572             var links = getSymbolLinks(symbol);
50573             return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
50574                 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
50575                 type.aliasTypeArgumentsContainsMarker = true;
50576                 return type;
50577             });
50578         }
50579         // Return an array containing the variance of each type parameter. The variance is effectively
50580         // a digest of the type comparisons that occur for each type argument when instantiations of the
50581         // generic type are structurally compared. We infer the variance information by comparing
50582         // instantiations of the generic type for type arguments with known relations. The function
50583         // returns the emptyArray singleton when invoked recursively for the given generic type.
50584         function getVariancesWorker(typeParameters, cache, createMarkerType) {
50585             if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
50586             var variances = cache.variances;
50587             if (!variances) {
50588                 // The emptyArray singleton is used to signal a recursive invocation.
50589                 cache.variances = ts.emptyArray;
50590                 variances = [];
50591                 var _loop_16 = function (tp) {
50592                     var unmeasurable = false;
50593                     var unreliable = false;
50594                     var oldHandler = outofbandVarianceMarkerHandler;
50595                     outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
50596                     // We first compare instantiations where the type parameter is replaced with
50597                     // marker types that have a known subtype relationship. From this we can infer
50598                     // invariance, covariance, contravariance or bivariance.
50599                     var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
50600                     var typeWithSub = createMarkerType(cache, tp, markerSubType);
50601                     var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
50602                         (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
50603                     // If the instantiations appear to be related bivariantly it may be because the
50604                     // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
50605                     // type). To determine this we compare instantiations where the type parameter is
50606                     // replaced with marker types that are known to be unrelated.
50607                     if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
50608                         variance = 4 /* Independent */;
50609                     }
50610                     outofbandVarianceMarkerHandler = oldHandler;
50611                     if (unmeasurable || unreliable) {
50612                         if (unmeasurable) {
50613                             variance |= 8 /* Unmeasurable */;
50614                         }
50615                         if (unreliable) {
50616                             variance |= 16 /* Unreliable */;
50617                         }
50618                     }
50619                     variances.push(variance);
50620                 };
50621                 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
50622                     var tp = typeParameters_1[_i];
50623                     _loop_16(tp);
50624                 }
50625                 cache.variances = variances;
50626             }
50627             return variances;
50628         }
50629         function getVariances(type) {
50630             // Arrays and tuples are known to be covariant, no need to spend time computing this.
50631             if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
50632                 return arrayVariances;
50633             }
50634             return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
50635         }
50636         // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
50637         // See comment at call in recursiveTypeRelatedTo for when this case matters.
50638         function hasCovariantVoidArgument(typeArguments, variances) {
50639             for (var i = 0; i < variances.length; i++) {
50640                 if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
50641                     return true;
50642                 }
50643             }
50644             return false;
50645         }
50646         function isUnconstrainedTypeParameter(type) {
50647             return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
50648         }
50649         function isNonDeferredTypeReference(type) {
50650             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
50651         }
50652         function isTypeReferenceWithGenericArguments(type) {
50653             return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
50654         }
50655         /**
50656          * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
50657          *   where A.id=111 and number.id=12
50658          */
50659         function getTypeReferenceId(type, typeParameters, depth) {
50660             if (depth === void 0) { depth = 0; }
50661             var result = "" + type.target.id;
50662             for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
50663                 var t = _a[_i];
50664                 if (isUnconstrainedTypeParameter(t)) {
50665                     var index = typeParameters.indexOf(t);
50666                     if (index < 0) {
50667                         index = typeParameters.length;
50668                         typeParameters.push(t);
50669                     }
50670                     result += "=" + index;
50671                 }
50672                 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
50673                     result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
50674                 }
50675                 else {
50676                     result += "-" + t.id;
50677                 }
50678             }
50679             return result;
50680         }
50681         /**
50682          * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
50683          * For other cases, the types ids are used.
50684          */
50685         function getRelationKey(source, target, intersectionState, relation) {
50686             if (relation === identityRelation && source.id > target.id) {
50687                 var temp = source;
50688                 source = target;
50689                 target = temp;
50690             }
50691             var postFix = intersectionState ? ":" + intersectionState : "";
50692             if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
50693                 var typeParameters = [];
50694                 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
50695             }
50696             return source.id + "," + target.id + postFix;
50697         }
50698         // Invoke the callback for each underlying property symbol of the given symbol and return the first
50699         // value that isn't undefined.
50700         function forEachProperty(prop, callback) {
50701             if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
50702                 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
50703                     var t = _a[_i];
50704                     var p = getPropertyOfType(t, prop.escapedName);
50705                     var result = p && forEachProperty(p, callback);
50706                     if (result) {
50707                         return result;
50708                     }
50709                 }
50710                 return undefined;
50711             }
50712             return callback(prop);
50713         }
50714         // Return the declaring class type of a property or undefined if property not declared in class
50715         function getDeclaringClass(prop) {
50716             return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
50717         }
50718         // Return true if some underlying source property is declared in a class that derives
50719         // from the given base class.
50720         function isPropertyInClassDerivedFrom(prop, baseClass) {
50721             return forEachProperty(prop, function (sp) {
50722                 var sourceClass = getDeclaringClass(sp);
50723                 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
50724             });
50725         }
50726         // Return true if source property is a valid override of protected parts of target property.
50727         function isValidOverrideOf(sourceProp, targetProp) {
50728             return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
50729                 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
50730         }
50731         // Return true if the given class derives from each of the declaring classes of the protected
50732         // constituents of the given property.
50733         function isClassDerivedFromDeclaringClasses(checkClass, prop) {
50734             return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
50735                 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
50736         }
50737         // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
50738         // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
50739         // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
50740         // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
50741         // levels, but unequal at some level beyond that.
50742         // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
50743         // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
50744         // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
50745         function isDeeplyNestedType(type, stack, depth) {
50746             // We track all object types that have an associated symbol (representing the origin of the type)
50747             if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
50748                 var symbol = type.symbol;
50749                 if (symbol) {
50750                     var count = 0;
50751                     for (var i = 0; i < depth; i++) {
50752                         var t = stack[i];
50753                         if (t.flags & 524288 /* Object */ && t.symbol === symbol) {
50754                             count++;
50755                             if (count >= 5)
50756                                 return true;
50757                         }
50758                     }
50759                 }
50760             }
50761             if (depth >= 5 && type.flags & 8388608 /* IndexedAccess */) {
50762                 var root = getRootObjectTypeFromIndexedAccessChain(type);
50763                 var count = 0;
50764                 for (var i = 0; i < depth; i++) {
50765                     var t = stack[i];
50766                     if (getRootObjectTypeFromIndexedAccessChain(t) === root) {
50767                         count++;
50768                         if (count >= 5)
50769                             return true;
50770                     }
50771                 }
50772             }
50773             return false;
50774         }
50775         /**
50776          * Gets the leftmost object type in a chain of indexed accesses, eg, in A[P][Q], returns A
50777          */
50778         function getRootObjectTypeFromIndexedAccessChain(type) {
50779             var t = type;
50780             while (t.flags & 8388608 /* IndexedAccess */) {
50781                 t = t.objectType;
50782             }
50783             return t;
50784         }
50785         function isPropertyIdenticalTo(sourceProp, targetProp) {
50786             return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
50787         }
50788         function compareProperties(sourceProp, targetProp, compareTypes) {
50789             // Two members are considered identical when
50790             // - they are public properties with identical names, optionality, and types,
50791             // - they are private or protected properties originating in the same declaration and having identical types
50792             if (sourceProp === targetProp) {
50793                 return -1 /* True */;
50794             }
50795             var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
50796             var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
50797             if (sourcePropAccessibility !== targetPropAccessibility) {
50798                 return 0 /* False */;
50799             }
50800             if (sourcePropAccessibility) {
50801                 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
50802                     return 0 /* False */;
50803                 }
50804             }
50805             else {
50806                 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
50807                     return 0 /* False */;
50808                 }
50809             }
50810             if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
50811                 return 0 /* False */;
50812             }
50813             return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
50814         }
50815         function isMatchingSignature(source, target, partialMatch) {
50816             var sourceParameterCount = getParameterCount(source);
50817             var targetParameterCount = getParameterCount(target);
50818             var sourceMinArgumentCount = getMinArgumentCount(source);
50819             var targetMinArgumentCount = getMinArgumentCount(target);
50820             var sourceHasRestParameter = hasEffectiveRestParameter(source);
50821             var targetHasRestParameter = hasEffectiveRestParameter(target);
50822             // A source signature matches a target signature if the two signatures have the same number of required,
50823             // optional, and rest parameters.
50824             if (sourceParameterCount === targetParameterCount &&
50825                 sourceMinArgumentCount === targetMinArgumentCount &&
50826                 sourceHasRestParameter === targetHasRestParameter) {
50827                 return true;
50828             }
50829             // A source signature partially matches a target signature if the target signature has no fewer required
50830             // parameters
50831             if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
50832                 return true;
50833             }
50834             return false;
50835         }
50836         /**
50837          * See signatureRelatedTo, compareSignaturesIdentical
50838          */
50839         function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
50840             // TODO (drosen): De-duplicate code between related functions.
50841             if (source === target) {
50842                 return -1 /* True */;
50843             }
50844             if (!(isMatchingSignature(source, target, partialMatch))) {
50845                 return 0 /* False */;
50846             }
50847             // Check that the two signatures have the same number of type parameters.
50848             if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
50849                 return 0 /* False */;
50850             }
50851             // Check that type parameter constraints and defaults match. If they do, instantiate the source
50852             // signature with the type parameters of the target signature and continue the comparison.
50853             if (target.typeParameters) {
50854                 var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
50855                 for (var i = 0; i < target.typeParameters.length; i++) {
50856                     var s = source.typeParameters[i];
50857                     var t = target.typeParameters[i];
50858                     if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
50859                         compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
50860                         return 0 /* False */;
50861                     }
50862                 }
50863                 source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
50864             }
50865             var result = -1 /* True */;
50866             if (!ignoreThisTypes) {
50867                 var sourceThisType = getThisTypeOfSignature(source);
50868                 if (sourceThisType) {
50869                     var targetThisType = getThisTypeOfSignature(target);
50870                     if (targetThisType) {
50871                         var related = compareTypes(sourceThisType, targetThisType);
50872                         if (!related) {
50873                             return 0 /* False */;
50874                         }
50875                         result &= related;
50876                     }
50877                 }
50878             }
50879             var targetLen = getParameterCount(target);
50880             for (var i = 0; i < targetLen; i++) {
50881                 var s = getTypeAtPosition(source, i);
50882                 var t = getTypeAtPosition(target, i);
50883                 var related = compareTypes(t, s);
50884                 if (!related) {
50885                     return 0 /* False */;
50886                 }
50887                 result &= related;
50888             }
50889             if (!ignoreReturnTypes) {
50890                 var sourceTypePredicate = getTypePredicateOfSignature(source);
50891                 var targetTypePredicate = getTypePredicateOfSignature(target);
50892                 result &= sourceTypePredicate || targetTypePredicate ?
50893                     compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
50894                     compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
50895             }
50896             return result;
50897         }
50898         function compareTypePredicatesIdentical(source, target, compareTypes) {
50899             return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
50900                 source.type === target.type ? -1 /* True */ :
50901                     source.type && target.type ? compareTypes(source.type, target.type) :
50902                         0 /* False */;
50903         }
50904         function literalTypesWithSameBaseType(types) {
50905             var commonBaseType;
50906             for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
50907                 var t = types_12[_i];
50908                 var baseType = getBaseTypeOfLiteralType(t);
50909                 if (!commonBaseType) {
50910                     commonBaseType = baseType;
50911                 }
50912                 if (baseType === t || baseType !== commonBaseType) {
50913                     return false;
50914                 }
50915             }
50916             return true;
50917         }
50918         // When the candidate types are all literal types with the same base type, return a union
50919         // of those literal types. Otherwise, return the leftmost type for which no type to the
50920         // right is a supertype.
50921         function getSupertypeOrUnion(types) {
50922             return literalTypesWithSameBaseType(types) ?
50923                 getUnionType(types) :
50924                 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
50925         }
50926         function getCommonSupertype(types) {
50927             if (!strictNullChecks) {
50928                 return getSupertypeOrUnion(types);
50929             }
50930             var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
50931             return primaryTypes.length ?
50932                 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
50933                 getUnionType(types, 2 /* Subtype */);
50934         }
50935         // Return the leftmost type for which no type to the right is a subtype.
50936         function getCommonSubtype(types) {
50937             return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
50938         }
50939         function isArrayType(type) {
50940             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
50941         }
50942         function isReadonlyArrayType(type) {
50943             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
50944         }
50945         function isMutableArrayOrTuple(type) {
50946             return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
50947         }
50948         function getElementTypeOfArrayType(type) {
50949             return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
50950         }
50951         function isArrayLikeType(type) {
50952             // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
50953             // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
50954             return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
50955         }
50956         function isEmptyArrayLiteralType(type) {
50957             var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined;
50958             return elementType === undefinedWideningType || elementType === implicitNeverType;
50959         }
50960         function isTupleLikeType(type) {
50961             return isTupleType(type) || !!getPropertyOfType(type, "0");
50962         }
50963         function isArrayOrTupleLikeType(type) {
50964             return isArrayLikeType(type) || isTupleLikeType(type);
50965         }
50966         function getTupleElementType(type, index) {
50967             var propType = getTypeOfPropertyOfType(type, "" + index);
50968             if (propType) {
50969                 return propType;
50970             }
50971             if (everyType(type, isTupleType)) {
50972                 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
50973             }
50974             return undefined;
50975         }
50976         function isNeitherUnitTypeNorNever(type) {
50977             return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
50978         }
50979         function isUnitType(type) {
50980             return !!(type.flags & 109440 /* Unit */);
50981         }
50982         function isLiteralType(type) {
50983             return type.flags & 16 /* Boolean */ ? true :
50984                 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
50985                     isUnitType(type);
50986         }
50987         function getBaseTypeOfLiteralType(type) {
50988             return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
50989                 type.flags & 128 /* StringLiteral */ ? stringType :
50990                     type.flags & 256 /* NumberLiteral */ ? numberType :
50991                         type.flags & 2048 /* BigIntLiteral */ ? bigintType :
50992                             type.flags & 512 /* BooleanLiteral */ ? booleanType :
50993                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
50994                                     type;
50995         }
50996         function getWidenedLiteralType(type) {
50997             return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
50998                 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
50999                     type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
51000                         type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
51001                             type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
51002                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
51003                                     type;
51004         }
51005         function getWidenedUniqueESSymbolType(type) {
51006             return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
51007                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
51008                     type;
51009         }
51010         function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
51011             if (!isLiteralOfContextualType(type, contextualType)) {
51012                 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
51013             }
51014             return type;
51015         }
51016         function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
51017             if (type && isUnitType(type)) {
51018                 var contextualType = !contextualSignatureReturnType ? undefined :
51019                     isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
51020                         contextualSignatureReturnType;
51021                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51022             }
51023             return type;
51024         }
51025         function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
51026             if (type && isUnitType(type)) {
51027                 var contextualType = !contextualSignatureReturnType ? undefined :
51028                     getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
51029                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51030             }
51031             return type;
51032         }
51033         /**
51034          * Check if a Type was written as a tuple type literal.
51035          * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required.
51036          */
51037         function isTupleType(type) {
51038             return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
51039         }
51040         function getRestTypeOfTupleType(type) {
51041             return type.target.hasRestElement ? getTypeArguments(type)[type.target.typeParameters.length - 1] : undefined;
51042         }
51043         function getRestArrayTypeOfTupleType(type) {
51044             var restType = getRestTypeOfTupleType(type);
51045             return restType && createArrayType(restType);
51046         }
51047         function getLengthOfTupleType(type) {
51048             return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0);
51049         }
51050         function isZeroBigInt(_a) {
51051             var value = _a.value;
51052             return value.base10Value === "0";
51053         }
51054         function getFalsyFlagsOfTypes(types) {
51055             var result = 0;
51056             for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
51057                 var t = types_13[_i];
51058                 result |= getFalsyFlags(t);
51059             }
51060             return result;
51061         }
51062         // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
51063         // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
51064         // no flags for all other types (including non-falsy literal types).
51065         function getFalsyFlags(type) {
51066             return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
51067                 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
51068                     type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
51069                         type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
51070                             type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
51071                                 type.flags & 117724 /* PossiblyFalsy */;
51072         }
51073         function removeDefinitelyFalsyTypes(type) {
51074             return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
51075                 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
51076                 type;
51077         }
51078         function extractDefinitelyFalsyTypes(type) {
51079             return mapType(type, getDefinitelyFalsyPartOfType);
51080         }
51081         function getDefinitelyFalsyPartOfType(type) {
51082             return type.flags & 4 /* String */ ? emptyStringType :
51083                 type.flags & 8 /* Number */ ? zeroType :
51084                     type.flags & 64 /* BigInt */ ? zeroBigIntType :
51085                         type === regularFalseType ||
51086                             type === falseType ||
51087                             type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) ||
51088                             type.flags & 128 /* StringLiteral */ && type.value === "" ||
51089                             type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
51090                             type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
51091                             neverType;
51092         }
51093         /**
51094          * Add undefined or null or both to a type if they are missing.
51095          * @param type - type to add undefined and/or null to if not present
51096          * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
51097          */
51098         function getNullableType(type, flags) {
51099             var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
51100             return missing === 0 ? type :
51101                 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
51102                     missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
51103                         getUnionType([type, undefinedType, nullType]);
51104         }
51105         function getOptionalType(type) {
51106             ts.Debug.assert(strictNullChecks);
51107             return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
51108         }
51109         function getGlobalNonNullableTypeInstantiation(type) {
51110             if (!deferredGlobalNonNullableTypeAlias) {
51111                 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
51112             }
51113             // Use NonNullable global type alias if available to improve quick info/declaration emit
51114             if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
51115                 return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
51116             }
51117             return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
51118         }
51119         function getNonNullableType(type) {
51120             return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
51121         }
51122         function addOptionalTypeMarker(type) {
51123             return strictNullChecks ? getUnionType([type, optionalType]) : type;
51124         }
51125         function isNotOptionalTypeMarker(type) {
51126             return type !== optionalType;
51127         }
51128         function removeOptionalTypeMarker(type) {
51129             return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type;
51130         }
51131         function propagateOptionalTypeMarker(type, node, wasOptional) {
51132             return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
51133         }
51134         function getOptionalExpressionType(exprType, expression) {
51135             return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
51136                 ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
51137                     exprType;
51138         }
51139         /**
51140          * Is source potentially coercible to target type under `==`.
51141          * Assumes that `source` is a constituent of a union, hence
51142          * the boolean literal flag on the LHS, but not on the RHS.
51143          *
51144          * This does not fully replicate the semantics of `==`. The
51145          * intention is to catch cases that are clearly not right.
51146          *
51147          * Comparing (string | number) to number should not remove the
51148          * string element.
51149          *
51150          * Comparing (string | number) to 1 will remove the string
51151          * element, though this is not sound. This is a pragmatic
51152          * choice.
51153          *
51154          * @see narrowTypeByEquality
51155          *
51156          * @param source
51157          * @param target
51158          */
51159         function isCoercibleUnderDoubleEquals(source, target) {
51160             return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
51161                 && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
51162         }
51163         /**
51164          * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
51165          * with no call or construct signatures.
51166          */
51167         function isObjectTypeWithInferableIndex(type) {
51168             return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
51169                 !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
51170                     !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
51171         }
51172         function createSymbolWithType(source, type) {
51173             var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
51174             symbol.declarations = source.declarations;
51175             symbol.parent = source.parent;
51176             symbol.type = type;
51177             symbol.target = source;
51178             if (source.valueDeclaration) {
51179                 symbol.valueDeclaration = source.valueDeclaration;
51180             }
51181             var nameType = getSymbolLinks(source).nameType;
51182             if (nameType) {
51183                 symbol.nameType = nameType;
51184             }
51185             return symbol;
51186         }
51187         function transformTypeOfMembers(type, f) {
51188             var members = ts.createSymbolTable();
51189             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51190                 var property = _a[_i];
51191                 var original = getTypeOfSymbol(property);
51192                 var updated = f(original);
51193                 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
51194             }
51195             return members;
51196         }
51197         /**
51198          * If the the provided object literal is subject to the excess properties check,
51199          * create a new that is exempt. Recursively mark object literal members as exempt.
51200          * Leave signatures alone since they are not subject to the check.
51201          */
51202         function getRegularTypeOfObjectLiteral(type) {
51203             if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
51204                 return type;
51205             }
51206             var regularType = type.regularType;
51207             if (regularType) {
51208                 return regularType;
51209             }
51210             var resolved = type;
51211             var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
51212             var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
51213             regularNew.flags = resolved.flags;
51214             regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
51215             type.regularType = regularNew;
51216             return regularNew;
51217         }
51218         function createWideningContext(parent, propertyName, siblings) {
51219             return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
51220         }
51221         function getSiblingsOfContext(context) {
51222             if (!context.siblings) {
51223                 var siblings_1 = [];
51224                 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
51225                     var type = _a[_i];
51226                     if (isObjectLiteralType(type)) {
51227                         var prop = getPropertyOfObjectType(type, context.propertyName);
51228                         if (prop) {
51229                             forEachType(getTypeOfSymbol(prop), function (t) {
51230                                 siblings_1.push(t);
51231                             });
51232                         }
51233                     }
51234                 }
51235                 context.siblings = siblings_1;
51236             }
51237             return context.siblings;
51238         }
51239         function getPropertiesOfContext(context) {
51240             if (!context.resolvedProperties) {
51241                 var names = ts.createMap();
51242                 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
51243                     var t = _a[_i];
51244                     if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
51245                         for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
51246                             var prop = _c[_b];
51247                             names.set(prop.escapedName, prop);
51248                         }
51249                     }
51250                 }
51251                 context.resolvedProperties = ts.arrayFrom(names.values());
51252             }
51253             return context.resolvedProperties;
51254         }
51255         function getWidenedProperty(prop, context) {
51256             if (!(prop.flags & 4 /* Property */)) {
51257                 // Since get accessors already widen their return value there is no need to
51258                 // widen accessor based properties here.
51259                 return prop;
51260             }
51261             var original = getTypeOfSymbol(prop);
51262             var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
51263             var widened = getWidenedTypeWithContext(original, propContext);
51264             return widened === original ? prop : createSymbolWithType(prop, widened);
51265         }
51266         function getUndefinedProperty(prop) {
51267             var cached = undefinedProperties.get(prop.escapedName);
51268             if (cached) {
51269                 return cached;
51270             }
51271             var result = createSymbolWithType(prop, undefinedType);
51272             result.flags |= 16777216 /* Optional */;
51273             undefinedProperties.set(prop.escapedName, result);
51274             return result;
51275         }
51276         function getWidenedTypeOfObjectLiteral(type, context) {
51277             var members = ts.createSymbolTable();
51278             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51279                 var prop = _a[_i];
51280                 members.set(prop.escapedName, getWidenedProperty(prop, context));
51281             }
51282             if (context) {
51283                 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
51284                     var prop = _c[_b];
51285                     if (!members.has(prop.escapedName)) {
51286                         members.set(prop.escapedName, getUndefinedProperty(prop));
51287                     }
51288                 }
51289             }
51290             var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
51291             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
51292             var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
51293             result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening
51294             return result;
51295         }
51296         function getWidenedType(type) {
51297             return getWidenedTypeWithContext(type, /*context*/ undefined);
51298         }
51299         function getWidenedTypeWithContext(type, context) {
51300             if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) {
51301                 if (context === undefined && type.widened) {
51302                     return type.widened;
51303                 }
51304                 var result = void 0;
51305                 if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
51306                     result = anyType;
51307                 }
51308                 else if (isObjectLiteralType(type)) {
51309                     result = getWidenedTypeOfObjectLiteral(type, context);
51310                 }
51311                 else if (type.flags & 1048576 /* Union */) {
51312                     var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
51313                     var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
51314                     // Widening an empty object literal transitions from a highly restrictive type to
51315                     // a highly inclusive one. For that reason we perform subtype reduction here if the
51316                     // union includes empty object types (e.g. reducing {} | string to just {}).
51317                     result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
51318                 }
51319                 else if (type.flags & 2097152 /* Intersection */) {
51320                     result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
51321                 }
51322                 else if (isArrayType(type) || isTupleType(type)) {
51323                     result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
51324                 }
51325                 if (result && context === undefined) {
51326                     type.widened = result;
51327                 }
51328                 return result || type;
51329             }
51330             return type;
51331         }
51332         /**
51333          * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
51334          * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
51335          * getWidenedType. But in some cases getWidenedType is called without reporting errors
51336          * (type argument inference is an example).
51337          *
51338          * The return value indicates whether an error was in fact reported. The particular circumstances
51339          * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
51340          * an object literal property (arbitrarily deeply), this function reports an error. If no error is
51341          * reported, reportImplicitAnyError is a suitable fallback to report a general error.
51342          */
51343         function reportWideningErrorsInType(type) {
51344             var errorReported = false;
51345             if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
51346                 if (type.flags & 1048576 /* Union */) {
51347                     if (ts.some(type.types, isEmptyObjectType)) {
51348                         errorReported = true;
51349                     }
51350                     else {
51351                         for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
51352                             var t = _a[_i];
51353                             if (reportWideningErrorsInType(t)) {
51354                                 errorReported = true;
51355                             }
51356                         }
51357                     }
51358                 }
51359                 if (isArrayType(type) || isTupleType(type)) {
51360                     for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
51361                         var t = _c[_b];
51362                         if (reportWideningErrorsInType(t)) {
51363                             errorReported = true;
51364                         }
51365                     }
51366                 }
51367                 if (isObjectLiteralType(type)) {
51368                     for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
51369                         var p = _e[_d];
51370                         var t = getTypeOfSymbol(p);
51371                         if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) {
51372                             if (!reportWideningErrorsInType(t)) {
51373                                 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
51374                             }
51375                             errorReported = true;
51376                         }
51377                     }
51378                 }
51379             }
51380             return errorReported;
51381         }
51382         function reportImplicitAny(declaration, type, wideningKind) {
51383             var typeAsString = typeToString(getWidenedType(type));
51384             if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
51385                 // Only report implicit any errors/suggestions in TS and ts-check JS files
51386                 return;
51387             }
51388             var diagnostic;
51389             switch (declaration.kind) {
51390                 case 209 /* BinaryExpression */:
51391                 case 159 /* PropertyDeclaration */:
51392                 case 158 /* PropertySignature */:
51393                     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;
51394                     break;
51395                 case 156 /* Parameter */:
51396                     var param = declaration;
51397                     if (ts.isIdentifier(param.name) &&
51398                         (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
51399                         param.parent.parameters.indexOf(param) > -1 &&
51400                         (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
51401                             param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
51402                         var newName = "arg" + param.parent.parameters.indexOf(param);
51403                         errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
51404                         return;
51405                     }
51406                     diagnostic = declaration.dotDotDotToken ?
51407                         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 :
51408                         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;
51409                     break;
51410                 case 191 /* BindingElement */:
51411                     diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
51412                     if (!noImplicitAny) {
51413                         // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
51414                         return;
51415                     }
51416                     break;
51417                 case 300 /* JSDocFunctionType */:
51418                     error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51419                     return;
51420                 case 244 /* FunctionDeclaration */:
51421                 case 161 /* MethodDeclaration */:
51422                 case 160 /* MethodSignature */:
51423                 case 163 /* GetAccessor */:
51424                 case 164 /* SetAccessor */:
51425                 case 201 /* FunctionExpression */:
51426                 case 202 /* ArrowFunction */:
51427                     if (noImplicitAny && !declaration.name) {
51428                         if (wideningKind === 3 /* GeneratorYield */) {
51429                             error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
51430                         }
51431                         else {
51432                             error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51433                         }
51434                         return;
51435                     }
51436                     diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
51437                         wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
51438                             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
51439                     break;
51440                 case 186 /* MappedType */:
51441                     if (noImplicitAny) {
51442                         error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
51443                     }
51444                     return;
51445                 default:
51446                     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;
51447             }
51448             errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
51449         }
51450         function reportErrorsFromWidening(declaration, type, wideningKind) {
51451             if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
51452                 // Report implicit any error within type if possible, otherwise report error on declaration
51453                 if (!reportWideningErrorsInType(type)) {
51454                     reportImplicitAny(declaration, type, wideningKind);
51455                 }
51456             }
51457         }
51458         function applyToParameterTypes(source, target, callback) {
51459             var sourceCount = getParameterCount(source);
51460             var targetCount = getParameterCount(target);
51461             var sourceRestType = getEffectiveRestType(source);
51462             var targetRestType = getEffectiveRestType(target);
51463             var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
51464             var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
51465             var sourceThisType = getThisTypeOfSignature(source);
51466             if (sourceThisType) {
51467                 var targetThisType = getThisTypeOfSignature(target);
51468                 if (targetThisType) {
51469                     callback(sourceThisType, targetThisType);
51470                 }
51471             }
51472             for (var i = 0; i < paramCount; i++) {
51473                 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
51474             }
51475             if (targetRestType) {
51476                 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
51477             }
51478         }
51479         function applyToReturnTypes(source, target, callback) {
51480             var sourceTypePredicate = getTypePredicateOfSignature(source);
51481             var targetTypePredicate = getTypePredicateOfSignature(target);
51482             if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
51483                 callback(sourceTypePredicate.type, targetTypePredicate.type);
51484             }
51485             else {
51486                 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
51487             }
51488         }
51489         function createInferenceContext(typeParameters, signature, flags, compareTypes) {
51490             return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
51491         }
51492         function cloneInferenceContext(context, extraFlags) {
51493             if (extraFlags === void 0) { extraFlags = 0; }
51494             return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
51495         }
51496         function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
51497             var context = {
51498                 inferences: inferences,
51499                 signature: signature,
51500                 flags: flags,
51501                 compareTypes: compareTypes,
51502                 mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }),
51503                 nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }),
51504             };
51505             return context;
51506         }
51507         function mapToInferredType(context, t, fix) {
51508             var inferences = context.inferences;
51509             for (var i = 0; i < inferences.length; i++) {
51510                 var inference = inferences[i];
51511                 if (t === inference.typeParameter) {
51512                     if (fix && !inference.isFixed) {
51513                         clearCachedInferences(inferences);
51514                         inference.isFixed = true;
51515                     }
51516                     return getInferredType(context, i);
51517                 }
51518             }
51519             return t;
51520         }
51521         function clearCachedInferences(inferences) {
51522             for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
51523                 var inference = inferences_1[_i];
51524                 if (!inference.isFixed) {
51525                     inference.inferredType = undefined;
51526                 }
51527             }
51528         }
51529         function createInferenceInfo(typeParameter) {
51530             return {
51531                 typeParameter: typeParameter,
51532                 candidates: undefined,
51533                 contraCandidates: undefined,
51534                 inferredType: undefined,
51535                 priority: undefined,
51536                 topLevel: true,
51537                 isFixed: false
51538             };
51539         }
51540         function cloneInferenceInfo(inference) {
51541             return {
51542                 typeParameter: inference.typeParameter,
51543                 candidates: inference.candidates && inference.candidates.slice(),
51544                 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
51545                 inferredType: inference.inferredType,
51546                 priority: inference.priority,
51547                 topLevel: inference.topLevel,
51548                 isFixed: inference.isFixed
51549             };
51550         }
51551         function cloneInferredPartOfContext(context) {
51552             var inferences = ts.filter(context.inferences, hasInferenceCandidates);
51553             return inferences.length ?
51554                 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
51555                 undefined;
51556         }
51557         function getMapperFromContext(context) {
51558             return context && context.mapper;
51559         }
51560         // Return true if the given type could possibly reference a type parameter for which
51561         // we perform type inference (i.e. a type parameter of a generic function). We cache
51562         // results for union and intersection types for performance reasons.
51563         function couldContainTypeVariables(type) {
51564             var objectFlags = ts.getObjectFlags(type);
51565             if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) {
51566                 return !!(objectFlags & 134217728 /* CouldContainTypeVariables */);
51567             }
51568             var result = !!(type.flags & 63176704 /* Instantiable */ ||
51569                 objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
51570                 objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
51571                 objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) ||
51572                 type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables));
51573             if (type.flags & 3899393 /* ObjectFlagsType */) {
51574                 type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0);
51575             }
51576             return result;
51577         }
51578         function isTypeParameterAtTopLevel(type, typeParameter) {
51579             return !!(type === typeParameter ||
51580                 type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
51581                 type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), typeParameter) ||
51582                     isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), typeParameter)));
51583         }
51584         /** Create an object with properties named in the string literal type. Every property has type `any` */
51585         function createEmptyObjectTypeFromStringLiteral(type) {
51586             var members = ts.createSymbolTable();
51587             forEachType(type, function (t) {
51588                 if (!(t.flags & 128 /* StringLiteral */)) {
51589                     return;
51590                 }
51591                 var name = ts.escapeLeadingUnderscores(t.value);
51592                 var literalProp = createSymbol(4 /* Property */, name);
51593                 literalProp.type = anyType;
51594                 if (t.symbol) {
51595                     literalProp.declarations = t.symbol.declarations;
51596                     literalProp.valueDeclaration = t.symbol.valueDeclaration;
51597                 }
51598                 members.set(name, literalProp);
51599             });
51600             var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
51601             return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
51602         }
51603         /**
51604          * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
51605          * an object type with the same set of properties as the source type, where the type of each
51606          * property is computed by inferring from the source property type to X for the type
51607          * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
51608          */
51609         function inferTypeForHomomorphicMappedType(source, target, constraint) {
51610             var key = source.id + "," + target.id + "," + constraint.id;
51611             if (reverseMappedCache.has(key)) {
51612                 return reverseMappedCache.get(key);
51613             }
51614             reverseMappedCache.set(key, undefined);
51615             var type = createReverseMappedType(source, target, constraint);
51616             reverseMappedCache.set(key, type);
51617             return type;
51618         }
51619         // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
51620         // an object literal type with at least one property of an inferable type. For example, an object
51621         // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
51622         // arrow function, but is considered partially inferable because property 'a' has an inferable type.
51623         function isPartiallyInferableType(type) {
51624             return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) ||
51625                 isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); });
51626         }
51627         function createReverseMappedType(source, target, constraint) {
51628             // We consider a source type reverse mappable if it has a string index signature or if
51629             // it has one or more properties and is of a partially inferable type.
51630             if (!(getIndexInfoOfType(source, 0 /* String */) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
51631                 return undefined;
51632             }
51633             // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
51634             // applied to the element type(s).
51635             if (isArrayType(source)) {
51636                 return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
51637             }
51638             if (isTupleType(source)) {
51639                 var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
51640                 var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
51641                     getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength;
51642                 return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, source.target.associatedNames);
51643             }
51644             // For all other object types we infer a new object type where the reverse mapping has been
51645             // applied to the type of each property.
51646             var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
51647             reversed.source = source;
51648             reversed.mappedType = target;
51649             reversed.constraintType = constraint;
51650             return reversed;
51651         }
51652         function getTypeOfReverseMappedSymbol(symbol) {
51653             return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
51654         }
51655         function inferReverseMappedType(sourceType, target, constraint) {
51656             var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
51657             var templateType = getTemplateTypeFromMappedType(target);
51658             var inference = createInferenceInfo(typeParameter);
51659             inferTypes([inference], sourceType, templateType);
51660             return getTypeFromInference(inference) || unknownType;
51661         }
51662         function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51663             var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
51664             return __generator(this, function (_a) {
51665                 switch (_a.label) {
51666                     case 0:
51667                         properties = getPropertiesOfType(target);
51668                         _i = 0, properties_2 = properties;
51669                         _a.label = 1;
51670                     case 1:
51671                         if (!(_i < properties_2.length)) return [3 /*break*/, 6];
51672                         targetProp = properties_2[_i];
51673                         // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
51674                         if (isStaticPrivateIdentifierProperty(targetProp)) {
51675                             return [3 /*break*/, 5];
51676                         }
51677                         if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
51678                         sourceProp = getPropertyOfType(source, targetProp.escapedName);
51679                         if (!!sourceProp) return [3 /*break*/, 3];
51680                         return [4 /*yield*/, targetProp];
51681                     case 2:
51682                         _a.sent();
51683                         return [3 /*break*/, 5];
51684                     case 3:
51685                         if (!matchDiscriminantProperties) return [3 /*break*/, 5];
51686                         targetType = getTypeOfSymbol(targetProp);
51687                         if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
51688                         sourceType = getTypeOfSymbol(sourceProp);
51689                         if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
51690                         return [4 /*yield*/, targetProp];
51691                     case 4:
51692                         _a.sent();
51693                         _a.label = 5;
51694                     case 5:
51695                         _i++;
51696                         return [3 /*break*/, 1];
51697                     case 6: return [2 /*return*/];
51698                 }
51699             });
51700         }
51701         function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51702             var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
51703             if (!result.done)
51704                 return result.value;
51705         }
51706         function tupleTypesDefinitelyUnrelated(source, target) {
51707             return target.target.minLength > source.target.minLength ||
51708                 !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source));
51709         }
51710         function typesDefinitelyUnrelated(source, target) {
51711             // Two tuple types with incompatible arities are definitely unrelated.
51712             // Two object types that each have a property that is unmatched in the other are definitely unrelated.
51713             return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) ||
51714                 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
51715                     !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
51716         }
51717         function getTypeFromInference(inference) {
51718             return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
51719                 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
51720                     undefined;
51721         }
51722         function hasSkipDirectInferenceFlag(node) {
51723             return !!getNodeLinks(node).skipDirectInference;
51724         }
51725         function isFromInferenceBlockedSource(type) {
51726             return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
51727         }
51728         function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
51729             if (priority === void 0) { priority = 0; }
51730             if (contravariant === void 0) { contravariant = false; }
51731             var symbolOrTypeStack;
51732             var visited;
51733             var bivariant = false;
51734             var propagationType;
51735             var inferencePriority = 512 /* MaxValue */;
51736             var allowComplexConstraintInference = true;
51737             inferFromTypes(originalSource, originalTarget);
51738             function inferFromTypes(source, target) {
51739                 if (!couldContainTypeVariables(target)) {
51740                     return;
51741                 }
51742                 if (source === wildcardType) {
51743                     // We are inferring from an 'any' type. We want to infer this type for every type parameter
51744                     // referenced in the target type, so we record it as the propagation type and infer from the
51745                     // target to itself. Then, as we find candidates we substitute the propagation type.
51746                     var savePropagationType = propagationType;
51747                     propagationType = source;
51748                     inferFromTypes(target, target);
51749                     propagationType = savePropagationType;
51750                     return;
51751                 }
51752                 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
51753                     // Source and target are types originating in the same generic type alias declaration.
51754                     // Simply infer from source type arguments to target type arguments.
51755                     inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
51756                     return;
51757                 }
51758                 if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
51759                     // When source and target are the same union or intersection type, just relate each constituent
51760                     // type to itself.
51761                     for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
51762                         var t = _a[_i];
51763                         inferFromTypes(t, t);
51764                     }
51765                     return;
51766                 }
51767                 if (target.flags & 1048576 /* Union */) {
51768                     // First, infer between identically matching source and target constituents and remove the
51769                     // matching types.
51770                     var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
51771                     // Next, infer between closely matching source and target constituents and remove
51772                     // the matching types. Types closely match when they are instantiations of the same
51773                     // object type or instantiations of the same type alias.
51774                     var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
51775                     if (targets.length === 0) {
51776                         return;
51777                     }
51778                     target = getUnionType(targets);
51779                     if (sources.length === 0) {
51780                         // All source constituents have been matched and there is nothing further to infer from.
51781                         // However, simply making no inferences is undesirable because it could ultimately mean
51782                         // inferring a type parameter constraint. Instead, make a lower priority inference from
51783                         // the full source to whatever remains in the target. For example, when inferring from
51784                         // string to 'string | T', make a lower priority inference of string for T.
51785                         inferWithPriority(source, target, 1 /* NakedTypeVariable */);
51786                         return;
51787                     }
51788                     source = getUnionType(sources);
51789                 }
51790                 else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
51791                     // We reduce intersection types only when they contain naked type parameters. For example, when
51792                     // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
51793                     // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
51794                     // string[] on the source side and infer string for T.
51795                     // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
51796                     // in such scenarios.
51797                     if (!(source.flags & 1048576 /* Union */)) {
51798                         // Infer between identically matching source and target constituents and remove the matching types.
51799                         var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
51800                         if (sources.length === 0 || targets.length === 0) {
51801                             return;
51802                         }
51803                         source = getIntersectionType(sources);
51804                         target = getIntersectionType(targets);
51805                     }
51806                 }
51807                 else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
51808                     target = getActualTypeVariable(target);
51809                 }
51810                 if (target.flags & 8650752 /* TypeVariable */) {
51811                     // If target is a type parameter, make an inference, unless the source type contains
51812                     // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
51813                     // Because the anyFunctionType is internal, it should not be exposed to the user by adding
51814                     // it as an inference candidate. Hopefully, a better candidate will come along that does
51815                     // not contain anyFunctionType when we come back to this argument for its second round
51816                     // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
51817                     // when constructing types from type parameters that had no inference candidates).
51818                     if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
51819                         (priority & 32 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
51820                         return;
51821                     }
51822                     var inference = getInferenceInfoForType(target);
51823                     if (inference) {
51824                         if (!inference.isFixed) {
51825                             if (inference.priority === undefined || priority < inference.priority) {
51826                                 inference.candidates = undefined;
51827                                 inference.contraCandidates = undefined;
51828                                 inference.topLevel = true;
51829                                 inference.priority = priority;
51830                             }
51831                             if (priority === inference.priority) {
51832                                 var candidate = propagationType || source;
51833                                 // We make contravariant inferences only if we are in a pure contravariant position,
51834                                 // i.e. only if we have not descended into a bivariant position.
51835                                 if (contravariant && !bivariant) {
51836                                     if (!ts.contains(inference.contraCandidates, candidate)) {
51837                                         inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
51838                                         clearCachedInferences(inferences);
51839                                     }
51840                                 }
51841                                 else if (!ts.contains(inference.candidates, candidate)) {
51842                                     inference.candidates = ts.append(inference.candidates, candidate);
51843                                     clearCachedInferences(inferences);
51844                                 }
51845                             }
51846                             if (!(priority & 32 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
51847                                 inference.topLevel = false;
51848                                 clearCachedInferences(inferences);
51849                             }
51850                         }
51851                         inferencePriority = Math.min(inferencePriority, priority);
51852                         return;
51853                     }
51854                     else {
51855                         // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
51856                         var simplified = getSimplifiedType(target, /*writing*/ false);
51857                         if (simplified !== target) {
51858                             invokeOnce(source, simplified, inferFromTypes);
51859                         }
51860                         else if (target.flags & 8388608 /* IndexedAccess */) {
51861                             var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
51862                             // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
51863                             // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
51864                             if (indexType.flags & 63176704 /* Instantiable */) {
51865                                 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
51866                                 if (simplified_1 && simplified_1 !== target) {
51867                                     invokeOnce(source, simplified_1, inferFromTypes);
51868                                 }
51869                             }
51870                         }
51871                     }
51872                 }
51873                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
51874                     !(source.node && target.node)) {
51875                     // If source and target are references to the same generic type, infer from type arguments
51876                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
51877                 }
51878                 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
51879                     contravariant = !contravariant;
51880                     inferFromTypes(source.type, target.type);
51881                     contravariant = !contravariant;
51882                 }
51883                 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
51884                     var empty = createEmptyObjectTypeFromStringLiteral(source);
51885                     contravariant = !contravariant;
51886                     inferWithPriority(empty, target.type, 64 /* LiteralKeyof */);
51887                     contravariant = !contravariant;
51888                 }
51889                 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
51890                     inferFromTypes(source.objectType, target.objectType);
51891                     inferFromTypes(source.indexType, target.indexType);
51892                 }
51893                 else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
51894                     inferFromTypes(source.checkType, target.checkType);
51895                     inferFromTypes(source.extendsType, target.extendsType);
51896                     inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
51897                     inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
51898                 }
51899                 else if (target.flags & 16777216 /* Conditional */) {
51900                     var savePriority = priority;
51901                     priority |= contravariant ? 16 /* ContravariantConditional */ : 0;
51902                     var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
51903                     inferToMultipleTypes(source, targetTypes, target.flags);
51904                     priority = savePriority;
51905                 }
51906                 else if (target.flags & 3145728 /* UnionOrIntersection */) {
51907                     inferToMultipleTypes(source, target.types, target.flags);
51908                 }
51909                 else if (source.flags & 1048576 /* Union */) {
51910                     // Source is a union or intersection type, infer from each constituent type
51911                     var sourceTypes = source.types;
51912                     for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) {
51913                         var sourceType = sourceTypes_2[_e];
51914                         inferFromTypes(sourceType, target);
51915                     }
51916                 }
51917                 else {
51918                     source = getReducedType(source);
51919                     if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) {
51920                         var apparentSource = getApparentType(source);
51921                         // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
51922                         // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
51923                         // with the simplified source.
51924                         if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
51925                             // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
51926                             // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
51927                             // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
51928                             // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
51929                             // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
51930                             // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
51931                             // remove this `allowComplexConstraintInference` flag.
51932                             allowComplexConstraintInference = false;
51933                             return inferFromTypes(apparentSource, target);
51934                         }
51935                         source = apparentSource;
51936                     }
51937                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
51938                         invokeOnce(source, target, inferFromObjectTypes);
51939                     }
51940                 }
51941                 if (source.flags & 25165824 /* Simplifiable */) {
51942                     var simplified = getSimplifiedType(source, contravariant);
51943                     if (simplified !== source) {
51944                         inferFromTypes(simplified, target);
51945                     }
51946                 }
51947             }
51948             function inferWithPriority(source, target, newPriority) {
51949                 var savePriority = priority;
51950                 priority |= newPriority;
51951                 inferFromTypes(source, target);
51952                 priority = savePriority;
51953             }
51954             function invokeOnce(source, target, action) {
51955                 var key = source.id + "," + target.id;
51956                 var status = visited && visited.get(key);
51957                 if (status !== undefined) {
51958                     inferencePriority = Math.min(inferencePriority, status);
51959                     return;
51960                 }
51961                 (visited || (visited = ts.createMap())).set(key, -1 /* Circularity */);
51962                 var saveInferencePriority = inferencePriority;
51963                 inferencePriority = 512 /* MaxValue */;
51964                 action(source, target);
51965                 visited.set(key, inferencePriority);
51966                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
51967             }
51968             function inferFromMatchingTypes(sources, targets, matches) {
51969                 var matchedSources;
51970                 var matchedTargets;
51971                 for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
51972                     var t = targets_1[_i];
51973                     for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
51974                         var s = sources_1[_a];
51975                         if (matches(s, t)) {
51976                             inferFromTypes(s, t);
51977                             matchedSources = ts.appendIfUnique(matchedSources, s);
51978                             matchedTargets = ts.appendIfUnique(matchedTargets, t);
51979                         }
51980                     }
51981                 }
51982                 return [
51983                     matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
51984                     matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
51985                 ];
51986             }
51987             function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
51988                 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
51989                 for (var i = 0; i < count; i++) {
51990                     if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
51991                         inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
51992                     }
51993                     else {
51994                         inferFromTypes(sourceTypes[i], targetTypes[i]);
51995                     }
51996                 }
51997             }
51998             function inferFromContravariantTypes(source, target) {
51999                 if (strictFunctionTypes || priority & 256 /* AlwaysStrict */) {
52000                     contravariant = !contravariant;
52001                     inferFromTypes(source, target);
52002                     contravariant = !contravariant;
52003                 }
52004                 else {
52005                     inferFromTypes(source, target);
52006                 }
52007             }
52008             function getInferenceInfoForType(type) {
52009                 if (type.flags & 8650752 /* TypeVariable */) {
52010                     for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
52011                         var inference = inferences_2[_i];
52012                         if (type === inference.typeParameter) {
52013                             return inference;
52014                         }
52015                     }
52016                 }
52017                 return undefined;
52018             }
52019             function getSingleTypeVariableFromIntersectionTypes(types) {
52020                 var typeVariable;
52021                 for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
52022                     var type = types_14[_i];
52023                     var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
52024                     if (!t || typeVariable && t !== typeVariable) {
52025                         return undefined;
52026                     }
52027                     typeVariable = t;
52028                 }
52029                 return typeVariable;
52030             }
52031             function inferToMultipleTypes(source, targets, targetFlags) {
52032                 var typeVariableCount = 0;
52033                 if (targetFlags & 1048576 /* Union */) {
52034                     var nakedTypeVariable = void 0;
52035                     var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
52036                     var matched_1 = new Array(sources.length);
52037                     var inferenceCircularity = false;
52038                     // First infer to types that are not naked type variables. For each source type we
52039                     // track whether inferences were made from that particular type to some target with
52040                     // equal priority (i.e. of equal quality) to what we would infer for a naked type
52041                     // parameter.
52042                     for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
52043                         var t = targets_2[_i];
52044                         if (getInferenceInfoForType(t)) {
52045                             nakedTypeVariable = t;
52046                             typeVariableCount++;
52047                         }
52048                         else {
52049                             for (var i = 0; i < sources.length; i++) {
52050                                 var saveInferencePriority = inferencePriority;
52051                                 inferencePriority = 512 /* MaxValue */;
52052                                 inferFromTypes(sources[i], t);
52053                                 if (inferencePriority === priority)
52054                                     matched_1[i] = true;
52055                                 inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
52056                                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
52057                             }
52058                         }
52059                     }
52060                     if (typeVariableCount === 0) {
52061                         // If every target is an intersection of types containing a single naked type variable,
52062                         // make a lower priority inference to that type variable. This handles inferring from
52063                         // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
52064                         var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
52065                         if (intersectionTypeVariable) {
52066                             inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
52067                         }
52068                         return;
52069                     }
52070                     // If the target has a single naked type variable and no inference circularities were
52071                     // encountered above (meaning we explored the types fully), create a union of the source
52072                     // types from which no inferences have been made so far and infer from that union to the
52073                     // naked type variable.
52074                     if (typeVariableCount === 1 && !inferenceCircularity) {
52075                         var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
52076                         if (unmatched.length) {
52077                             inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
52078                             return;
52079                         }
52080                     }
52081                 }
52082                 else {
52083                     // We infer from types that are not naked type variables first so that inferences we
52084                     // make from nested naked type variables and given slightly higher priority by virtue
52085                     // of being first in the candidates array.
52086                     for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
52087                         var t = targets_3[_a];
52088                         if (getInferenceInfoForType(t)) {
52089                             typeVariableCount++;
52090                         }
52091                         else {
52092                             inferFromTypes(source, t);
52093                         }
52094                     }
52095                 }
52096                 // Inferences directly to naked type variables are given lower priority as they are
52097                 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
52098                 // we want to infer string for T, not Promise<string> | string. For intersection types
52099                 // we only infer to single naked type variables.
52100                 if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
52101                     for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
52102                         var t = targets_4[_b];
52103                         if (getInferenceInfoForType(t)) {
52104                             inferWithPriority(source, t, 1 /* NakedTypeVariable */);
52105                         }
52106                     }
52107                 }
52108             }
52109             function inferToMappedType(source, target, constraintType) {
52110                 if (constraintType.flags & 1048576 /* Union */) {
52111                     var result = false;
52112                     for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
52113                         var type = _a[_i];
52114                         result = inferToMappedType(source, target, type) || result;
52115                     }
52116                     return result;
52117                 }
52118                 if (constraintType.flags & 4194304 /* Index */) {
52119                     // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
52120                     // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
52121                     // type and then make a secondary inference from that type to T. We make a secondary inference
52122                     // such that direct inferences to T get priority over inferences to Partial<T>, for example.
52123                     var inference = getInferenceInfoForType(constraintType.type);
52124                     if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
52125                         var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
52126                         if (inferredType) {
52127                             // We assign a lower priority to inferences made from types containing non-inferrable
52128                             // types because we may only have a partial result (i.e. we may have failed to make
52129                             // reverse inferences for some properties).
52130                             inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ?
52131                                 4 /* PartialHomomorphicMappedType */ :
52132                                 2 /* HomomorphicMappedType */);
52133                         }
52134                     }
52135                     return true;
52136                 }
52137                 if (constraintType.flags & 262144 /* TypeParameter */) {
52138                     // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
52139                     // parameter. First infer from 'keyof S' to K.
52140                     inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */);
52141                     // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
52142                     // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
52143                     // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
52144                     // Pick<T, K>.
52145                     var extendedConstraint = getConstraintOfType(constraintType);
52146                     if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
52147                         return true;
52148                     }
52149                     // If no inferences can be made to K's constraint, infer from a union of the property types
52150                     // in the source to the template type X.
52151                     var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
52152                     var stringIndexType = getIndexTypeOfType(source, 0 /* String */);
52153                     var numberIndexInfo = getNonEnumNumberIndexInfo(source);
52154                     var numberIndexType = numberIndexInfo && numberIndexInfo.type;
52155                     inferFromTypes(getUnionType(ts.append(ts.append(propTypes, stringIndexType), numberIndexType)), getTemplateTypeFromMappedType(target));
52156                     return true;
52157                 }
52158                 return false;
52159             }
52160             function inferFromObjectTypes(source, target) {
52161                 // If we are already processing another target type with the same associated symbol (such as
52162                 // an instantiation of the same generic type), we do not explore this target as it would yield
52163                 // no further inferences. We exclude the static side of classes from this check since it shares
52164                 // its symbol with the instance side which would lead to false positives.
52165                 var isNonConstructorObject = target.flags & 524288 /* Object */ &&
52166                     !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */);
52167                 var symbolOrType = isNonConstructorObject ? isTupleType(target) ? target.target : target.symbol : undefined;
52168                 if (symbolOrType) {
52169                     if (ts.contains(symbolOrTypeStack, symbolOrType)) {
52170                         inferencePriority = -1 /* Circularity */;
52171                         return;
52172                     }
52173                     (symbolOrTypeStack || (symbolOrTypeStack = [])).push(symbolOrType);
52174                     inferFromObjectTypesWorker(source, target);
52175                     symbolOrTypeStack.pop();
52176                 }
52177                 else {
52178                     inferFromObjectTypesWorker(source, target);
52179                 }
52180             }
52181             function inferFromObjectTypesWorker(source, target) {
52182                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
52183                     // If source and target are references to the same generic type, infer from type arguments
52184                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
52185                     return;
52186                 }
52187                 if (isGenericMappedType(source) && isGenericMappedType(target)) {
52188                     // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
52189                     // from S to T and from X to Y.
52190                     inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
52191                     inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
52192                 }
52193                 if (ts.getObjectFlags(target) & 32 /* Mapped */) {
52194                     var constraintType = getConstraintTypeFromMappedType(target);
52195                     if (inferToMappedType(source, target, constraintType)) {
52196                         return;
52197                     }
52198                 }
52199                 // Infer from the members of source and target only if the two types are possibly related
52200                 if (!typesDefinitelyUnrelated(source, target)) {
52201                     if (isArrayType(source) || isTupleType(source)) {
52202                         if (isTupleType(target)) {
52203                             var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
52204                             var targetLength = getLengthOfTupleType(target);
52205                             var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
52206                             var targetRestType = getRestTypeOfTupleType(target);
52207                             var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
52208                             for (var i = 0; i < fixedLength; i++) {
52209                                 inferFromTypes(i < sourceLength ? getTypeArguments(source)[i] : sourceRestType, getTypeArguments(target)[i]);
52210                             }
52211                             if (targetRestType) {
52212                                 var types = fixedLength < sourceLength ? getTypeArguments(source).slice(fixedLength, sourceLength) : [];
52213                                 if (sourceRestType) {
52214                                     types.push(sourceRestType);
52215                                 }
52216                                 if (types.length) {
52217                                     inferFromTypes(getUnionType(types), targetRestType);
52218                                 }
52219                             }
52220                             return;
52221                         }
52222                         if (isArrayType(target)) {
52223                             inferFromIndexTypes(source, target);
52224                             return;
52225                         }
52226                     }
52227                     inferFromProperties(source, target);
52228                     inferFromSignatures(source, target, 0 /* Call */);
52229                     inferFromSignatures(source, target, 1 /* Construct */);
52230                     inferFromIndexTypes(source, target);
52231                 }
52232             }
52233             function inferFromProperties(source, target) {
52234                 var properties = getPropertiesOfObjectType(target);
52235                 for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
52236                     var targetProp = properties_3[_i];
52237                     var sourceProp = getPropertyOfType(source, targetProp.escapedName);
52238                     if (sourceProp) {
52239                         inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
52240                     }
52241                 }
52242             }
52243             function inferFromSignatures(source, target, kind) {
52244                 var sourceSignatures = getSignaturesOfType(source, kind);
52245                 var targetSignatures = getSignaturesOfType(target, kind);
52246                 var sourceLen = sourceSignatures.length;
52247                 var targetLen = targetSignatures.length;
52248                 var len = sourceLen < targetLen ? sourceLen : targetLen;
52249                 var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */);
52250                 for (var i = 0; i < len; i++) {
52251                     inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters);
52252                 }
52253             }
52254             function inferFromSignature(source, target, skipParameters) {
52255                 if (!skipParameters) {
52256                     var saveBivariant = bivariant;
52257                     var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
52258                     // Once we descend into a bivariant signature we remain bivariant for all nested inferences
52259                     bivariant = bivariant || kind === 161 /* MethodDeclaration */ || kind === 160 /* MethodSignature */ || kind === 162 /* Constructor */;
52260                     applyToParameterTypes(source, target, inferFromContravariantTypes);
52261                     bivariant = saveBivariant;
52262                 }
52263                 applyToReturnTypes(source, target, inferFromTypes);
52264             }
52265             function inferFromIndexTypes(source, target) {
52266                 var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
52267                 if (targetStringIndexType) {
52268                     var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
52269                         getImplicitIndexTypeOfType(source, 0 /* String */);
52270                     if (sourceIndexType) {
52271                         inferFromTypes(sourceIndexType, targetStringIndexType);
52272                     }
52273                 }
52274                 var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
52275                 if (targetNumberIndexType) {
52276                     var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
52277                         getIndexTypeOfType(source, 0 /* String */) ||
52278                         getImplicitIndexTypeOfType(source, 1 /* Number */);
52279                     if (sourceIndexType) {
52280                         inferFromTypes(sourceIndexType, targetNumberIndexType);
52281                     }
52282                 }
52283             }
52284         }
52285         function isTypeOrBaseIdenticalTo(s, t) {
52286             return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
52287         }
52288         function isTypeCloselyMatchedBy(s, t) {
52289             return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
52290                 s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
52291         }
52292         function hasPrimitiveConstraint(type) {
52293             var constraint = getConstraintOfTypeParameter(type);
52294             return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */);
52295         }
52296         function isObjectLiteralType(type) {
52297             return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
52298         }
52299         function isObjectOrArrayLiteralType(type) {
52300             return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */));
52301         }
52302         function unionObjectAndArrayLiteralCandidates(candidates) {
52303             if (candidates.length > 1) {
52304                 var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
52305                 if (objectLiterals.length) {
52306                     var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
52307                     return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
52308                 }
52309             }
52310             return candidates;
52311         }
52312         function getContravariantInference(inference) {
52313             return inference.priority & 104 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
52314         }
52315         function getCovariantInference(inference, signature) {
52316             // Extract all object and array literal types and replace them with a single widened and normalized type.
52317             var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
52318             // We widen inferred literal types if
52319             // all inferences were made to top-level occurrences of the type parameter, and
52320             // the type parameter has no constraint or its constraint includes no primitive or literal types, and
52321             // the type parameter was fixed during inference or does not occur at top-level in the return type.
52322             var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
52323             var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
52324                 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
52325             var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
52326                 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
52327                     candidates;
52328             // If all inferences were made from a position that implies a combined result, infer a union type.
52329             // Otherwise, infer a common supertype.
52330             var unwidenedType = inference.priority & 104 /* PriorityImpliesCombination */ ?
52331                 getUnionType(baseCandidates, 2 /* Subtype */) :
52332                 getCommonSupertype(baseCandidates);
52333             return getWidenedType(unwidenedType);
52334         }
52335         function getInferredType(context, index) {
52336             var inference = context.inferences[index];
52337             if (!inference.inferredType) {
52338                 var inferredType = void 0;
52339                 var signature = context.signature;
52340                 if (signature) {
52341                     var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
52342                     if (inference.contraCandidates) {
52343                         var inferredContravariantType = getContravariantInference(inference);
52344                         // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
52345                         // unless the co-variant inference is a subtype and not 'never'.
52346                         inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
52347                             isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
52348                             inferredCovariantType : inferredContravariantType;
52349                     }
52350                     else if (inferredCovariantType) {
52351                         inferredType = inferredCovariantType;
52352                     }
52353                     else if (context.flags & 1 /* NoDefault */) {
52354                         // We use silentNeverType as the wildcard that signals no inferences.
52355                         inferredType = silentNeverType;
52356                     }
52357                     else {
52358                         // Infer either the default or the empty object type when no inferences were
52359                         // made. It is important to remember that in this case, inference still
52360                         // succeeds, meaning there is no error for not having inference candidates. An
52361                         // inference error only occurs when there are *conflicting* candidates, i.e.
52362                         // candidates with no common supertype.
52363                         var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
52364                         if (defaultType) {
52365                             // Instantiate the default type. Any forward reference to a type
52366                             // parameter should be instantiated to the empty object type.
52367                             inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
52368                         }
52369                     }
52370                 }
52371                 else {
52372                     inferredType = getTypeFromInference(inference);
52373                 }
52374                 inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
52375                 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
52376                 if (constraint) {
52377                     var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
52378                     if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
52379                         inference.inferredType = inferredType = instantiatedConstraint;
52380                     }
52381                 }
52382             }
52383             return inference.inferredType;
52384         }
52385         function getDefaultTypeArgumentType(isInJavaScriptFile) {
52386             return isInJavaScriptFile ? anyType : unknownType;
52387         }
52388         function getInferredTypes(context) {
52389             var result = [];
52390             for (var i = 0; i < context.inferences.length; i++) {
52391                 result.push(getInferredType(context, i));
52392             }
52393             return result;
52394         }
52395         // EXPRESSION TYPE CHECKING
52396         function getCannotFindNameDiagnosticForName(node) {
52397             switch (node.escapedText) {
52398                 case "document":
52399                 case "console":
52400                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
52401                 case "$":
52402                     return compilerOptions.types
52403                         ? 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
52404                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
52405                 case "describe":
52406                 case "suite":
52407                 case "it":
52408                 case "test":
52409                     return compilerOptions.types
52410                         ? 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
52411                         : 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;
52412                 case "process":
52413                 case "require":
52414                 case "Buffer":
52415                 case "module":
52416                     return compilerOptions.types
52417                         ? 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
52418                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
52419                 case "Map":
52420                 case "Set":
52421                 case "Promise":
52422                 case "Symbol":
52423                 case "WeakMap":
52424                 case "WeakSet":
52425                 case "Iterator":
52426                 case "AsyncIterator":
52427                     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;
52428                 default:
52429                     if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
52430                         return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
52431                     }
52432                     else {
52433                         return ts.Diagnostics.Cannot_find_name_0;
52434                     }
52435             }
52436         }
52437         function getResolvedSymbol(node) {
52438             var links = getNodeLinks(node);
52439             if (!links.resolvedSymbol) {
52440                 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
52441                     resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), 
52442                     /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
52443             }
52444             return links.resolvedSymbol;
52445         }
52446         function isInTypeQuery(node) {
52447             // TypeScript 1.0 spec (April 2014): 3.6.3
52448             // A type query consists of the keyword typeof followed by an expression.
52449             // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
52450             return !!ts.findAncestor(node, function (n) { return n.kind === 172 /* TypeQuery */ ? true : n.kind === 75 /* Identifier */ || n.kind === 153 /* QualifiedName */ ? false : "quit"; });
52451         }
52452         // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
52453         // separated by dots). The key consists of the id of the symbol referenced by the
52454         // leftmost identifier followed by zero or more property names separated by dots.
52455         // The result is undefined if the reference isn't a dotted name. We prefix nodes
52456         // occurring in an apparent type position with '@' because the control flow type
52457         // of such nodes may be based on the apparent type instead of the declared type.
52458         function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
52459             switch (node.kind) {
52460                 case 75 /* Identifier */:
52461                     var symbol = getResolvedSymbol(node);
52462                     return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
52463                 case 104 /* ThisKeyword */:
52464                     return "0";
52465                 case 218 /* NonNullExpression */:
52466                 case 200 /* ParenthesizedExpression */:
52467                     return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52468                 case 194 /* PropertyAccessExpression */:
52469                 case 195 /* ElementAccessExpression */:
52470                     var propName = getAccessedPropertyName(node);
52471                     if (propName !== undefined) {
52472                         var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52473                         return key && key + "." + propName;
52474                     }
52475             }
52476             return undefined;
52477         }
52478         function isMatchingReference(source, target) {
52479             switch (target.kind) {
52480                 case 200 /* ParenthesizedExpression */:
52481                 case 218 /* NonNullExpression */:
52482                     return isMatchingReference(source, target.expression);
52483             }
52484             switch (source.kind) {
52485                 case 75 /* Identifier */:
52486                     return target.kind === 75 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
52487                         (target.kind === 242 /* VariableDeclaration */ || target.kind === 191 /* BindingElement */) &&
52488                             getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
52489                 case 104 /* ThisKeyword */:
52490                     return target.kind === 104 /* ThisKeyword */;
52491                 case 102 /* SuperKeyword */:
52492                     return target.kind === 102 /* SuperKeyword */;
52493                 case 218 /* NonNullExpression */:
52494                 case 200 /* ParenthesizedExpression */:
52495                     return isMatchingReference(source.expression, target);
52496                 case 194 /* PropertyAccessExpression */:
52497                 case 195 /* ElementAccessExpression */:
52498                     return ts.isAccessExpression(target) &&
52499                         getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
52500                         isMatchingReference(source.expression, target.expression);
52501             }
52502             return false;
52503         }
52504         // Given a source x, check if target matches x or is an && operation with an operand that matches x.
52505         function containsTruthyCheck(source, target) {
52506             return isMatchingReference(source, target) ||
52507                 (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ &&
52508                     (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right)));
52509         }
52510         function getAccessedPropertyName(access) {
52511             return access.kind === 194 /* PropertyAccessExpression */ ? access.name.escapedText :
52512                 ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
52513                     undefined;
52514         }
52515         function containsMatchingReference(source, target) {
52516             while (ts.isAccessExpression(source)) {
52517                 source = source.expression;
52518                 if (isMatchingReference(source, target)) {
52519                     return true;
52520                 }
52521             }
52522             return false;
52523         }
52524         function optionalChainContainsReference(source, target) {
52525             while (ts.isOptionalChain(source)) {
52526                 source = source.expression;
52527                 if (isMatchingReference(source, target)) {
52528                     return true;
52529                 }
52530             }
52531             return false;
52532         }
52533         function isDiscriminantProperty(type, name) {
52534             if (type && type.flags & 1048576 /* Union */) {
52535                 var prop = getUnionOrIntersectionProperty(type, name);
52536                 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
52537                     if (prop.isDiscriminantProperty === undefined) {
52538                         prop.isDiscriminantProperty =
52539                             (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
52540                                 !maybeTypeOfKind(getTypeOfSymbol(prop), 63176704 /* Instantiable */);
52541                     }
52542                     return !!prop.isDiscriminantProperty;
52543                 }
52544             }
52545             return false;
52546         }
52547         function findDiscriminantProperties(sourceProperties, target) {
52548             var result;
52549             for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
52550                 var sourceProperty = sourceProperties_2[_i];
52551                 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
52552                     if (result) {
52553                         result.push(sourceProperty);
52554                         continue;
52555                     }
52556                     result = [sourceProperty];
52557                 }
52558             }
52559             return result;
52560         }
52561         function isOrContainsMatchingReference(source, target) {
52562             return isMatchingReference(source, target) || containsMatchingReference(source, target);
52563         }
52564         function hasMatchingArgument(callExpression, reference) {
52565             if (callExpression.arguments) {
52566                 for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
52567                     var argument = _a[_i];
52568                     if (isOrContainsMatchingReference(reference, argument)) {
52569                         return true;
52570                     }
52571                 }
52572             }
52573             if (callExpression.expression.kind === 194 /* PropertyAccessExpression */ &&
52574                 isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
52575                 return true;
52576             }
52577             return false;
52578         }
52579         function getFlowNodeId(flow) {
52580             if (!flow.id || flow.id < 0) {
52581                 flow.id = nextFlowId;
52582                 nextFlowId++;
52583             }
52584             return flow.id;
52585         }
52586         function typeMaybeAssignableTo(source, target) {
52587             if (!(source.flags & 1048576 /* Union */)) {
52588                 return isTypeAssignableTo(source, target);
52589             }
52590             for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
52591                 var t = _a[_i];
52592                 if (isTypeAssignableTo(t, target)) {
52593                     return true;
52594                 }
52595             }
52596             return false;
52597         }
52598         // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
52599         // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
52600         // we remove type string.
52601         function getAssignmentReducedType(declaredType, assignedType) {
52602             if (declaredType !== assignedType) {
52603                 if (assignedType.flags & 131072 /* Never */) {
52604                     return assignedType;
52605                 }
52606                 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
52607                 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
52608                     reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
52609                 }
52610                 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
52611                 // For now, when that happens, we give up and don't narrow at all.  (This also
52612                 // means we'll never narrow for erroneous assignments where the assigned type
52613                 // is not assignable to the declared type.)
52614                 if (isTypeAssignableTo(assignedType, reducedType)) {
52615                     return reducedType;
52616                 }
52617             }
52618             return declaredType;
52619         }
52620         function getTypeFactsOfTypes(types) {
52621             var result = 0 /* None */;
52622             for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
52623                 var t = types_15[_i];
52624                 result |= getTypeFacts(t);
52625             }
52626             return result;
52627         }
52628         function isFunctionObjectType(type) {
52629             // We do a quick check for a "bind" property before performing the more expensive subtype
52630             // check. This gives us a quicker out in the common case where an object type is not a function.
52631             var resolved = resolveStructuredTypeMembers(type);
52632             return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
52633                 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
52634         }
52635         function getTypeFacts(type) {
52636             var flags = type.flags;
52637             if (flags & 4 /* String */) {
52638                 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
52639             }
52640             if (flags & 128 /* StringLiteral */) {
52641                 var isEmpty = type.value === "";
52642                 return strictNullChecks ?
52643                     isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
52644                     isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
52645             }
52646             if (flags & (8 /* Number */ | 32 /* Enum */)) {
52647                 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
52648             }
52649             if (flags & 256 /* NumberLiteral */) {
52650                 var isZero = type.value === 0;
52651                 return strictNullChecks ?
52652                     isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
52653                     isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
52654             }
52655             if (flags & 64 /* BigInt */) {
52656                 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
52657             }
52658             if (flags & 2048 /* BigIntLiteral */) {
52659                 var isZero = isZeroBigInt(type);
52660                 return strictNullChecks ?
52661                     isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
52662                     isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
52663             }
52664             if (flags & 16 /* Boolean */) {
52665                 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
52666             }
52667             if (flags & 528 /* BooleanLike */) {
52668                 return strictNullChecks ?
52669                     (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
52670                     (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
52671             }
52672             if (flags & 524288 /* Object */) {
52673                 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
52674                     strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
52675                     isFunctionObjectType(type) ?
52676                         strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
52677                         strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52678             }
52679             if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
52680                 return 9830144 /* UndefinedFacts */;
52681             }
52682             if (flags & 65536 /* Null */) {
52683                 return 9363232 /* NullFacts */;
52684             }
52685             if (flags & 12288 /* ESSymbolLike */) {
52686                 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
52687             }
52688             if (flags & 67108864 /* NonPrimitive */) {
52689                 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52690             }
52691             if (flags & 131072 /* Never */) {
52692                 return 0 /* None */;
52693             }
52694             if (flags & 63176704 /* Instantiable */) {
52695                 return getTypeFacts(getBaseConstraintOfType(type) || unknownType);
52696             }
52697             if (flags & 3145728 /* UnionOrIntersection */) {
52698                 return getTypeFactsOfTypes(type.types);
52699             }
52700             return 16777215 /* All */;
52701         }
52702         function getTypeWithFacts(type, include) {
52703             return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
52704         }
52705         function getTypeWithDefault(type, defaultExpression) {
52706             if (defaultExpression) {
52707                 var defaultType = getTypeOfExpression(defaultExpression);
52708                 return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
52709             }
52710             return type;
52711         }
52712         function getTypeOfDestructuredProperty(type, name) {
52713             var nameType = getLiteralTypeFromPropertyName(name);
52714             if (!isTypeUsableAsPropertyName(nameType))
52715                 return errorType;
52716             var text = getPropertyNameFromType(nameType);
52717             return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
52718                 isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) ||
52719                 getIndexTypeOfType(type, 0 /* String */) ||
52720                 errorType;
52721         }
52722         function getTypeOfDestructuredArrayElement(type, index) {
52723             return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
52724                 checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) ||
52725                 errorType;
52726         }
52727         function getTypeOfDestructuredSpreadExpression(type) {
52728             return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
52729         }
52730         function getAssignedTypeOfBinaryExpression(node) {
52731             var isDestructuringDefaultAssignment = node.parent.kind === 192 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
52732                 node.parent.kind === 281 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
52733             return isDestructuringDefaultAssignment ?
52734                 getTypeWithDefault(getAssignedType(node), node.right) :
52735                 getTypeOfExpression(node.right);
52736         }
52737         function isDestructuringAssignmentTarget(parent) {
52738             return parent.parent.kind === 209 /* BinaryExpression */ && parent.parent.left === parent ||
52739                 parent.parent.kind === 232 /* ForOfStatement */ && parent.parent.initializer === parent;
52740         }
52741         function getAssignedTypeOfArrayLiteralElement(node, element) {
52742             return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
52743         }
52744         function getAssignedTypeOfSpreadExpression(node) {
52745             return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
52746         }
52747         function getAssignedTypeOfPropertyAssignment(node) {
52748             return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
52749         }
52750         function getAssignedTypeOfShorthandPropertyAssignment(node) {
52751             return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
52752         }
52753         function getAssignedType(node) {
52754             var parent = node.parent;
52755             switch (parent.kind) {
52756                 case 231 /* ForInStatement */:
52757                     return stringType;
52758                 case 232 /* ForOfStatement */:
52759                     return checkRightHandSideOfForOf(parent) || errorType;
52760                 case 209 /* BinaryExpression */:
52761                     return getAssignedTypeOfBinaryExpression(parent);
52762                 case 203 /* DeleteExpression */:
52763                     return undefinedType;
52764                 case 192 /* ArrayLiteralExpression */:
52765                     return getAssignedTypeOfArrayLiteralElement(parent, node);
52766                 case 213 /* SpreadElement */:
52767                     return getAssignedTypeOfSpreadExpression(parent);
52768                 case 281 /* PropertyAssignment */:
52769                     return getAssignedTypeOfPropertyAssignment(parent);
52770                 case 282 /* ShorthandPropertyAssignment */:
52771                     return getAssignedTypeOfShorthandPropertyAssignment(parent);
52772             }
52773             return errorType;
52774         }
52775         function getInitialTypeOfBindingElement(node) {
52776             var pattern = node.parent;
52777             var parentType = getInitialType(pattern.parent);
52778             var type = pattern.kind === 189 /* ObjectBindingPattern */ ?
52779                 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
52780                 !node.dotDotDotToken ?
52781                     getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
52782                     getTypeOfDestructuredSpreadExpression(parentType);
52783             return getTypeWithDefault(type, node.initializer);
52784         }
52785         function getTypeOfInitializer(node) {
52786             // Return the cached type if one is available. If the type of the variable was inferred
52787             // from its initializer, we'll already have cached the type. Otherwise we compute it now
52788             // without caching such that transient types are reflected.
52789             var links = getNodeLinks(node);
52790             return links.resolvedType || getTypeOfExpression(node);
52791         }
52792         function getInitialTypeOfVariableDeclaration(node) {
52793             if (node.initializer) {
52794                 return getTypeOfInitializer(node.initializer);
52795             }
52796             if (node.parent.parent.kind === 231 /* ForInStatement */) {
52797                 return stringType;
52798             }
52799             if (node.parent.parent.kind === 232 /* ForOfStatement */) {
52800                 return checkRightHandSideOfForOf(node.parent.parent) || errorType;
52801             }
52802             return errorType;
52803         }
52804         function getInitialType(node) {
52805             return node.kind === 242 /* VariableDeclaration */ ?
52806                 getInitialTypeOfVariableDeclaration(node) :
52807                 getInitialTypeOfBindingElement(node);
52808         }
52809         function isEmptyArrayAssignment(node) {
52810             return node.kind === 242 /* VariableDeclaration */ && node.initializer &&
52811                 isEmptyArrayLiteral(node.initializer) ||
52812                 node.kind !== 191 /* BindingElement */ && node.parent.kind === 209 /* BinaryExpression */ &&
52813                     isEmptyArrayLiteral(node.parent.right);
52814         }
52815         function getReferenceCandidate(node) {
52816             switch (node.kind) {
52817                 case 200 /* ParenthesizedExpression */:
52818                     return getReferenceCandidate(node.expression);
52819                 case 209 /* BinaryExpression */:
52820                     switch (node.operatorToken.kind) {
52821                         case 62 /* EqualsToken */:
52822                             return getReferenceCandidate(node.left);
52823                         case 27 /* CommaToken */:
52824                             return getReferenceCandidate(node.right);
52825                     }
52826             }
52827             return node;
52828         }
52829         function getReferenceRoot(node) {
52830             var parent = node.parent;
52831             return parent.kind === 200 /* ParenthesizedExpression */ ||
52832                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node ||
52833                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
52834                 getReferenceRoot(parent) : node;
52835         }
52836         function getTypeOfSwitchClause(clause) {
52837             if (clause.kind === 277 /* CaseClause */) {
52838                 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
52839             }
52840             return neverType;
52841         }
52842         function getSwitchClauseTypes(switchStatement) {
52843             var links = getNodeLinks(switchStatement);
52844             if (!links.switchTypes) {
52845                 links.switchTypes = [];
52846                 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
52847                     var clause = _a[_i];
52848                     links.switchTypes.push(getTypeOfSwitchClause(clause));
52849                 }
52850             }
52851             return links.switchTypes;
52852         }
52853         function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) {
52854             var witnesses = [];
52855             for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
52856                 var clause = _a[_i];
52857                 if (clause.kind === 277 /* CaseClause */) {
52858                     if (ts.isStringLiteralLike(clause.expression)) {
52859                         witnesses.push(clause.expression.text);
52860                         continue;
52861                     }
52862                     return ts.emptyArray;
52863                 }
52864                 if (retainDefault)
52865                     witnesses.push(/*explicitDefaultStatement*/ undefined);
52866             }
52867             return witnesses;
52868         }
52869         function eachTypeContainedIn(source, types) {
52870             return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
52871         }
52872         function isTypeSubsetOf(source, target) {
52873             return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
52874         }
52875         function isTypeSubsetOfUnion(source, target) {
52876             if (source.flags & 1048576 /* Union */) {
52877                 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
52878                     var t = _a[_i];
52879                     if (!containsType(target.types, t)) {
52880                         return false;
52881                     }
52882                 }
52883                 return true;
52884             }
52885             if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
52886                 return true;
52887             }
52888             return containsType(target.types, source);
52889         }
52890         function forEachType(type, f) {
52891             return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
52892         }
52893         function everyType(type, f) {
52894             return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
52895         }
52896         function filterType(type, f) {
52897             if (type.flags & 1048576 /* Union */) {
52898                 var types = type.types;
52899                 var filtered = ts.filter(types, f);
52900                 return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
52901             }
52902             return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
52903         }
52904         function countTypes(type) {
52905             return type.flags & 1048576 /* Union */ ? type.types.length : 1;
52906         }
52907         function mapType(type, mapper, noReductions) {
52908             if (type.flags & 131072 /* Never */) {
52909                 return type;
52910             }
52911             if (!(type.flags & 1048576 /* Union */)) {
52912                 return mapper(type);
52913             }
52914             var mappedTypes;
52915             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
52916                 var t = _a[_i];
52917                 var mapped = mapper(t);
52918                 if (mapped) {
52919                     if (!mappedTypes) {
52920                         mappedTypes = [mapped];
52921                     }
52922                     else {
52923                         mappedTypes.push(mapped);
52924                     }
52925                 }
52926             }
52927             return mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
52928         }
52929         function extractTypesOfKind(type, kind) {
52930             return filterType(type, function (t) { return (t.flags & kind) !== 0; });
52931         }
52932         // Return a new type in which occurrences of the string and number primitive types in
52933         // typeWithPrimitives have been replaced with occurrences of string literals and numeric
52934         // literals in typeWithLiterals, respectively.
52935         function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
52936             if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
52937                 isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
52938                 isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
52939                 return mapType(typeWithPrimitives, function (t) {
52940                     return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
52941                         t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
52942                             t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
52943                 });
52944             }
52945             return typeWithPrimitives;
52946         }
52947         function isIncomplete(flowType) {
52948             return flowType.flags === 0;
52949         }
52950         function getTypeFromFlowType(flowType) {
52951             return flowType.flags === 0 ? flowType.type : flowType;
52952         }
52953         function createFlowType(type, incomplete) {
52954             return incomplete ? { flags: 0, type: type } : type;
52955         }
52956         // An evolving array type tracks the element types that have so far been seen in an
52957         // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
52958         // array types are ultimately converted into manifest array types (using getFinalArrayType)
52959         // and never escape the getFlowTypeOfReference function.
52960         function createEvolvingArrayType(elementType) {
52961             var result = createObjectType(256 /* EvolvingArray */);
52962             result.elementType = elementType;
52963             return result;
52964         }
52965         function getEvolvingArrayType(elementType) {
52966             return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
52967         }
52968         // When adding evolving array element types we do not perform subtype reduction. Instead,
52969         // we defer subtype reduction until the evolving array type is finalized into a manifest
52970         // array type.
52971         function addEvolvingArrayElementType(evolvingArrayType, node) {
52972             var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node));
52973             return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
52974         }
52975         function createFinalArrayType(elementType) {
52976             return elementType.flags & 131072 /* Never */ ?
52977                 autoArrayType :
52978                 createArrayType(elementType.flags & 1048576 /* Union */ ?
52979                     getUnionType(elementType.types, 2 /* Subtype */) :
52980                     elementType);
52981         }
52982         // We perform subtype reduction upon obtaining the final array type from an evolving array type.
52983         function getFinalArrayType(evolvingArrayType) {
52984             return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
52985         }
52986         function finalizeEvolvingArrayType(type) {
52987             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
52988         }
52989         function getElementTypeOfEvolvingArrayType(type) {
52990             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
52991         }
52992         function isEvolvingArrayTypeList(types) {
52993             var hasEvolvingArrayType = false;
52994             for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
52995                 var t = types_16[_i];
52996                 if (!(t.flags & 131072 /* Never */)) {
52997                     if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
52998                         return false;
52999                     }
53000                     hasEvolvingArrayType = true;
53001                 }
53002             }
53003             return hasEvolvingArrayType;
53004         }
53005         // At flow control branch or loop junctions, if the type along every antecedent code path
53006         // is an evolving array type, we construct a combined evolving array type. Otherwise we
53007         // finalize all evolving array types.
53008         function getUnionOrEvolvingArrayType(types, subtypeReduction) {
53009             return isEvolvingArrayTypeList(types) ?
53010                 getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
53011                 getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
53012         }
53013         // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
53014         // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
53015         function isEvolvingArrayOperationTarget(node) {
53016             var root = getReferenceRoot(node);
53017             var parent = root.parent;
53018             var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
53019                 parent.parent.kind === 196 /* CallExpression */
53020                     && ts.isIdentifier(parent.name)
53021                     && ts.isPushOrUnshiftIdentifier(parent.name));
53022             var isElementAssignment = parent.kind === 195 /* ElementAccessExpression */ &&
53023                 parent.expression === root &&
53024                 parent.parent.kind === 209 /* BinaryExpression */ &&
53025                 parent.parent.operatorToken.kind === 62 /* EqualsToken */ &&
53026                 parent.parent.left === parent &&
53027                 !ts.isAssignmentTarget(parent.parent) &&
53028                 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
53029             return isLengthPushOrUnshift || isElementAssignment;
53030         }
53031         function isDeclarationWithExplicitTypeAnnotation(declaration) {
53032             return (declaration.kind === 242 /* VariableDeclaration */ || declaration.kind === 156 /* Parameter */ ||
53033                 declaration.kind === 159 /* PropertyDeclaration */ || declaration.kind === 158 /* PropertySignature */) &&
53034                 !!ts.getEffectiveTypeAnnotationNode(declaration);
53035         }
53036         function getExplicitTypeOfSymbol(symbol, diagnostic) {
53037             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
53038                 return getTypeOfSymbol(symbol);
53039             }
53040             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
53041                 var declaration = symbol.valueDeclaration;
53042                 if (declaration) {
53043                     if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
53044                         return getTypeOfSymbol(symbol);
53045                     }
53046                     if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
53047                         var statement = declaration.parent.parent;
53048                         var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined);
53049                         if (expressionType) {
53050                             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
53051                             return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined);
53052                         }
53053                     }
53054                     if (diagnostic) {
53055                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
53056                     }
53057                 }
53058             }
53059         }
53060         // We require the dotted function name in an assertion expression to be comprised of identifiers
53061         // that reference function, method, class or value module symbols; or variable, property or
53062         // parameter symbols with declarations that have explicit type annotations. Such references are
53063         // resolvable with no possibility of triggering circularities in control flow analysis.
53064         function getTypeOfDottedName(node, diagnostic) {
53065             if (!(node.flags & 16777216 /* InWithStatement */)) {
53066                 switch (node.kind) {
53067                     case 75 /* Identifier */:
53068                         var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
53069                         return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
53070                     case 104 /* ThisKeyword */:
53071                         return getExplicitThisType(node);
53072                     case 102 /* SuperKeyword */:
53073                         return checkSuperExpression(node);
53074                     case 194 /* PropertyAccessExpression */:
53075                         var type = getTypeOfDottedName(node.expression, diagnostic);
53076                         var prop = type && getPropertyOfType(type, node.name.escapedText);
53077                         return prop && getExplicitTypeOfSymbol(prop, diagnostic);
53078                     case 200 /* ParenthesizedExpression */:
53079                         return getTypeOfDottedName(node.expression, diagnostic);
53080                 }
53081             }
53082         }
53083         function getEffectsSignature(node) {
53084             var links = getNodeLinks(node);
53085             var signature = links.effectsSignature;
53086             if (signature === undefined) {
53087                 // A call expression parented by an expression statement is a potential assertion. Other call
53088                 // expressions are potential type predicate function calls. In order to avoid triggering
53089                 // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
53090                 // target expression of an assertion.
53091                 var funcType = void 0;
53092                 if (node.parent.kind === 226 /* ExpressionStatement */) {
53093                     funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
53094                 }
53095                 else if (node.expression.kind !== 102 /* SuperKeyword */) {
53096                     if (ts.isOptionalChain(node)) {
53097                         funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
53098                     }
53099                     else {
53100                         funcType = checkNonNullExpression(node.expression);
53101                     }
53102                 }
53103                 var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
53104                 var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
53105                     ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
53106                         undefined;
53107                 signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
53108             }
53109             return signature === unknownSignature ? undefined : signature;
53110         }
53111         function hasTypePredicateOrNeverReturnType(signature) {
53112             return !!(getTypePredicateOfSignature(signature) ||
53113                 signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
53114         }
53115         function getTypePredicateArgument(predicate, callExpression) {
53116             if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
53117                 return callExpression.arguments[predicate.parameterIndex];
53118             }
53119             var invokedExpression = ts.skipParentheses(callExpression.expression);
53120             return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
53121         }
53122         function reportFlowControlError(node) {
53123             var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
53124             var sourceFile = ts.getSourceFileOfNode(node);
53125             var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
53126             diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
53127         }
53128         function isReachableFlowNode(flow) {
53129             var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false);
53130             lastFlowNode = flow;
53131             lastFlowNodeReachable = result;
53132             return result;
53133         }
53134         function isFalseExpression(expr) {
53135             var node = ts.skipParentheses(expr);
53136             return node.kind === 91 /* FalseKeyword */ || node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
53137                 node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
53138         }
53139         function isReachableFlowNodeWorker(flow, noCacheCheck) {
53140             while (true) {
53141                 if (flow === lastFlowNode) {
53142                     return lastFlowNodeReachable;
53143                 }
53144                 var flags = flow.flags;
53145                 if (flags & 4096 /* Shared */) {
53146                     if (!noCacheCheck) {
53147                         var id = getFlowNodeId(flow);
53148                         var reachable = flowNodeReachable[id];
53149                         return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true));
53150                     }
53151                     noCacheCheck = false;
53152                 }
53153                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
53154                     flow = flow.antecedent;
53155                 }
53156                 else if (flags & 512 /* Call */) {
53157                     var signature = getEffectsSignature(flow.node);
53158                     if (signature) {
53159                         var predicate = getTypePredicateOfSignature(signature);
53160                         if (predicate && predicate.kind === 3 /* AssertsIdentifier */) {
53161                             var predicateArgument = flow.node.arguments[predicate.parameterIndex];
53162                             if (predicateArgument && isFalseExpression(predicateArgument)) {
53163                                 return false;
53164                             }
53165                         }
53166                         if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53167                             return false;
53168                         }
53169                     }
53170                     flow = flow.antecedent;
53171                 }
53172                 else if (flags & 4 /* BranchLabel */) {
53173                     // A branching point is reachable if any branch is reachable.
53174                     return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
53175                 }
53176                 else if (flags & 8 /* LoopLabel */) {
53177                     // A loop is reachable if the control flow path that leads to the top is reachable.
53178                     flow = flow.antecedents[0];
53179                 }
53180                 else if (flags & 128 /* SwitchClause */) {
53181                     // The control flow path representing an unmatched value in a switch statement with
53182                     // no default clause is unreachable if the switch statement is exhaustive.
53183                     if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
53184                         return false;
53185                     }
53186                     flow = flow.antecedent;
53187                 }
53188                 else if (flags & 1024 /* ReduceLabel */) {
53189                     // Cache is unreliable once we start adjusting labels
53190                     lastFlowNode = undefined;
53191                     var target = flow.target;
53192                     var saveAntecedents = target.antecedents;
53193                     target.antecedents = flow.antecedents;
53194                     var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false);
53195                     target.antecedents = saveAntecedents;
53196                     return result;
53197                 }
53198                 else {
53199                     return !(flags & 1 /* Unreachable */);
53200                 }
53201             }
53202         }
53203         function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
53204             if (initialType === void 0) { initialType = declaredType; }
53205             var key;
53206             var keySet = false;
53207             var flowDepth = 0;
53208             if (flowAnalysisDisabled) {
53209                 return errorType;
53210             }
53211             if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) {
53212                 return declaredType;
53213             }
53214             flowInvocationCount++;
53215             var sharedFlowStart = sharedFlowCount;
53216             var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
53217             sharedFlowCount = sharedFlowStart;
53218             // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
53219             // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
53220             // on empty arrays are possible without implicit any errors and new element types can be inferred without
53221             // type mismatch errors.
53222             var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
53223             if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 218 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
53224                 return declaredType;
53225             }
53226             return resultType;
53227             function getOrSetCacheKey() {
53228                 if (keySet) {
53229                     return key;
53230                 }
53231                 keySet = true;
53232                 return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
53233             }
53234             function getTypeAtFlowNode(flow) {
53235                 if (flowDepth === 2000) {
53236                     // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
53237                     // and disable further control flow analysis in the containing function or module body.
53238                     flowAnalysisDisabled = true;
53239                     reportFlowControlError(reference);
53240                     return errorType;
53241                 }
53242                 flowDepth++;
53243                 while (true) {
53244                     var flags = flow.flags;
53245                     if (flags & 4096 /* Shared */) {
53246                         // We cache results of flow type resolution for shared nodes that were previously visited in
53247                         // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
53248                         // antecedent of more than one node.
53249                         for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
53250                             if (sharedFlowNodes[i] === flow) {
53251                                 flowDepth--;
53252                                 return sharedFlowTypes[i];
53253                             }
53254                         }
53255                     }
53256                     var type = void 0;
53257                     if (flags & 16 /* Assignment */) {
53258                         type = getTypeAtFlowAssignment(flow);
53259                         if (!type) {
53260                             flow = flow.antecedent;
53261                             continue;
53262                         }
53263                     }
53264                     else if (flags & 512 /* Call */) {
53265                         type = getTypeAtFlowCall(flow);
53266                         if (!type) {
53267                             flow = flow.antecedent;
53268                             continue;
53269                         }
53270                     }
53271                     else if (flags & 96 /* Condition */) {
53272                         type = getTypeAtFlowCondition(flow);
53273                     }
53274                     else if (flags & 128 /* SwitchClause */) {
53275                         type = getTypeAtSwitchClause(flow);
53276                     }
53277                     else if (flags & 12 /* Label */) {
53278                         if (flow.antecedents.length === 1) {
53279                             flow = flow.antecedents[0];
53280                             continue;
53281                         }
53282                         type = flags & 4 /* BranchLabel */ ?
53283                             getTypeAtFlowBranchLabel(flow) :
53284                             getTypeAtFlowLoopLabel(flow);
53285                     }
53286                     else if (flags & 256 /* ArrayMutation */) {
53287                         type = getTypeAtFlowArrayMutation(flow);
53288                         if (!type) {
53289                             flow = flow.antecedent;
53290                             continue;
53291                         }
53292                     }
53293                     else if (flags & 1024 /* ReduceLabel */) {
53294                         var target = flow.target;
53295                         var saveAntecedents = target.antecedents;
53296                         target.antecedents = flow.antecedents;
53297                         type = getTypeAtFlowNode(flow.antecedent);
53298                         target.antecedents = saveAntecedents;
53299                     }
53300                     else if (flags & 2 /* Start */) {
53301                         // Check if we should continue with the control flow of the containing function.
53302                         var container = flow.node;
53303                         if (container && container !== flowContainer &&
53304                             reference.kind !== 194 /* PropertyAccessExpression */ &&
53305                             reference.kind !== 195 /* ElementAccessExpression */ &&
53306                             reference.kind !== 104 /* ThisKeyword */) {
53307                             flow = container.flowNode;
53308                             continue;
53309                         }
53310                         // At the top of the flow we have the initial type.
53311                         type = initialType;
53312                     }
53313                     else {
53314                         // Unreachable code errors are reported in the binding phase. Here we
53315                         // simply return the non-auto declared type to reduce follow-on errors.
53316                         type = convertAutoToAny(declaredType);
53317                     }
53318                     if (flags & 4096 /* Shared */) {
53319                         // Record visited node and the associated type in the cache.
53320                         sharedFlowNodes[sharedFlowCount] = flow;
53321                         sharedFlowTypes[sharedFlowCount] = type;
53322                         sharedFlowCount++;
53323                     }
53324                     flowDepth--;
53325                     return type;
53326                 }
53327             }
53328             function getInitialOrAssignedType(flow) {
53329                 var node = flow.node;
53330                 return getConstraintForLocation(node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */ ?
53331                     getInitialType(node) :
53332                     getAssignedType(node), reference);
53333             }
53334             function getTypeAtFlowAssignment(flow) {
53335                 var node = flow.node;
53336                 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
53337                 // only need to evaluate the assigned type if the declared type is a union type.
53338                 if (isMatchingReference(reference, node)) {
53339                     if (!isReachableFlowNode(flow)) {
53340                         return unreachableNeverType;
53341                     }
53342                     if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
53343                         var flowType = getTypeAtFlowNode(flow.antecedent);
53344                         return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
53345                     }
53346                     if (declaredType === autoType || declaredType === autoArrayType) {
53347                         if (isEmptyArrayAssignment(node)) {
53348                             return getEvolvingArrayType(neverType);
53349                         }
53350                         var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow));
53351                         return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
53352                     }
53353                     if (declaredType.flags & 1048576 /* Union */) {
53354                         return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
53355                     }
53356                     return declaredType;
53357                 }
53358                 // We didn't have a direct match. However, if the reference is a dotted name, this
53359                 // may be an assignment to a left hand part of the reference. For example, for a
53360                 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
53361                 // return the declared type.
53362                 if (containsMatchingReference(reference, node)) {
53363                     if (!isReachableFlowNode(flow)) {
53364                         return unreachableNeverType;
53365                     }
53366                     // A matching dotted name might also be an expando property on a function *expression*,
53367                     // in which case we continue control flow analysis back to the function's declaration
53368                     if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
53369                         var init = ts.getDeclaredExpandoInitializer(node);
53370                         if (init && (init.kind === 201 /* FunctionExpression */ || init.kind === 202 /* ArrowFunction */)) {
53371                             return getTypeAtFlowNode(flow.antecedent);
53372                         }
53373                     }
53374                     return declaredType;
53375                 }
53376                 // for (const _ in ref) acts as a nonnull on ref
53377                 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 231 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
53378                     return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
53379                 }
53380                 // Assignment doesn't affect reference
53381                 return undefined;
53382             }
53383             function narrowTypeByAssertion(type, expr) {
53384                 var node = ts.skipParentheses(expr);
53385                 if (node.kind === 91 /* FalseKeyword */) {
53386                     return unreachableNeverType;
53387                 }
53388                 if (node.kind === 209 /* BinaryExpression */) {
53389                     if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
53390                         return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
53391                     }
53392                     if (node.operatorToken.kind === 56 /* BarBarToken */) {
53393                         return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
53394                     }
53395                 }
53396                 return narrowType(type, node, /*assumeTrue*/ true);
53397             }
53398             function getTypeAtFlowCall(flow) {
53399                 var signature = getEffectsSignature(flow.node);
53400                 if (signature) {
53401                     var predicate = getTypePredicateOfSignature(signature);
53402                     if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
53403                         var flowType = getTypeAtFlowNode(flow.antecedent);
53404                         var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
53405                         var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
53406                             predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
53407                                 type;
53408                         return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
53409                     }
53410                     if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53411                         return unreachableNeverType;
53412                     }
53413                 }
53414                 return undefined;
53415             }
53416             function getTypeAtFlowArrayMutation(flow) {
53417                 if (declaredType === autoType || declaredType === autoArrayType) {
53418                     var node = flow.node;
53419                     var expr = node.kind === 196 /* CallExpression */ ?
53420                         node.expression.expression :
53421                         node.left.expression;
53422                     if (isMatchingReference(reference, getReferenceCandidate(expr))) {
53423                         var flowType = getTypeAtFlowNode(flow.antecedent);
53424                         var type = getTypeFromFlowType(flowType);
53425                         if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
53426                             var evolvedType_1 = type;
53427                             if (node.kind === 196 /* CallExpression */) {
53428                                 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
53429                                     var arg = _a[_i];
53430                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
53431                                 }
53432                             }
53433                             else {
53434                                 // 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)
53435                                 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
53436                                 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
53437                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
53438                                 }
53439                             }
53440                             return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
53441                         }
53442                         return flowType;
53443                     }
53444                 }
53445                 return undefined;
53446             }
53447             function getTypeAtFlowCondition(flow) {
53448                 var flowType = getTypeAtFlowNode(flow.antecedent);
53449                 var type = getTypeFromFlowType(flowType);
53450                 if (type.flags & 131072 /* Never */) {
53451                     return flowType;
53452                 }
53453                 // If we have an antecedent type (meaning we're reachable in some way), we first
53454                 // attempt to narrow the antecedent type. If that produces the never type, and if
53455                 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
53456                 // take the type guard as an indication that control *could* reach here once we
53457                 // have the complete type. We proceed by switching to the silent never type which
53458                 // doesn't report errors when operators are applied to it. Note that this is the
53459                 // *only* place a silent never type is ever generated.
53460                 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
53461                 var nonEvolvingType = finalizeEvolvingArrayType(type);
53462                 var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
53463                 if (narrowedType === nonEvolvingType) {
53464                     return flowType;
53465                 }
53466                 var incomplete = isIncomplete(flowType);
53467                 var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType;
53468                 return createFlowType(resultType, incomplete);
53469             }
53470             function getTypeAtSwitchClause(flow) {
53471                 var expr = flow.switchStatement.expression;
53472                 var flowType = getTypeAtFlowNode(flow.antecedent);
53473                 var type = getTypeFromFlowType(flowType);
53474                 if (isMatchingReference(reference, expr)) {
53475                     type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53476                 }
53477                 else if (expr.kind === 204 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
53478                     type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53479                 }
53480                 else {
53481                     if (strictNullChecks) {
53482                         if (optionalChainContainsReference(expr, reference)) {
53483                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
53484                         }
53485                         else if (expr.kind === 204 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
53486                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
53487                         }
53488                     }
53489                     if (isMatchingReferenceDiscriminant(expr, type)) {
53490                         type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
53491                     }
53492                 }
53493                 return createFlowType(type, isIncomplete(flowType));
53494             }
53495             function getTypeAtFlowBranchLabel(flow) {
53496                 var antecedentTypes = [];
53497                 var subtypeReduction = false;
53498                 var seenIncomplete = false;
53499                 var bypassFlow;
53500                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53501                     var antecedent = _a[_i];
53502                     if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
53503                         // The antecedent is the bypass branch of a potentially exhaustive switch statement.
53504                         bypassFlow = antecedent;
53505                         continue;
53506                     }
53507                     var flowType = getTypeAtFlowNode(antecedent);
53508                     var type = getTypeFromFlowType(flowType);
53509                     // If the type at a particular antecedent path is the declared type and the
53510                     // reference is known to always be assigned (i.e. when declared and initial types
53511                     // are the same), there is no reason to process more antecedents since the only
53512                     // possible outcome is subtypes that will be removed in the final union type anyway.
53513                     if (type === declaredType && declaredType === initialType) {
53514                         return type;
53515                     }
53516                     ts.pushIfUnique(antecedentTypes, type);
53517                     // If an antecedent type is not a subset of the declared type, we need to perform
53518                     // subtype reduction. This happens when a "foreign" type is injected into the control
53519                     // flow using the instanceof operator or a user defined type predicate.
53520                     if (!isTypeSubsetOf(type, declaredType)) {
53521                         subtypeReduction = true;
53522                     }
53523                     if (isIncomplete(flowType)) {
53524                         seenIncomplete = true;
53525                     }
53526                 }
53527                 if (bypassFlow) {
53528                     var flowType = getTypeAtFlowNode(bypassFlow);
53529                     var type = getTypeFromFlowType(flowType);
53530                     // If the bypass flow contributes a type we haven't seen yet and the switch statement
53531                     // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
53532                     // the risk of circularities, we only want to perform them when they make a difference.
53533                     if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
53534                         if (type === declaredType && declaredType === initialType) {
53535                             return type;
53536                         }
53537                         antecedentTypes.push(type);
53538                         if (!isTypeSubsetOf(type, declaredType)) {
53539                             subtypeReduction = true;
53540                         }
53541                         if (isIncomplete(flowType)) {
53542                             seenIncomplete = true;
53543                         }
53544                     }
53545                 }
53546                 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
53547             }
53548             function getTypeAtFlowLoopLabel(flow) {
53549                 // If we have previously computed the control flow type for the reference at
53550                 // this flow loop junction, return the cached type.
53551                 var id = getFlowNodeId(flow);
53552                 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap());
53553                 var key = getOrSetCacheKey();
53554                 if (!key) {
53555                     // No cache key is generated when binding patterns are in unnarrowable situations
53556                     return declaredType;
53557                 }
53558                 var cached = cache.get(key);
53559                 if (cached) {
53560                     return cached;
53561                 }
53562                 // If this flow loop junction and reference are already being processed, return
53563                 // the union of the types computed for each branch so far, marked as incomplete.
53564                 // It is possible to see an empty array in cases where loops are nested and the
53565                 // back edge of the outer loop reaches an inner loop that is already being analyzed.
53566                 // In such cases we restart the analysis of the inner loop, which will then see
53567                 // a non-empty in-process array for the outer loop and eventually terminate because
53568                 // the first antecedent of a loop junction is always the non-looping control flow
53569                 // path that leads to the top.
53570                 for (var i = flowLoopStart; i < flowLoopCount; i++) {
53571                     if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
53572                         return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
53573                     }
53574                 }
53575                 // Add the flow loop junction and reference to the in-process stack and analyze
53576                 // each antecedent code path.
53577                 var antecedentTypes = [];
53578                 var subtypeReduction = false;
53579                 var firstAntecedentType;
53580                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53581                     var antecedent = _a[_i];
53582                     var flowType = void 0;
53583                     if (!firstAntecedentType) {
53584                         // The first antecedent of a loop junction is always the non-looping control
53585                         // flow path that leads to the top.
53586                         flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
53587                     }
53588                     else {
53589                         // All but the first antecedent are the looping control flow paths that lead
53590                         // back to the loop junction. We track these on the flow loop stack.
53591                         flowLoopNodes[flowLoopCount] = flow;
53592                         flowLoopKeys[flowLoopCount] = key;
53593                         flowLoopTypes[flowLoopCount] = antecedentTypes;
53594                         flowLoopCount++;
53595                         var saveFlowTypeCache = flowTypeCache;
53596                         flowTypeCache = undefined;
53597                         flowType = getTypeAtFlowNode(antecedent);
53598                         flowTypeCache = saveFlowTypeCache;
53599                         flowLoopCount--;
53600                         // If we see a value appear in the cache it is a sign that control flow analysis
53601                         // was restarted and completed by checkExpressionCached. We can simply pick up
53602                         // the resulting type and bail out.
53603                         var cached_1 = cache.get(key);
53604                         if (cached_1) {
53605                             return cached_1;
53606                         }
53607                     }
53608                     var type = getTypeFromFlowType(flowType);
53609                     ts.pushIfUnique(antecedentTypes, type);
53610                     // If an antecedent type is not a subset of the declared type, we need to perform
53611                     // subtype reduction. This happens when a "foreign" type is injected into the control
53612                     // flow using the instanceof operator or a user defined type predicate.
53613                     if (!isTypeSubsetOf(type, declaredType)) {
53614                         subtypeReduction = true;
53615                     }
53616                     // If the type at a particular antecedent path is the declared type there is no
53617                     // reason to process more antecedents since the only possible outcome is subtypes
53618                     // that will be removed in the final union type anyway.
53619                     if (type === declaredType) {
53620                         break;
53621                     }
53622                 }
53623                 // The result is incomplete if the first antecedent (the non-looping control flow path)
53624                 // is incomplete.
53625                 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
53626                 if (isIncomplete(firstAntecedentType)) {
53627                     return createFlowType(result, /*incomplete*/ true);
53628                 }
53629                 cache.set(key, result);
53630                 return result;
53631             }
53632             function isMatchingReferenceDiscriminant(expr, computedType) {
53633                 if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
53634                     return false;
53635                 }
53636                 var name = getAccessedPropertyName(expr);
53637                 if (name === undefined) {
53638                     return false;
53639                 }
53640                 return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name);
53641             }
53642             function narrowTypeByDiscriminant(type, access, narrowType) {
53643                 var propName = getAccessedPropertyName(access);
53644                 if (propName === undefined) {
53645                     return type;
53646                 }
53647                 var propType = getTypeOfPropertyOfType(type, propName);
53648                 if (!propType) {
53649                     return type;
53650                 }
53651                 var narrowedPropType = narrowType(propType);
53652                 return filterType(type, function (t) {
53653                     var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
53654                     return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType);
53655                 });
53656             }
53657             function narrowTypeByTruthiness(type, expr, assumeTrue) {
53658                 if (isMatchingReference(reference, expr)) {
53659                     return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
53660                 }
53661                 if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
53662                     type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53663                 }
53664                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
53665                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
53666                 }
53667                 return type;
53668             }
53669             function isTypePresencePossible(type, propName, assumeTrue) {
53670                 if (getIndexInfoOfType(type, 0 /* String */)) {
53671                     return true;
53672                 }
53673                 var prop = getPropertyOfType(type, propName);
53674                 if (prop) {
53675                     return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
53676                 }
53677                 return !assumeTrue;
53678             }
53679             function narrowByInKeyword(type, literal, assumeTrue) {
53680                 if (type.flags & (1048576 /* Union */ | 524288 /* Object */) || isThisTypeParameter(type)) {
53681                     var propName_1 = ts.escapeLeadingUnderscores(literal.text);
53682                     return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
53683                 }
53684                 return type;
53685             }
53686             function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
53687                 switch (expr.operatorToken.kind) {
53688                     case 62 /* EqualsToken */:
53689                         return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
53690                     case 34 /* EqualsEqualsToken */:
53691                     case 35 /* ExclamationEqualsToken */:
53692                     case 36 /* EqualsEqualsEqualsToken */:
53693                     case 37 /* ExclamationEqualsEqualsToken */:
53694                         var operator_1 = expr.operatorToken.kind;
53695                         var left_1 = getReferenceCandidate(expr.left);
53696                         var right_1 = getReferenceCandidate(expr.right);
53697                         if (left_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
53698                             return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
53699                         }
53700                         if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
53701                             return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
53702                         }
53703                         if (isMatchingReference(reference, left_1)) {
53704                             return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
53705                         }
53706                         if (isMatchingReference(reference, right_1)) {
53707                             return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
53708                         }
53709                         if (strictNullChecks) {
53710                             if (optionalChainContainsReference(left_1, reference)) {
53711                                 type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue);
53712                             }
53713                             else if (optionalChainContainsReference(right_1, reference)) {
53714                                 type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue);
53715                             }
53716                         }
53717                         if (isMatchingReferenceDiscriminant(left_1, declaredType)) {
53718                             return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
53719                         }
53720                         if (isMatchingReferenceDiscriminant(right_1, declaredType)) {
53721                             return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
53722                         }
53723                         if (isMatchingConstructorReference(left_1)) {
53724                             return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue);
53725                         }
53726                         if (isMatchingConstructorReference(right_1)) {
53727                             return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue);
53728                         }
53729                         break;
53730                     case 98 /* InstanceOfKeyword */:
53731                         return narrowTypeByInstanceof(type, expr, assumeTrue);
53732                     case 97 /* InKeyword */:
53733                         var target = getReferenceCandidate(expr.right);
53734                         if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
53735                             return narrowByInKeyword(type, expr.left, assumeTrue);
53736                         }
53737                         break;
53738                     case 27 /* CommaToken */:
53739                         return narrowType(type, expr.right, assumeTrue);
53740                 }
53741                 return type;
53742             }
53743             function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
53744                 // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
53745                 // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
53746                 // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
53747                 // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
53748                 // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
53749                 // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
53750                 // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
53751                 // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
53752                 // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
53753                 var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
53754                 var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
53755                 var valueType = getTypeOfExpression(value);
53756                 // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
53757                 var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
53758                     equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
53759                 return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
53760             }
53761             function narrowTypeByEquality(type, operator, value, assumeTrue) {
53762                 if (type.flags & 1 /* Any */) {
53763                     return type;
53764                 }
53765                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53766                     assumeTrue = !assumeTrue;
53767                 }
53768                 var valueType = getTypeOfExpression(value);
53769                 if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
53770                     if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
53771                         return valueType;
53772                     }
53773                     if (valueType.flags & 524288 /* Object */) {
53774                         return nonPrimitiveType;
53775                     }
53776                     return type;
53777                 }
53778                 if (valueType.flags & 98304 /* Nullable */) {
53779                     if (!strictNullChecks) {
53780                         return type;
53781                     }
53782                     var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
53783                     var facts = doubleEquals ?
53784                         assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
53785                         valueType.flags & 65536 /* Null */ ?
53786                             assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
53787                             assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
53788                     return getTypeWithFacts(type, facts);
53789                 }
53790                 if (type.flags & 67637251 /* NotUnionOrUnit */) {
53791                     return type;
53792                 }
53793                 if (assumeTrue) {
53794                     var filterFn = operator === 34 /* EqualsEqualsToken */ ?
53795                         (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) :
53796                         function (t) { return areTypesComparable(t, valueType); };
53797                     var narrowedType = filterType(type, filterFn);
53798                     return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType);
53799                 }
53800                 if (isUnitType(valueType)) {
53801                     var regularType_1 = getRegularTypeOfLiteralType(valueType);
53802                     return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; });
53803                 }
53804                 return type;
53805             }
53806             function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
53807                 // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
53808                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53809                     assumeTrue = !assumeTrue;
53810                 }
53811                 var target = getReferenceCandidate(typeOfExpr.expression);
53812                 if (!isMatchingReference(reference, target)) {
53813                     if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
53814                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53815                     }
53816                     return type;
53817                 }
53818                 if (type.flags & 1 /* Any */ && literal.text === "function") {
53819                     return type;
53820                 }
53821                 if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") {
53822                     // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't
53823                     // need to check for the reverse typeof x === 'object' && x since that already narrows correctly.
53824                     if (typeOfExpr.parent.parent.kind === 209 /* BinaryExpression */) {
53825                         var expr = typeOfExpr.parent.parent;
53826                         if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) {
53827                             return nonPrimitiveType;
53828                         }
53829                     }
53830                     return getUnionType([nonPrimitiveType, nullType]);
53831                 }
53832                 var facts = assumeTrue ?
53833                     typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
53834                     typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
53835                 return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts);
53836                 function narrowTypeForTypeof(type) {
53837                     // We narrow a non-union type to an exact primitive type if the non-union type
53838                     // is a supertype of that primitive type. For example, type 'any' can be narrowed
53839                     // to one of the primitive types.
53840                     var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text);
53841                     if (targetType) {
53842                         if (isTypeSubtypeOf(type, targetType)) {
53843                             return type;
53844                         }
53845                         if (isTypeSubtypeOf(targetType, type)) {
53846                             return targetType;
53847                         }
53848                         if (type.flags & 63176704 /* Instantiable */) {
53849                             var constraint = getBaseConstraintOfType(type) || anyType;
53850                             if (isTypeSubtypeOf(targetType, constraint)) {
53851                                 return getIntersectionType([type, targetType]);
53852                             }
53853                         }
53854                     }
53855                     return type;
53856                 }
53857             }
53858             function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
53859                 var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
53860                 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
53861             }
53862             function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
53863                 // We only narrow if all case expressions specify
53864                 // values with unit types, except for the case where
53865                 // `type` is unknown. In this instance we map object
53866                 // types to the nonPrimitive type and narrow with that.
53867                 var switchTypes = getSwitchClauseTypes(switchStatement);
53868                 if (!switchTypes.length) {
53869                     return type;
53870                 }
53871                 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
53872                 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
53873                 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
53874                     var groundClauseTypes = void 0;
53875                     for (var i = 0; i < clauseTypes.length; i += 1) {
53876                         var t = clauseTypes[i];
53877                         if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
53878                             if (groundClauseTypes !== undefined) {
53879                                 groundClauseTypes.push(t);
53880                             }
53881                         }
53882                         else if (t.flags & 524288 /* Object */) {
53883                             if (groundClauseTypes === undefined) {
53884                                 groundClauseTypes = clauseTypes.slice(0, i);
53885                             }
53886                             groundClauseTypes.push(nonPrimitiveType);
53887                         }
53888                         else {
53889                             return type;
53890                         }
53891                     }
53892                     return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
53893                 }
53894                 var discriminantType = getUnionType(clauseTypes);
53895                 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
53896                     replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
53897                 if (!hasDefaultClause) {
53898                     return caseType;
53899                 }
53900                 var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
53901                 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
53902             }
53903             function getImpliedTypeFromTypeofCase(type, text) {
53904                 switch (text) {
53905                     case "function":
53906                         return type.flags & 1 /* Any */ ? type : globalFunctionType;
53907                     case "object":
53908                         return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
53909                     default:
53910                         return typeofTypesByName.get(text) || type;
53911                 }
53912             }
53913             function narrowTypeForTypeofSwitch(candidate) {
53914                 return function (type) {
53915                     if (isTypeSubtypeOf(candidate, type)) {
53916                         return candidate;
53917                     }
53918                     if (type.flags & 63176704 /* Instantiable */) {
53919                         var constraint = getBaseConstraintOfType(type) || anyType;
53920                         if (isTypeSubtypeOf(candidate, constraint)) {
53921                             return getIntersectionType([type, candidate]);
53922                         }
53923                     }
53924                     return type;
53925                 };
53926             }
53927             function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
53928                 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true);
53929                 if (!switchWitnesses.length) {
53930                     return type;
53931                 }
53932                 //  Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
53933                 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
53934                 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
53935                 var clauseWitnesses;
53936                 var switchFacts;
53937                 if (defaultCaseLocation > -1) {
53938                     // We no longer need the undefined denoting an
53939                     // explicit default case. Remove the undefined and
53940                     // fix-up clauseStart and clauseEnd.  This means
53941                     // that we don't have to worry about undefined
53942                     // in the witness array.
53943                     var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
53944                     // The adjusted clause start and end after removing the `default` statement.
53945                     var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
53946                     var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
53947                     clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
53948                     switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
53949                 }
53950                 else {
53951                     clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
53952                     switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
53953                 }
53954                 if (hasDefaultClause) {
53955                     return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
53956                 }
53957                 /*
53958                   The implied type is the raw type suggested by a
53959                   value being caught in this clause.
53960
53961                   When the clause contains a default case we ignore
53962                   the implied type and try to narrow using any facts
53963                   we can learn: see `switchFacts`.
53964
53965                   Example:
53966                   switch (typeof x) {
53967                       case 'number':
53968                       case 'string': break;
53969                       default: break;
53970                       case 'number':
53971                       case 'boolean': break
53972                   }
53973
53974                   In the first clause (case `number` and `string`) the
53975                   implied type is number | string.
53976
53977                   In the default clause we de not compute an implied type.
53978
53979                   In the third clause (case `number` and `boolean`)
53980                   the naive implied type is number | boolean, however
53981                   we use the type facts to narrow the implied type to
53982                   boolean. We know that number cannot be selected
53983                   because it is caught in the first clause.
53984                 */
53985                 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts);
53986                 if (impliedType.flags & 1048576 /* Union */) {
53987                     impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type));
53988                 }
53989                 return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts);
53990             }
53991             function isMatchingConstructorReference(expr) {
53992                 return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" ||
53993                     ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") &&
53994                     isMatchingReference(reference, expr.expression);
53995             }
53996             function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
53997                 // Do not narrow when checking inequality.
53998                 if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) {
53999                     return type;
54000                 }
54001                 // Get the type of the constructor identifier expression, if it is not a function then do not narrow.
54002                 var identifierType = getTypeOfExpression(identifier);
54003                 if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
54004                     return type;
54005                 }
54006                 // Get the prototype property of the type identifier so we can find out its type.
54007                 var prototypeProperty = getPropertyOfType(identifierType, "prototype");
54008                 if (!prototypeProperty) {
54009                     return type;
54010                 }
54011                 // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow.
54012                 var prototypeType = getTypeOfSymbol(prototypeProperty);
54013                 var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined;
54014                 if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
54015                     return type;
54016                 }
54017                 // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`.
54018                 if (isTypeAny(type)) {
54019                     return candidate;
54020                 }
54021                 // Filter out types that are not considered to be "constructed by" the `candidate` type.
54022                 return filterType(type, function (t) { return isConstructedBy(t, candidate); });
54023                 function isConstructedBy(source, target) {
54024                     // If either the source or target type are a class type then we need to check that they are the same exact type.
54025                     // This is because you may have a class `A` that defines some set of properties, and another class `B`
54026                     // that defines the same set of properties as class `A`, in that case they are structurally the same
54027                     // type, but when you do something like `instanceOfA.constructor === B` it will return false.
54028                     if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ ||
54029                         target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) {
54030                         return source.symbol === target.symbol;
54031                     }
54032                     // For all other types just check that the `source` type is a subtype of the `target` type.
54033                     return isTypeSubtypeOf(source, target);
54034                 }
54035             }
54036             function narrowTypeByInstanceof(type, expr, assumeTrue) {
54037                 var left = getReferenceCandidate(expr.left);
54038                 if (!isMatchingReference(reference, left)) {
54039                     if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
54040                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54041                     }
54042                     return type;
54043                 }
54044                 // Check that right operand is a function type with a prototype property
54045                 var rightType = getTypeOfExpression(expr.right);
54046                 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
54047                     return type;
54048                 }
54049                 var targetType;
54050                 var prototypeProperty = getPropertyOfType(rightType, "prototype");
54051                 if (prototypeProperty) {
54052                     // Target type is type of the prototype property
54053                     var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
54054                     if (!isTypeAny(prototypePropertyType)) {
54055                         targetType = prototypePropertyType;
54056                     }
54057                 }
54058                 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
54059                 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
54060                     return type;
54061                 }
54062                 if (!targetType) {
54063                     var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
54064                     targetType = constructSignatures.length ?
54065                         getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
54066                         emptyObjectType;
54067                 }
54068                 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
54069             }
54070             function getNarrowedType(type, candidate, assumeTrue, isRelated) {
54071                 if (!assumeTrue) {
54072                     return filterType(type, function (t) { return !isRelated(t, candidate); });
54073                 }
54074                 // If the current type is a union type, remove all constituents that couldn't be instances of
54075                 // the candidate type. If one or more constituents remain, return a union of those.
54076                 if (type.flags & 1048576 /* Union */) {
54077                     var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
54078                     if (!(assignableType.flags & 131072 /* Never */)) {
54079                         return assignableType;
54080                     }
54081                 }
54082                 // If the candidate type is a subtype of the target type, narrow to the candidate type.
54083                 // Otherwise, if the target type is assignable to the candidate type, keep the target type.
54084                 // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
54085                 // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
54086                 // two types.
54087                 return isTypeSubtypeOf(candidate, type) ? candidate :
54088                     isTypeAssignableTo(type, candidate) ? type :
54089                         isTypeAssignableTo(candidate, type) ? candidate :
54090                             getIntersectionType([type, candidate]);
54091             }
54092             function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
54093                 if (hasMatchingArgument(callExpression, reference)) {
54094                     var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
54095                     var predicate = signature && getTypePredicateOfSignature(signature);
54096                     if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
54097                         return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
54098                     }
54099                 }
54100                 return type;
54101             }
54102             function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
54103                 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
54104                 if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
54105                     var predicateArgument = getTypePredicateArgument(predicate, callExpression);
54106                     if (predicateArgument) {
54107                         if (isMatchingReference(reference, predicateArgument)) {
54108                             return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
54109                         }
54110                         if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
54111                             !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
54112                             type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54113                         }
54114                         if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) {
54115                             return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); });
54116                         }
54117                     }
54118                 }
54119                 return type;
54120             }
54121             // Narrow the given type based on the given expression having the assumed boolean value. The returned type
54122             // will be a subtype or the same type as the argument.
54123             function narrowType(type, expr, assumeTrue) {
54124                 // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
54125                 if (ts.isExpressionOfOptionalChainRoot(expr) ||
54126                     ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
54127                     return narrowTypeByOptionality(type, expr, assumeTrue);
54128                 }
54129                 switch (expr.kind) {
54130                     case 75 /* Identifier */:
54131                     case 104 /* ThisKeyword */:
54132                     case 102 /* SuperKeyword */:
54133                     case 194 /* PropertyAccessExpression */:
54134                     case 195 /* ElementAccessExpression */:
54135                         return narrowTypeByTruthiness(type, expr, assumeTrue);
54136                     case 196 /* CallExpression */:
54137                         return narrowTypeByCallExpression(type, expr, assumeTrue);
54138                     case 200 /* ParenthesizedExpression */:
54139                         return narrowType(type, expr.expression, assumeTrue);
54140                     case 209 /* BinaryExpression */:
54141                         return narrowTypeByBinaryExpression(type, expr, assumeTrue);
54142                     case 207 /* PrefixUnaryExpression */:
54143                         if (expr.operator === 53 /* ExclamationToken */) {
54144                             return narrowType(type, expr.operand, !assumeTrue);
54145                         }
54146                         break;
54147                 }
54148                 return type;
54149             }
54150             function narrowTypeByOptionality(type, expr, assumePresent) {
54151                 if (isMatchingReference(reference, expr)) {
54152                     return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
54153                 }
54154                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
54155                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
54156                 }
54157                 return type;
54158             }
54159         }
54160         function getTypeOfSymbolAtLocation(symbol, location) {
54161             symbol = symbol.exportSymbol || symbol;
54162             // If we have an identifier or a property access at the given location, if the location is
54163             // an dotted name expression, and if the location is not an assignment target, obtain the type
54164             // of the expression (which will reflect control flow analysis). If the expression indeed
54165             // resolved to the given symbol, return the narrowed type.
54166             if (location.kind === 75 /* Identifier */) {
54167                 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
54168                     location = location.parent;
54169                 }
54170                 if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
54171                     var type = getTypeOfExpression(location);
54172                     if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
54173                         return type;
54174                     }
54175                 }
54176             }
54177             // The location isn't a reference to the given symbol, meaning we're being asked
54178             // a hypothetical question of what type the symbol would have if there was a reference
54179             // to it at the given location. Since we have no control flow information for the
54180             // hypothetical reference (control flow information is created and attached by the
54181             // binder), we simply return the declared type of the symbol.
54182             return getTypeOfSymbol(symbol);
54183         }
54184         function getControlFlowContainer(node) {
54185             return ts.findAncestor(node.parent, function (node) {
54186                 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
54187                     node.kind === 250 /* ModuleBlock */ ||
54188                     node.kind === 290 /* SourceFile */ ||
54189                     node.kind === 159 /* PropertyDeclaration */;
54190             });
54191         }
54192         // Check if a parameter is assigned anywhere within its declaring function.
54193         function isParameterAssigned(symbol) {
54194             var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
54195             var links = getNodeLinks(func);
54196             if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
54197                 links.flags |= 8388608 /* AssignmentsMarked */;
54198                 if (!hasParentWithAssignmentsMarked(func)) {
54199                     markParameterAssignments(func);
54200                 }
54201             }
54202             return symbol.isAssigned || false;
54203         }
54204         function hasParentWithAssignmentsMarked(node) {
54205             return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
54206         }
54207         function markParameterAssignments(node) {
54208             if (node.kind === 75 /* Identifier */) {
54209                 if (ts.isAssignmentTarget(node)) {
54210                     var symbol = getResolvedSymbol(node);
54211                     if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 156 /* Parameter */) {
54212                         symbol.isAssigned = true;
54213                     }
54214                 }
54215             }
54216             else {
54217                 ts.forEachChild(node, markParameterAssignments);
54218             }
54219         }
54220         function isConstVariable(symbol) {
54221             return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
54222         }
54223         /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
54224         function removeOptionalityFromDeclaredType(declaredType, declaration) {
54225             if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) {
54226                 var annotationIncludesUndefined = strictNullChecks &&
54227                     declaration.kind === 156 /* Parameter */ &&
54228                     declaration.initializer &&
54229                     getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
54230                     !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
54231                 popTypeResolution();
54232                 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
54233             }
54234             else {
54235                 reportCircularityError(declaration.symbol);
54236                 return declaredType;
54237             }
54238         }
54239         function isConstraintPosition(node) {
54240             var parent = node.parent;
54241             return parent.kind === 194 /* PropertyAccessExpression */ ||
54242                 parent.kind === 196 /* CallExpression */ && parent.expression === node ||
54243                 parent.kind === 195 /* ElementAccessExpression */ && parent.expression === node ||
54244                 parent.kind === 191 /* BindingElement */ && parent.name === node && !!parent.initializer;
54245         }
54246         function typeHasNullableConstraint(type) {
54247             return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */);
54248         }
54249         function getConstraintForLocation(type, node) {
54250             // When a node is the left hand expression of a property access, element access, or call expression,
54251             // and the type of the node includes type variables with constraints that are nullable, we fetch the
54252             // apparent type of the node *before* performing control flow analysis such that narrowings apply to
54253             // the constraint type.
54254             if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
54255                 return mapType(getWidenedType(type), getBaseConstraintOrType);
54256             }
54257             return type;
54258         }
54259         function isExportOrExportExpression(location) {
54260             return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); });
54261         }
54262         function markAliasReferenced(symbol, location) {
54263             if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
54264                 if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
54265                     markAliasSymbolAsReferenced(symbol);
54266                 }
54267                 else {
54268                     markConstEnumAliasAsReferenced(symbol);
54269                 }
54270             }
54271         }
54272         function checkIdentifier(node) {
54273             var symbol = getResolvedSymbol(node);
54274             if (symbol === unknownSymbol) {
54275                 return errorType;
54276             }
54277             // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
54278             // Although in down-level emit of arrow function, we emit it using function expression which means that
54279             // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
54280             // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
54281             // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
54282             // can explicitly bound arguments objects
54283             if (symbol === argumentsSymbol) {
54284                 var container = ts.getContainingFunction(node);
54285                 if (languageVersion < 2 /* ES2015 */) {
54286                     if (container.kind === 202 /* ArrowFunction */) {
54287                         error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
54288                     }
54289                     else if (ts.hasModifier(container, 256 /* Async */)) {
54290                         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);
54291                     }
54292                 }
54293                 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
54294                 return getTypeOfSymbol(symbol);
54295             }
54296             // We should only mark aliases as referenced if there isn't a local value declaration
54297             // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
54298             if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
54299                 markAliasReferenced(symbol, node);
54300             }
54301             var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
54302             var declaration = localOrExportSymbol.valueDeclaration;
54303             if (localOrExportSymbol.flags & 32 /* Class */) {
54304                 // Due to the emit for class decorators, any reference to the class from inside of the class body
54305                 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
54306                 // behavior of class names in ES6.
54307                 if (declaration.kind === 245 /* ClassDeclaration */
54308                     && ts.nodeIsDecorated(declaration)) {
54309                     var container = ts.getContainingClass(node);
54310                     while (container !== undefined) {
54311                         if (container === declaration && container.name !== node) {
54312                             getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54313                             getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54314                             break;
54315                         }
54316                         container = ts.getContainingClass(container);
54317                     }
54318                 }
54319                 else if (declaration.kind === 214 /* ClassExpression */) {
54320                     // When we emit a class expression with static members that contain a reference
54321                     // to the constructor in the initializer, we will need to substitute that
54322                     // binding with an alias as the class name is not in scope.
54323                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54324                     while (container.kind !== 290 /* SourceFile */) {
54325                         if (container.parent === declaration) {
54326                             if (container.kind === 159 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
54327                                 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54328                                 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54329                             }
54330                             break;
54331                         }
54332                         container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
54333                     }
54334                 }
54335             }
54336             checkNestedBlockScopedBinding(node, symbol);
54337             var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
54338             var assignmentKind = ts.getAssignmentTargetKind(node);
54339             if (assignmentKind) {
54340                 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
54341                     !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
54342                     error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
54343                     return errorType;
54344                 }
54345                 if (isReadonlySymbol(localOrExportSymbol)) {
54346                     if (localOrExportSymbol.flags & 3 /* Variable */) {
54347                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
54348                     }
54349                     else {
54350                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
54351                     }
54352                     return errorType;
54353                 }
54354             }
54355             var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
54356             // We only narrow variables and parameters occurring in a non-assignment position. For all other
54357             // entities we simply return the declared type.
54358             if (localOrExportSymbol.flags & 3 /* Variable */) {
54359                 if (assignmentKind === 1 /* Definite */) {
54360                     return type;
54361                 }
54362             }
54363             else if (isAlias) {
54364                 declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
54365             }
54366             else {
54367                 return type;
54368             }
54369             if (!declaration) {
54370                 return type;
54371             }
54372             // The declaration container is the innermost function that encloses the declaration of the variable
54373             // or parameter. The flow container is the innermost function starting with which we analyze the control
54374             // flow graph to determine the control flow based type.
54375             var isParameter = ts.getRootDeclaration(declaration).kind === 156 /* Parameter */;
54376             var declarationContainer = getControlFlowContainer(declaration);
54377             var flowContainer = getControlFlowContainer(node);
54378             var isOuterVariable = flowContainer !== declarationContainer;
54379             var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
54380             var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
54381             // When the control flow originates in a function expression or arrow function and we are referencing
54382             // a const variable or parameter from an outer function, we extend the origin of the control flow
54383             // analysis to include the immediately enclosing function.
54384             while (flowContainer !== declarationContainer && (flowContainer.kind === 201 /* FunctionExpression */ ||
54385                 flowContainer.kind === 202 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
54386                 (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
54387                 flowContainer = getControlFlowContainer(flowContainer);
54388             }
54389             // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
54390             // the entire control flow graph from the variable's declaration (i.e. when the flow container and
54391             // declaration container are the same).
54392             var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
54393                 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
54394                     isInTypeQuery(node) || node.parent.kind === 263 /* ExportSpecifier */) ||
54395                 node.parent.kind === 218 /* NonNullExpression */ ||
54396                 declaration.kind === 242 /* VariableDeclaration */ && declaration.exclamationToken ||
54397                 declaration.flags & 8388608 /* Ambient */;
54398             var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
54399                 type === autoType || type === autoArrayType ? undefinedType :
54400                     getOptionalType(type);
54401             var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
54402             // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
54403             // from declaration to use, and when the variable's declared type doesn't include undefined but the
54404             // control flow based type does include undefined.
54405             if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
54406                 if (flowType === autoType || flowType === autoArrayType) {
54407                     if (noImplicitAny) {
54408                         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));
54409                         error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
54410                     }
54411                     return convertAutoToAny(flowType);
54412                 }
54413             }
54414             else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
54415                 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
54416                 // Return the declared type to reduce follow-on errors
54417                 return type;
54418             }
54419             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
54420         }
54421         function isInsideFunction(node, threshold) {
54422             return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
54423         }
54424         function getPartOfForStatementContainingNode(node, container) {
54425             return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
54426         }
54427         function checkNestedBlockScopedBinding(node, symbol) {
54428             if (languageVersion >= 2 /* ES2015 */ ||
54429                 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
54430                 ts.isSourceFile(symbol.valueDeclaration) ||
54431                 symbol.valueDeclaration.parent.kind === 280 /* CatchClause */) {
54432                 return;
54433             }
54434             // 1. walk from the use site up to the declaration and check
54435             // if there is anything function like between declaration and use-site (is binding/class is captured in function).
54436             // 2. walk from the declaration up to the boundary of lexical environment and check
54437             // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
54438             var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
54439             var usedInFunction = isInsideFunction(node.parent, container);
54440             var current = container;
54441             var containedInIterationStatement = false;
54442             while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
54443                 if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
54444                     containedInIterationStatement = true;
54445                     break;
54446                 }
54447                 current = current.parent;
54448             }
54449             if (containedInIterationStatement) {
54450                 if (usedInFunction) {
54451                     // mark iteration statement as containing block-scoped binding captured in some function
54452                     var capturesBlockScopeBindingInLoopBody = true;
54453                     if (ts.isForStatement(container)) {
54454                         var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54455                         if (varDeclList && varDeclList.parent === container) {
54456                             var part = getPartOfForStatementContainingNode(node.parent, container);
54457                             if (part) {
54458                                 var links = getNodeLinks(part);
54459                                 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
54460                                 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
54461                                 ts.pushIfUnique(capturedBindings, symbol);
54462                                 if (part === container.initializer) {
54463                                     capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
54464                                 }
54465                             }
54466                         }
54467                     }
54468                     if (capturesBlockScopeBindingInLoopBody) {
54469                         getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
54470                     }
54471                 }
54472                 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
54473                 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
54474                 if (ts.isForStatement(container)) {
54475                     var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54476                     if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
54477                         getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
54478                     }
54479                 }
54480                 // set 'declared inside loop' bit on the block-scoped binding
54481                 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
54482             }
54483             if (usedInFunction) {
54484                 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
54485             }
54486         }
54487         function isBindingCapturedByNode(node, decl) {
54488             var links = getNodeLinks(node);
54489             return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
54490         }
54491         function isAssignedInBodyOfForStatement(node, container) {
54492             // skip parenthesized nodes
54493             var current = node;
54494             while (current.parent.kind === 200 /* ParenthesizedExpression */) {
54495                 current = current.parent;
54496             }
54497             // check if node is used as LHS in some assignment expression
54498             var isAssigned = false;
54499             if (ts.isAssignmentTarget(current)) {
54500                 isAssigned = true;
54501             }
54502             else if ((current.parent.kind === 207 /* PrefixUnaryExpression */ || current.parent.kind === 208 /* PostfixUnaryExpression */)) {
54503                 var expr = current.parent;
54504                 isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
54505             }
54506             if (!isAssigned) {
54507                 return false;
54508             }
54509             // at this point we know that node is the target of assignment
54510             // now check that modification happens inside the statement part of the ForStatement
54511             return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
54512         }
54513         function captureLexicalThis(node, container) {
54514             getNodeLinks(node).flags |= 2 /* LexicalThis */;
54515             if (container.kind === 159 /* PropertyDeclaration */ || container.kind === 162 /* Constructor */) {
54516                 var classNode = container.parent;
54517                 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
54518             }
54519             else {
54520                 getNodeLinks(container).flags |= 4 /* CaptureThis */;
54521             }
54522         }
54523         function findFirstSuperCall(n) {
54524             if (ts.isSuperCall(n)) {
54525                 return n;
54526             }
54527             else if (ts.isFunctionLike(n)) {
54528                 return undefined;
54529             }
54530             return ts.forEachChild(n, findFirstSuperCall);
54531         }
54532         /**
54533          * Return a cached result if super-statement is already found.
54534          * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor
54535          *
54536          * @param constructor constructor-function to look for super statement
54537          */
54538         function getSuperCallInConstructor(constructor) {
54539             var links = getNodeLinks(constructor);
54540             // Only trying to find super-call if we haven't yet tried to find one.  Once we try, we will record the result
54541             if (links.hasSuperCall === undefined) {
54542                 links.superCall = findFirstSuperCall(constructor.body);
54543                 links.hasSuperCall = links.superCall ? true : false;
54544             }
54545             return links.superCall;
54546         }
54547         /**
54548          * Check if the given class-declaration extends null then return true.
54549          * Otherwise, return false
54550          * @param classDecl a class declaration to check if it extends null
54551          */
54552         function classDeclarationExtendsNull(classDecl) {
54553             var classSymbol = getSymbolOfNode(classDecl);
54554             var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
54555             var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
54556             return baseConstructorType === nullWideningType;
54557         }
54558         function checkThisBeforeSuper(node, container, diagnosticMessage) {
54559             var containingClassDecl = container.parent;
54560             var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
54561             // If a containing class does not have extends clause or the class extends null
54562             // skip checking whether super statement is called before "this" accessing.
54563             if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
54564                 var superCall = getSuperCallInConstructor(container);
54565                 // We should give an error in the following cases:
54566                 //      - No super-call
54567                 //      - "this" is accessing before super-call.
54568                 //          i.e super(this)
54569                 //              this.x; super();
54570                 // We want to make sure that super-call is done before accessing "this" so that
54571                 // "this" is not accessed as a parameter of the super-call.
54572                 if (!superCall || superCall.end > node.pos) {
54573                     // In ES6, super inside constructor of class-declaration has to precede "this" accessing
54574                     error(node, diagnosticMessage);
54575                 }
54576             }
54577         }
54578         function checkThisExpression(node) {
54579             // Stop at the first arrow function so that we can
54580             // tell whether 'this' needs to be captured.
54581             var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
54582             var capturedByArrowFunction = false;
54583             if (container.kind === 162 /* Constructor */) {
54584                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
54585             }
54586             // Now skip arrow functions to get the "real" owner of 'this'.
54587             if (container.kind === 202 /* ArrowFunction */) {
54588                 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
54589                 capturedByArrowFunction = true;
54590             }
54591             switch (container.kind) {
54592                 case 249 /* ModuleDeclaration */:
54593                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
54594                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54595                     break;
54596                 case 248 /* EnumDeclaration */:
54597                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
54598                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54599                     break;
54600                 case 162 /* Constructor */:
54601                     if (isInConstructorArgumentInitializer(node, container)) {
54602                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
54603                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54604                     }
54605                     break;
54606                 case 159 /* PropertyDeclaration */:
54607                 case 158 /* PropertySignature */:
54608                     if (ts.hasModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
54609                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
54610                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54611                     }
54612                     break;
54613                 case 154 /* ComputedPropertyName */:
54614                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
54615                     break;
54616             }
54617             // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
54618             if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
54619                 captureLexicalThis(node, container);
54620             }
54621             var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
54622             if (noImplicitThis) {
54623                 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
54624                 if (type === globalThisType_1 && capturedByArrowFunction) {
54625                     error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
54626                 }
54627                 else if (!type) {
54628                     // With noImplicitThis, functions may not reference 'this' if it has type 'any'
54629                     var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
54630                     if (!ts.isSourceFile(container)) {
54631                         var outsideThis = tryGetThisTypeAt(container);
54632                         if (outsideThis && outsideThis !== globalThisType_1) {
54633                             ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
54634                         }
54635                     }
54636                 }
54637             }
54638             return type || anyType;
54639         }
54640         function tryGetThisTypeAt(node, includeGlobalThis, container) {
54641             if (includeGlobalThis === void 0) { includeGlobalThis = true; }
54642             if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
54643             var isInJS = ts.isInJSFile(node);
54644             if (ts.isFunctionLike(container) &&
54645                 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
54646                 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
54647                 // If this is a function in a JS file, it might be a class method.
54648                 var className = getClassNameFromPrototypeMethod(container);
54649                 if (isInJS && className) {
54650                     var classSymbol = checkExpression(className).symbol;
54651                     if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
54652                         var classType = getDeclaredTypeOfSymbol(classSymbol).thisType;
54653                         if (classType) {
54654                             return getFlowTypeOfReference(node, classType);
54655                         }
54656                     }
54657                 }
54658                 // Check if it's a constructor definition, can be either a variable decl or function decl
54659                 // i.e.
54660                 //   * /** @constructor */ function [name]() { ... }
54661                 //   * /** @constructor */ var x = function() { ... }
54662                 else if (isInJS &&
54663                     (container.kind === 201 /* FunctionExpression */ || container.kind === 244 /* FunctionDeclaration */) &&
54664                     ts.getJSDocClassTag(container)) {
54665                     var classType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
54666                     return getFlowTypeOfReference(node, classType);
54667                 }
54668                 var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container);
54669                 if (thisType) {
54670                     return getFlowTypeOfReference(node, thisType);
54671                 }
54672             }
54673             if (ts.isClassLike(container.parent)) {
54674                 var symbol = getSymbolOfNode(container.parent);
54675                 var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54676                 return getFlowTypeOfReference(node, type);
54677             }
54678             if (isInJS) {
54679                 var type = getTypeForThisExpressionFromJSDoc(container);
54680                 if (type && type !== errorType) {
54681                     return getFlowTypeOfReference(node, type);
54682                 }
54683             }
54684             if (ts.isSourceFile(container)) {
54685                 // look up in the source file's locals or exports
54686                 if (container.commonJsModuleIndicator) {
54687                     var fileSymbol = getSymbolOfNode(container);
54688                     return fileSymbol && getTypeOfSymbol(fileSymbol);
54689                 }
54690                 else if (includeGlobalThis) {
54691                     return getTypeOfSymbol(globalThisSymbol);
54692                 }
54693             }
54694         }
54695         function getExplicitThisType(node) {
54696             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54697             if (ts.isFunctionLike(container)) {
54698                 var signature = getSignatureFromDeclaration(container);
54699                 if (signature.thisParameter) {
54700                     return getExplicitTypeOfSymbol(signature.thisParameter);
54701                 }
54702             }
54703             if (ts.isClassLike(container.parent)) {
54704                 var symbol = getSymbolOfNode(container.parent);
54705                 return ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54706             }
54707         }
54708         function getClassNameFromPrototypeMethod(container) {
54709             // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
54710             if (container.kind === 201 /* FunctionExpression */ &&
54711                 ts.isBinaryExpression(container.parent) &&
54712                 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
54713                 // Get the 'x' of 'x.prototype.y = container'
54714                 return container.parent // x.prototype.y = container
54715                     .left // x.prototype.y
54716                     .expression // x.prototype
54717                     .expression; // x
54718             }
54719             // x.prototype = { method() { } }
54720             else if (container.kind === 161 /* MethodDeclaration */ &&
54721                 container.parent.kind === 193 /* ObjectLiteralExpression */ &&
54722                 ts.isBinaryExpression(container.parent.parent) &&
54723                 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
54724                 return container.parent.parent.left.expression;
54725             }
54726             // x.prototype = { method: function() { } }
54727             else if (container.kind === 201 /* FunctionExpression */ &&
54728                 container.parent.kind === 281 /* PropertyAssignment */ &&
54729                 container.parent.parent.kind === 193 /* ObjectLiteralExpression */ &&
54730                 ts.isBinaryExpression(container.parent.parent.parent) &&
54731                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
54732                 return container.parent.parent.parent.left.expression;
54733             }
54734             // Object.defineProperty(x, "method", { value: function() { } });
54735             // Object.defineProperty(x, "method", { set: (x: () => void) => void });
54736             // Object.defineProperty(x, "method", { get: () => function() { }) });
54737             else if (container.kind === 201 /* FunctionExpression */ &&
54738                 ts.isPropertyAssignment(container.parent) &&
54739                 ts.isIdentifier(container.parent.name) &&
54740                 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
54741                 ts.isObjectLiteralExpression(container.parent.parent) &&
54742                 ts.isCallExpression(container.parent.parent.parent) &&
54743                 container.parent.parent.parent.arguments[2] === container.parent.parent &&
54744                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54745                 return container.parent.parent.parent.arguments[0].expression;
54746             }
54747             // Object.defineProperty(x, "method", { value() { } });
54748             // Object.defineProperty(x, "method", { set(x: () => void) {} });
54749             // Object.defineProperty(x, "method", { get() { return () => {} } });
54750             else if (ts.isMethodDeclaration(container) &&
54751                 ts.isIdentifier(container.name) &&
54752                 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
54753                 ts.isObjectLiteralExpression(container.parent) &&
54754                 ts.isCallExpression(container.parent.parent) &&
54755                 container.parent.parent.arguments[2] === container.parent &&
54756                 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54757                 return container.parent.parent.arguments[0].expression;
54758             }
54759         }
54760         function getTypeForThisExpressionFromJSDoc(node) {
54761             var jsdocType = ts.getJSDocType(node);
54762             if (jsdocType && jsdocType.kind === 300 /* JSDocFunctionType */) {
54763                 var jsDocFunctionType = jsdocType;
54764                 if (jsDocFunctionType.parameters.length > 0 &&
54765                     jsDocFunctionType.parameters[0].name &&
54766                     jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
54767                     return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
54768                 }
54769             }
54770             var thisTag = ts.getJSDocThisTag(node);
54771             if (thisTag && thisTag.typeExpression) {
54772                 return getTypeFromTypeNode(thisTag.typeExpression);
54773             }
54774         }
54775         function isInConstructorArgumentInitializer(node, constructorDecl) {
54776             return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 156 /* Parameter */ && n.parent === constructorDecl; });
54777         }
54778         function checkSuperExpression(node) {
54779             var isCallExpression = node.parent.kind === 196 /* CallExpression */ && node.parent.expression === node;
54780             var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
54781             var needToCaptureLexicalThis = false;
54782             // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
54783             if (!isCallExpression) {
54784                 while (container && container.kind === 202 /* ArrowFunction */) {
54785                     container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
54786                     needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
54787                 }
54788             }
54789             var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
54790             var nodeCheckFlag = 0;
54791             if (!canUseSuperExpression) {
54792                 // issue more specific error if super is used in computed property name
54793                 // class A { foo() { return "1" }}
54794                 // class B {
54795                 //     [super.foo()]() {}
54796                 // }
54797                 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 154 /* ComputedPropertyName */; });
54798                 if (current && current.kind === 154 /* ComputedPropertyName */) {
54799                     error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
54800                 }
54801                 else if (isCallExpression) {
54802                     error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
54803                 }
54804                 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */)) {
54805                     error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
54806                 }
54807                 else {
54808                     error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
54809                 }
54810                 return errorType;
54811             }
54812             if (!isCallExpression && container.kind === 162 /* Constructor */) {
54813                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
54814             }
54815             if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) {
54816                 nodeCheckFlag = 512 /* SuperStatic */;
54817             }
54818             else {
54819                 nodeCheckFlag = 256 /* SuperInstance */;
54820             }
54821             getNodeLinks(node).flags |= nodeCheckFlag;
54822             // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
54823             // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
54824             // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
54825             // uses an arrow function, which is permitted to reference `super`.
54826             //
54827             // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
54828             // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
54829             // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
54830             //
54831             // The simplest case is reading a value, in which case we will emit something like the following:
54832             //
54833             //  // ts
54834             //  ...
54835             //  async asyncMethod() {
54836             //    let x = await super.asyncMethod();
54837             //    return x;
54838             //  }
54839             //  ...
54840             //
54841             //  // js
54842             //  ...
54843             //  asyncMethod() {
54844             //      const _super = Object.create(null, {
54845             //        asyncMethod: { get: () => super.asyncMethod },
54846             //      });
54847             //      return __awaiter(this, arguments, Promise, function *() {
54848             //          let x = yield _super.asyncMethod.call(this);
54849             //          return x;
54850             //      });
54851             //  }
54852             //  ...
54853             //
54854             // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
54855             // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
54856             //
54857             //  // ts
54858             //  ...
54859             //  async asyncMethod(ar: Promise<any[]>) {
54860             //      [super.a, super.b] = await ar;
54861             //  }
54862             //  ...
54863             //
54864             //  // js
54865             //  ...
54866             //  asyncMethod(ar) {
54867             //      const _super = Object.create(null, {
54868             //        a: { get: () => super.a, set: (v) => super.a = v },
54869             //        b: { get: () => super.b, set: (v) => super.b = v }
54870             //      };
54871             //      return __awaiter(this, arguments, Promise, function *() {
54872             //          [_super.a, _super.b] = yield ar;
54873             //      });
54874             //  }
54875             //  ...
54876             //
54877             // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
54878             // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
54879             //
54880             // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
54881             if (container.kind === 161 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) {
54882                 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
54883                     getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
54884                 }
54885                 else {
54886                     getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
54887                 }
54888             }
54889             if (needToCaptureLexicalThis) {
54890                 // call expressions are allowed only in constructors so they should always capture correct 'this'
54891                 // super property access expressions can also appear in arrow functions -
54892                 // in this case they should also use correct lexical this
54893                 captureLexicalThis(node.parent, container);
54894             }
54895             if (container.parent.kind === 193 /* ObjectLiteralExpression */) {
54896                 if (languageVersion < 2 /* ES2015 */) {
54897                     error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
54898                     return errorType;
54899                 }
54900                 else {
54901                     // for object literal assume that type of 'super' is 'any'
54902                     return anyType;
54903                 }
54904             }
54905             // at this point the only legal case for parent is ClassLikeDeclaration
54906             var classLikeDeclaration = container.parent;
54907             if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
54908                 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
54909                 return errorType;
54910             }
54911             var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
54912             var baseClassType = classType && getBaseTypes(classType)[0];
54913             if (!baseClassType) {
54914                 return errorType;
54915             }
54916             if (container.kind === 162 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
54917                 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
54918                 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
54919                 return errorType;
54920             }
54921             return nodeCheckFlag === 512 /* SuperStatic */
54922                 ? getBaseConstructorTypeOfClass(classType)
54923                 : getTypeWithThisArgument(baseClassType, classType.thisType);
54924             function isLegalUsageOfSuperExpression(container) {
54925                 if (!container) {
54926                     return false;
54927                 }
54928                 if (isCallExpression) {
54929                     // TS 1.0 SPEC (April 2014): 4.8.1
54930                     // Super calls are only permitted in constructors of derived classes
54931                     return container.kind === 162 /* Constructor */;
54932                 }
54933                 else {
54934                     // TS 1.0 SPEC (April 2014)
54935                     // 'super' property access is allowed
54936                     // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
54937                     // - In a static member function or static member accessor
54938                     // topmost container must be something that is directly nested in the class declaration\object literal expression
54939                     if (ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */) {
54940                         if (ts.hasModifier(container, 32 /* Static */)) {
54941                             return container.kind === 161 /* MethodDeclaration */ ||
54942                                 container.kind === 160 /* MethodSignature */ ||
54943                                 container.kind === 163 /* GetAccessor */ ||
54944                                 container.kind === 164 /* SetAccessor */;
54945                         }
54946                         else {
54947                             return container.kind === 161 /* MethodDeclaration */ ||
54948                                 container.kind === 160 /* MethodSignature */ ||
54949                                 container.kind === 163 /* GetAccessor */ ||
54950                                 container.kind === 164 /* SetAccessor */ ||
54951                                 container.kind === 159 /* PropertyDeclaration */ ||
54952                                 container.kind === 158 /* PropertySignature */ ||
54953                                 container.kind === 162 /* Constructor */;
54954                         }
54955                     }
54956                 }
54957                 return false;
54958             }
54959         }
54960         function getContainingObjectLiteral(func) {
54961             return (func.kind === 161 /* MethodDeclaration */ ||
54962                 func.kind === 163 /* GetAccessor */ ||
54963                 func.kind === 164 /* SetAccessor */) && func.parent.kind === 193 /* ObjectLiteralExpression */ ? func.parent :
54964                 func.kind === 201 /* FunctionExpression */ && func.parent.kind === 281 /* PropertyAssignment */ ? func.parent.parent :
54965                     undefined;
54966         }
54967         function getThisTypeArgument(type) {
54968             return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
54969         }
54970         function getThisTypeFromContextualType(type) {
54971             return mapType(type, function (t) {
54972                 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
54973             });
54974         }
54975         function getContextualThisParameterType(func) {
54976             if (func.kind === 202 /* ArrowFunction */) {
54977                 return undefined;
54978             }
54979             if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
54980                 var contextualSignature = getContextualSignature(func);
54981                 if (contextualSignature) {
54982                     var thisParameter = contextualSignature.thisParameter;
54983                     if (thisParameter) {
54984                         return getTypeOfSymbol(thisParameter);
54985                     }
54986                 }
54987             }
54988             var inJs = ts.isInJSFile(func);
54989             if (noImplicitThis || inJs) {
54990                 var containingLiteral = getContainingObjectLiteral(func);
54991                 if (containingLiteral) {
54992                     // We have an object literal method. Check if the containing object literal has a contextual type
54993                     // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
54994                     // any directly enclosing object literals.
54995                     var contextualType = getApparentTypeOfContextualType(containingLiteral);
54996                     var literal = containingLiteral;
54997                     var type = contextualType;
54998                     while (type) {
54999                         var thisType = getThisTypeFromContextualType(type);
55000                         if (thisType) {
55001                             return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
55002                         }
55003                         if (literal.parent.kind !== 281 /* PropertyAssignment */) {
55004                             break;
55005                         }
55006                         literal = literal.parent.parent;
55007                         type = getApparentTypeOfContextualType(literal);
55008                     }
55009                     // There was no contextual ThisType<T> for the containing object literal, so the contextual type
55010                     // for 'this' is the non-null form of the contextual type for the containing object literal or
55011                     // the type of the object literal itself.
55012                     return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
55013                 }
55014                 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
55015                 // contextual type for 'this' is 'obj'.
55016                 var parent = ts.walkUpParenthesizedExpressions(func.parent);
55017                 if (parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) {
55018                     var target = parent.left;
55019                     if (ts.isAccessExpression(target)) {
55020                         var expression = target.expression;
55021                         // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
55022                         if (inJs && ts.isIdentifier(expression)) {
55023                             var sourceFile = ts.getSourceFileOfNode(parent);
55024                             if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
55025                                 return undefined;
55026                             }
55027                         }
55028                         return getWidenedType(checkExpressionCached(expression));
55029                     }
55030                 }
55031             }
55032             return undefined;
55033         }
55034         // Return contextual type of parameter or undefined if no contextual type is available
55035         function getContextuallyTypedParameterType(parameter) {
55036             var func = parameter.parent;
55037             if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
55038                 return undefined;
55039             }
55040             var iife = ts.getImmediatelyInvokedFunctionExpression(func);
55041             if (iife && iife.arguments) {
55042                 var args = getEffectiveCallArguments(iife);
55043                 var indexOfParameter = func.parameters.indexOf(parameter);
55044                 if (parameter.dotDotDotToken) {
55045                     return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined);
55046                 }
55047                 var links = getNodeLinks(iife);
55048                 var cached = links.resolvedSignature;
55049                 links.resolvedSignature = anySignature;
55050                 var type = indexOfParameter < args.length ?
55051                     getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
55052                     parameter.initializer ? undefined : undefinedWideningType;
55053                 links.resolvedSignature = cached;
55054                 return type;
55055             }
55056             var contextualSignature = getContextualSignature(func);
55057             if (contextualSignature) {
55058                 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
55059                 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
55060                     getRestTypeAtPosition(contextualSignature, index) :
55061                     tryGetTypeAtPosition(contextualSignature, index);
55062             }
55063         }
55064         function getContextualTypeForVariableLikeDeclaration(declaration) {
55065             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
55066             if (typeNode) {
55067                 return getTypeFromTypeNode(typeNode);
55068             }
55069             switch (declaration.kind) {
55070                 case 156 /* Parameter */:
55071                     return getContextuallyTypedParameterType(declaration);
55072                 case 191 /* BindingElement */:
55073                     return getContextualTypeForBindingElement(declaration);
55074                 // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent
55075             }
55076         }
55077         function getContextualTypeForBindingElement(declaration) {
55078             var parent = declaration.parent.parent;
55079             var name = declaration.propertyName || declaration.name;
55080             var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
55081                 parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
55082             if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) {
55083                 var nameType = getLiteralTypeFromPropertyName(name);
55084                 if (isTypeUsableAsPropertyName(nameType)) {
55085                     var text = getPropertyNameFromType(nameType);
55086                     return getTypeOfPropertyOfType(parentType, text);
55087                 }
55088             }
55089         }
55090         // In a variable, parameter or property declaration with a type annotation,
55091         //   the contextual type of an initializer expression is the type of the variable, parameter or property.
55092         // Otherwise, in a parameter declaration of a contextually typed function expression,
55093         //   the contextual type of an initializer expression is the contextual type of the parameter.
55094         // Otherwise, in a variable or parameter declaration with a binding pattern name,
55095         //   the contextual type of an initializer expression is the type implied by the binding pattern.
55096         // Otherwise, in a binding pattern inside a variable or parameter declaration,
55097         //   the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
55098         function getContextualTypeForInitializerExpression(node) {
55099             var declaration = node.parent;
55100             if (ts.hasInitializer(declaration) && node === declaration.initializer) {
55101                 var result = getContextualTypeForVariableLikeDeclaration(declaration);
55102                 if (result) {
55103                     return result;
55104                 }
55105                 if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable
55106                     return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
55107                 }
55108             }
55109             return undefined;
55110         }
55111         function getContextualTypeForReturnExpression(node) {
55112             var func = ts.getContainingFunction(node);
55113             if (func) {
55114                 var functionFlags = ts.getFunctionFlags(func);
55115                 if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
55116                     return undefined;
55117                 }
55118                 var contextualReturnType = getContextualReturnType(func);
55119                 if (contextualReturnType) {
55120                     if (functionFlags & 2 /* Async */) { // Async function
55121                         var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise);
55122                         return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55123                     }
55124                     return contextualReturnType; // Regular function
55125                 }
55126             }
55127             return undefined;
55128         }
55129         function getContextualTypeForAwaitOperand(node) {
55130             var contextualType = getContextualType(node);
55131             if (contextualType) {
55132                 var contextualAwaitedType = getAwaitedType(contextualType);
55133                 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55134             }
55135             return undefined;
55136         }
55137         function getContextualTypeForYieldOperand(node) {
55138             var func = ts.getContainingFunction(node);
55139             if (func) {
55140                 var functionFlags = ts.getFunctionFlags(func);
55141                 var contextualReturnType = getContextualReturnType(func);
55142                 if (contextualReturnType) {
55143                     return node.asteriskToken
55144                         ? contextualReturnType
55145                         : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
55146                 }
55147             }
55148             return undefined;
55149         }
55150         function isInParameterInitializerBeforeContainingFunction(node) {
55151             var inBindingInitializer = false;
55152             while (node.parent && !ts.isFunctionLike(node.parent)) {
55153                 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
55154                     return true;
55155                 }
55156                 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
55157                     inBindingInitializer = true;
55158                 }
55159                 node = node.parent;
55160             }
55161             return false;
55162         }
55163         function getContextualIterationType(kind, functionDecl) {
55164             var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
55165             var contextualReturnType = getContextualReturnType(functionDecl);
55166             if (contextualReturnType) {
55167                 return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
55168                     || undefined;
55169             }
55170             return undefined;
55171         }
55172         function getContextualReturnType(functionDecl) {
55173             // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
55174             // corresponding set accessor has a type annotation, return statements in the function are contextually typed
55175             var returnType = getReturnTypeFromAnnotation(functionDecl);
55176             if (returnType) {
55177                 return returnType;
55178             }
55179             // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
55180             // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
55181             var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
55182             if (signature && !isResolvingReturnTypeOfSignature(signature)) {
55183                 return getReturnTypeOfSignature(signature);
55184             }
55185             return undefined;
55186         }
55187         // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
55188         function getContextualTypeForArgument(callTarget, arg) {
55189             var args = getEffectiveCallArguments(callTarget);
55190             var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
55191             return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
55192         }
55193         function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
55194             // If we're already in the process of resolving the given signature, don't resolve again as
55195             // that could cause infinite recursion. Instead, return anySignature.
55196             var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
55197             if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
55198                 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
55199             }
55200             return getTypeAtPosition(signature, argIndex);
55201         }
55202         function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
55203             if (template.parent.kind === 198 /* TaggedTemplateExpression */) {
55204                 return getContextualTypeForArgument(template.parent, substitutionExpression);
55205             }
55206             return undefined;
55207         }
55208         function getContextualTypeForBinaryOperand(node, contextFlags) {
55209             var binaryExpression = node.parent;
55210             var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
55211             switch (operatorToken.kind) {
55212                 case 62 /* EqualsToken */:
55213                     if (node !== right) {
55214                         return undefined;
55215                     }
55216                     var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression);
55217                     if (!contextSensitive) {
55218                         return undefined;
55219                     }
55220                     return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive;
55221                 case 56 /* BarBarToken */:
55222                 case 60 /* QuestionQuestionToken */:
55223                     // When an || expression has a contextual type, the operands are contextually typed by that type, except
55224                     // when that type originates in a binding pattern, the right operand is contextually typed by the type of
55225                     // the left operand. When an || expression has no contextual type, the right operand is contextually typed
55226                     // by the type of the left operand, except for the special case of Javascript declarations of the form
55227                     // `namespace.prop = namespace.prop || {}`.
55228                     var type = getContextualType(binaryExpression, contextFlags);
55229                     return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
55230                         getTypeOfExpression(left) : type;
55231                 case 55 /* AmpersandAmpersandToken */:
55232                 case 27 /* CommaToken */:
55233                     return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
55234                 default:
55235                     return undefined;
55236             }
55237         }
55238         // In an assignment expression, the right operand is contextually typed by the type of the left operand.
55239         // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
55240         function getIsContextSensitiveAssignmentOrContextType(binaryExpression) {
55241             var kind = ts.getAssignmentDeclarationKind(binaryExpression);
55242             switch (kind) {
55243                 case 0 /* None */:
55244                     return true;
55245                 case 5 /* Property */:
55246                 case 1 /* ExportsProperty */:
55247                 case 6 /* Prototype */:
55248                 case 3 /* PrototypeProperty */:
55249                     // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
55250                     // See `bindStaticPropertyAssignment` in `binder.ts`.
55251                     if (!binaryExpression.left.symbol) {
55252                         return true;
55253                     }
55254                     else {
55255                         var decl = binaryExpression.left.symbol.valueDeclaration;
55256                         if (!decl) {
55257                             return false;
55258                         }
55259                         var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
55260                         var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
55261                         if (overallAnnotation) {
55262                             return getTypeFromTypeNode(overallAnnotation);
55263                         }
55264                         else if (ts.isIdentifier(lhs.expression)) {
55265                             var id = lhs.expression;
55266                             var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
55267                             if (parentSymbol) {
55268                                 var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
55269                                 if (annotated) {
55270                                     var nameStr_1 = ts.getElementOrPropertyAccessName(lhs);
55271                                     if (nameStr_1 !== undefined) {
55272                                         var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr_1);
55273                                         return type || false;
55274                                     }
55275                                 }
55276                                 return false;
55277                             }
55278                         }
55279                         return !ts.isInJSFile(decl);
55280                     }
55281                 case 2 /* ModuleExports */:
55282                 case 4 /* ThisProperty */:
55283                     if (!binaryExpression.symbol)
55284                         return true;
55285                     if (binaryExpression.symbol.valueDeclaration) {
55286                         var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
55287                         if (annotated) {
55288                             var type = getTypeFromTypeNode(annotated);
55289                             if (type) {
55290                                 return type;
55291                             }
55292                         }
55293                     }
55294                     if (kind === 2 /* ModuleExports */)
55295                         return false;
55296                     var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
55297                     if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
55298                         return false;
55299                     }
55300                     var thisType = checkThisExpression(thisAccess.expression);
55301                     var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
55302                     return nameStr !== undefined && thisType && getTypeOfPropertyOfContextualType(thisType, nameStr) || false;
55303                 case 7 /* ObjectDefinePropertyValue */:
55304                 case 8 /* ObjectDefinePropertyExports */:
55305                 case 9 /* ObjectDefinePrototypeProperty */:
55306                     return ts.Debug.fail("Does not apply");
55307                 default:
55308                     return ts.Debug.assertNever(kind);
55309             }
55310         }
55311         function isCircularMappedProperty(symbol) {
55312             return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
55313         }
55314         function getTypeOfPropertyOfContextualType(type, name) {
55315             return mapType(type, function (t) {
55316                 if (isGenericMappedType(t)) {
55317                     var constraint = getConstraintTypeFromMappedType(t);
55318                     var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
55319                     var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
55320                     if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
55321                         return substituteIndexedMappedType(t, propertyNameType);
55322                     }
55323                 }
55324                 else if (t.flags & 3670016 /* StructuredType */) {
55325                     var prop = getPropertyOfType(t, name);
55326                     if (prop) {
55327                         return isCircularMappedProperty(prop) ? undefined : getTypeOfSymbol(prop);
55328                     }
55329                     if (isTupleType(t)) {
55330                         var restType = getRestTypeOfTupleType(t);
55331                         if (restType && isNumericLiteralName(name) && +name >= 0) {
55332                             return restType;
55333                         }
55334                     }
55335                     return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
55336                         getIndexTypeOfContextualType(t, 0 /* String */);
55337                 }
55338                 return undefined;
55339             }, /*noReductions*/ true);
55340         }
55341         function getIndexTypeOfContextualType(type, kind) {
55342             return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
55343         }
55344         // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
55345         // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
55346         // exists. Otherwise, it is the type of the string index signature in T, if one exists.
55347         function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
55348             ts.Debug.assert(ts.isObjectLiteralMethod(node));
55349             if (node.flags & 16777216 /* InWithStatement */) {
55350                 // We cannot answer semantic questions within a with block, do not proceed any further
55351                 return undefined;
55352             }
55353             return getContextualTypeForObjectLiteralElement(node, contextFlags);
55354         }
55355         function getContextualTypeForObjectLiteralElement(element, contextFlags) {
55356             var objectLiteral = element.parent;
55357             var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
55358             if (type) {
55359                 if (!hasNonBindableDynamicName(element)) {
55360                     // For a (non-symbol) computed property, there is no reason to look up the name
55361                     // in the type. It will just be "__computed", which does not appear in any
55362                     // SymbolTable.
55363                     var symbolName_3 = getSymbolOfNode(element).escapedName;
55364                     var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
55365                     if (propertyType) {
55366                         return propertyType;
55367                     }
55368                 }
55369                 return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
55370                     getIndexTypeOfContextualType(type, 0 /* String */);
55371             }
55372             return undefined;
55373         }
55374         // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
55375         // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
55376         // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
55377         // type of T.
55378         function getContextualTypeForElementExpression(arrayContextualType, index) {
55379             return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
55380                 || getIteratedTypeOrElementType(1 /* Element */, arrayContextualType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false));
55381         }
55382         // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
55383         function getContextualTypeForConditionalOperand(node, contextFlags) {
55384             var conditional = node.parent;
55385             return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
55386         }
55387         function getContextualTypeForChildJsxExpression(node, child) {
55388             var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
55389             // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
55390             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
55391             if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
55392                 return undefined;
55393             }
55394             var realChildren = getSemanticJsxChildren(node.children);
55395             var childIndex = realChildren.indexOf(child);
55396             var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
55397             return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
55398                 if (isArrayLikeType(t)) {
55399                     return getIndexedAccessType(t, getLiteralType(childIndex));
55400                 }
55401                 else {
55402                     return t;
55403                 }
55404             }, /*noReductions*/ true));
55405         }
55406         function getContextualTypeForJsxExpression(node) {
55407             var exprParent = node.parent;
55408             return ts.isJsxAttributeLike(exprParent)
55409                 ? getContextualType(node)
55410                 : ts.isJsxElement(exprParent)
55411                     ? getContextualTypeForChildJsxExpression(exprParent, node)
55412                     : undefined;
55413         }
55414         function getContextualTypeForJsxAttribute(attribute) {
55415             // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
55416             // which is a type of the parameter of the signature we are trying out.
55417             // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
55418             if (ts.isJsxAttribute(attribute)) {
55419                 var attributesType = getApparentTypeOfContextualType(attribute.parent);
55420                 if (!attributesType || isTypeAny(attributesType)) {
55421                     return undefined;
55422                 }
55423                 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
55424             }
55425             else {
55426                 return getContextualType(attribute.parent);
55427             }
55428         }
55429         // Return true if the given expression is possibly a discriminant value. We limit the kinds of
55430         // expressions we check to those that don't depend on their contextual type in order not to cause
55431         // recursive (and possibly infinite) invocations of getContextualType.
55432         function isPossiblyDiscriminantValue(node) {
55433             switch (node.kind) {
55434                 case 10 /* StringLiteral */:
55435                 case 8 /* NumericLiteral */:
55436                 case 9 /* BigIntLiteral */:
55437                 case 14 /* NoSubstitutionTemplateLiteral */:
55438                 case 106 /* TrueKeyword */:
55439                 case 91 /* FalseKeyword */:
55440                 case 100 /* NullKeyword */:
55441                 case 75 /* Identifier */:
55442                 case 146 /* UndefinedKeyword */:
55443                     return true;
55444                 case 194 /* PropertyAccessExpression */:
55445                 case 200 /* ParenthesizedExpression */:
55446                     return isPossiblyDiscriminantValue(node.expression);
55447                 case 276 /* JsxExpression */:
55448                     return !node.expression || isPossiblyDiscriminantValue(node.expression);
55449             }
55450             return false;
55451         }
55452         function discriminateContextualTypeByObjectMembers(node, contextualType) {
55453             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);
55454         }
55455         function discriminateContextualTypeByJSXAttributes(node, contextualType) {
55456             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);
55457         }
55458         // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
55459         // be "pushed" onto a node using the contextualType property.
55460         function getApparentTypeOfContextualType(node, contextFlags) {
55461             var contextualType = ts.isObjectLiteralMethod(node) ?
55462                 getContextualTypeForObjectLiteralMethod(node, contextFlags) :
55463                 getContextualType(node, contextFlags);
55464             var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
55465             if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
55466                 var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
55467                 if (apparentType.flags & 1048576 /* Union */) {
55468                     if (ts.isObjectLiteralExpression(node)) {
55469                         return discriminateContextualTypeByObjectMembers(node, apparentType);
55470                     }
55471                     else if (ts.isJsxAttributes(node)) {
55472                         return discriminateContextualTypeByJSXAttributes(node, apparentType);
55473                     }
55474                 }
55475                 return apparentType;
55476             }
55477         }
55478         // If the given contextual type contains instantiable types and if a mapper representing
55479         // return type inferences is available, instantiate those types using that mapper.
55480         function instantiateContextualType(contextualType, node, contextFlags) {
55481             if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
55482                 var inferenceContext = getInferenceContext(node);
55483                 // If no inferences have been made, nothing is gained from instantiating as type parameters
55484                 // would just be replaced with their defaults similar to the apparent type.
55485                 if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
55486                     // For contextual signatures we incorporate all inferences made so far, e.g. from return
55487                     // types as well as arguments to the left in a function call.
55488                     if (contextFlags && contextFlags & 1 /* Signature */) {
55489                         return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
55490                     }
55491                     // For other purposes (e.g. determining whether to produce literal types) we only
55492                     // incorporate inferences made from the return type in a function call.
55493                     if (inferenceContext.returnMapper) {
55494                         return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
55495                     }
55496                 }
55497             }
55498             return contextualType;
55499         }
55500         // This function is similar to instantiateType, except that (a) it only instantiates types that
55501         // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
55502         // no reductions on instantiated union types.
55503         function instantiateInstantiableTypes(type, mapper) {
55504             if (type.flags & 63176704 /* Instantiable */) {
55505                 return instantiateType(type, mapper);
55506             }
55507             if (type.flags & 1048576 /* Union */) {
55508                 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
55509             }
55510             if (type.flags & 2097152 /* Intersection */) {
55511                 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
55512             }
55513             return type;
55514         }
55515         /**
55516          * Whoa! Do you really want to use this function?
55517          *
55518          * Unless you're trying to get the *non-apparent* type for a
55519          * value-literal type or you're authoring relevant portions of this algorithm,
55520          * you probably meant to use 'getApparentTypeOfContextualType'.
55521          * Otherwise this may not be very useful.
55522          *
55523          * In cases where you *are* working on this function, you should understand
55524          * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
55525          *
55526          *   - Use 'getContextualType' when you are simply going to propagate the result to the expression.
55527          *   - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
55528          *
55529          * @param node the expression whose contextual type will be returned.
55530          * @returns the contextual type of an expression.
55531          */
55532         function getContextualType(node, contextFlags) {
55533             if (node.flags & 16777216 /* InWithStatement */) {
55534                 // We cannot answer semantic questions within a with block, do not proceed any further
55535                 return undefined;
55536             }
55537             if (node.contextualType) {
55538                 return node.contextualType;
55539             }
55540             var parent = node.parent;
55541             switch (parent.kind) {
55542                 case 242 /* VariableDeclaration */:
55543                 case 156 /* Parameter */:
55544                 case 159 /* PropertyDeclaration */:
55545                 case 158 /* PropertySignature */:
55546                 case 191 /* BindingElement */:
55547                     return getContextualTypeForInitializerExpression(node);
55548                 case 202 /* ArrowFunction */:
55549                 case 235 /* ReturnStatement */:
55550                     return getContextualTypeForReturnExpression(node);
55551                 case 212 /* YieldExpression */:
55552                     return getContextualTypeForYieldOperand(parent);
55553                 case 206 /* AwaitExpression */:
55554                     return getContextualTypeForAwaitOperand(parent);
55555                 case 196 /* CallExpression */:
55556                     if (parent.expression.kind === 96 /* ImportKeyword */) {
55557                         return stringType;
55558                     }
55559                 /* falls through */
55560                 case 197 /* NewExpression */:
55561                     return getContextualTypeForArgument(parent, node);
55562                 case 199 /* TypeAssertionExpression */:
55563                 case 217 /* AsExpression */:
55564                     return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
55565                 case 209 /* BinaryExpression */:
55566                     return getContextualTypeForBinaryOperand(node, contextFlags);
55567                 case 281 /* PropertyAssignment */:
55568                 case 282 /* ShorthandPropertyAssignment */:
55569                     return getContextualTypeForObjectLiteralElement(parent, contextFlags);
55570                 case 283 /* SpreadAssignment */:
55571                     return getApparentTypeOfContextualType(parent.parent, contextFlags);
55572                 case 192 /* ArrayLiteralExpression */: {
55573                     var arrayLiteral = parent;
55574                     var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
55575                     return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
55576                 }
55577                 case 210 /* ConditionalExpression */:
55578                     return getContextualTypeForConditionalOperand(node, contextFlags);
55579                 case 221 /* TemplateSpan */:
55580                     ts.Debug.assert(parent.parent.kind === 211 /* TemplateExpression */);
55581                     return getContextualTypeForSubstitutionExpression(parent.parent, node);
55582                 case 200 /* ParenthesizedExpression */: {
55583                     // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
55584                     var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
55585                     return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
55586                 }
55587                 case 276 /* JsxExpression */:
55588                     return getContextualTypeForJsxExpression(parent);
55589                 case 273 /* JsxAttribute */:
55590                 case 275 /* JsxSpreadAttribute */:
55591                     return getContextualTypeForJsxAttribute(parent);
55592                 case 268 /* JsxOpeningElement */:
55593                 case 267 /* JsxSelfClosingElement */:
55594                     return getContextualJsxElementAttributesType(parent, contextFlags);
55595             }
55596             return undefined;
55597         }
55598         function getInferenceContext(node) {
55599             var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
55600             return ancestor && ancestor.inferenceContext;
55601         }
55602         function getContextualJsxElementAttributesType(node, contextFlags) {
55603             if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
55604                 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
55605                 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
55606                 // (as below) instead!
55607                 return node.parent.contextualType;
55608             }
55609             return getContextualTypeForArgumentAtIndex(node, 0);
55610         }
55611         function getEffectiveFirstArgumentForJsxSignature(signature, node) {
55612             return getJsxReferenceKind(node) !== 0 /* Component */
55613                 ? getJsxPropsTypeFromCallSignature(signature, node)
55614                 : getJsxPropsTypeFromClassType(signature, node);
55615         }
55616         function getJsxPropsTypeFromCallSignature(sig, context) {
55617             var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
55618             propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
55619             var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55620             if (intrinsicAttribs !== errorType) {
55621                 propsType = intersectTypes(intrinsicAttribs, propsType);
55622             }
55623             return propsType;
55624         }
55625         function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
55626             if (sig.unionSignatures) {
55627                 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
55628                 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
55629                 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
55630                 // 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.
55631                 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
55632                 var results = [];
55633                 for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
55634                     var signature = _a[_i];
55635                     var instance = getReturnTypeOfSignature(signature);
55636                     if (isTypeAny(instance)) {
55637                         return instance;
55638                     }
55639                     var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
55640                     if (!propType) {
55641                         return;
55642                     }
55643                     results.push(propType);
55644                 }
55645                 return getIntersectionType(results);
55646             }
55647             var instanceType = getReturnTypeOfSignature(sig);
55648             return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
55649         }
55650         function getStaticTypeOfReferencedJsxConstructor(context) {
55651             if (isJsxIntrinsicIdentifier(context.tagName)) {
55652                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
55653                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55654                 return getOrCreateTypeFromSignature(fakeSignature);
55655             }
55656             var tagType = checkExpressionCached(context.tagName);
55657             if (tagType.flags & 128 /* StringLiteral */) {
55658                 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
55659                 if (!result) {
55660                     return errorType;
55661                 }
55662                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55663                 return getOrCreateTypeFromSignature(fakeSignature);
55664             }
55665             return tagType;
55666         }
55667         function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
55668             var managedSym = getJsxLibraryManagedAttributes(ns);
55669             if (managedSym) {
55670                 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
55671                 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
55672                 if (ts.length(declaredManagedType.typeParameters) >= 2) {
55673                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
55674                     return createTypeReference(declaredManagedType, args);
55675                 }
55676                 else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
55677                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
55678                     return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
55679                 }
55680             }
55681             return attributesType;
55682         }
55683         function getJsxPropsTypeFromClassType(sig, context) {
55684             var ns = getJsxNamespaceAt(context);
55685             var forcedLookupLocation = getJsxElementPropertiesName(ns);
55686             var attributesType = forcedLookupLocation === undefined
55687                 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
55688                 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
55689                 : forcedLookupLocation === ""
55690                     // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
55691                     ? getReturnTypeOfSignature(sig)
55692                     // Otherwise get the type of the property on the signature return type
55693                     : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
55694             if (!attributesType) {
55695                 // There is no property named 'props' on this instance type
55696                 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
55697                     error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
55698                 }
55699                 return unknownType;
55700             }
55701             attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
55702             if (isTypeAny(attributesType)) {
55703                 // Props is of type 'any' or unknown
55704                 return attributesType;
55705             }
55706             else {
55707                 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
55708                 var apparentAttributesType = attributesType;
55709                 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
55710                 if (intrinsicClassAttribs !== errorType) {
55711                     var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
55712                     var hostClassType = getReturnTypeOfSignature(sig);
55713                     apparentAttributesType = intersectTypes(typeParams
55714                         ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
55715                         : intrinsicClassAttribs, apparentAttributesType);
55716                 }
55717                 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55718                 if (intrinsicAttribs !== errorType) {
55719                     apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
55720                 }
55721                 return apparentAttributesType;
55722             }
55723         }
55724         // If the given type is an object or union type with a single signature, and if that signature has at
55725         // least as many parameters as the given function, return the signature. Otherwise return undefined.
55726         function getContextualCallSignature(type, node) {
55727             var signatures = getSignaturesOfType(type, 0 /* Call */);
55728             if (signatures.length === 1) {
55729                 var signature = signatures[0];
55730                 if (!isAritySmaller(signature, node)) {
55731                     return signature;
55732                 }
55733             }
55734         }
55735         /** If the contextual signature has fewer parameters than the function expression, do not use it */
55736         function isAritySmaller(signature, target) {
55737             var targetParameterCount = 0;
55738             for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
55739                 var param = target.parameters[targetParameterCount];
55740                 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
55741                     break;
55742                 }
55743             }
55744             if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
55745                 targetParameterCount--;
55746             }
55747             return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
55748         }
55749         function isFunctionExpressionOrArrowFunction(node) {
55750             return node.kind === 201 /* FunctionExpression */ || node.kind === 202 /* ArrowFunction */;
55751         }
55752         function getContextualSignatureForFunctionLikeDeclaration(node) {
55753             // Only function expressions, arrow functions, and object literal methods are contextually typed.
55754             return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
55755                 ? getContextualSignature(node)
55756                 : undefined;
55757         }
55758         // Return the contextual signature for a given expression node. A contextual type provides a
55759         // contextual signature if it has a single call signature and if that call signature is non-generic.
55760         // If the contextual type is a union type, get the signature from each type possible and if they are
55761         // all identical ignoring their return type, the result is same signature but with return type as
55762         // union type of return types from these signatures
55763         function getContextualSignature(node) {
55764             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
55765             var typeTagSignature = getSignatureOfTypeTag(node);
55766             if (typeTagSignature) {
55767                 return typeTagSignature;
55768             }
55769             var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
55770             if (!type) {
55771                 return undefined;
55772             }
55773             if (!(type.flags & 1048576 /* Union */)) {
55774                 return getContextualCallSignature(type, node);
55775             }
55776             var signatureList;
55777             var types = type.types;
55778             for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
55779                 var current = types_17[_i];
55780                 var signature = getContextualCallSignature(current, node);
55781                 if (signature) {
55782                     if (!signatureList) {
55783                         // This signature will contribute to contextual union signature
55784                         signatureList = [signature];
55785                     }
55786                     else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
55787                         // Signatures aren't identical, do not use
55788                         return undefined;
55789                     }
55790                     else {
55791                         // Use this signature for contextual union signature
55792                         signatureList.push(signature);
55793                     }
55794                 }
55795             }
55796             // Result is union of signatures collected (return type is union of return types of this signature set)
55797             if (signatureList) {
55798                 return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
55799             }
55800         }
55801         function checkSpreadExpression(node, checkMode) {
55802             if (languageVersion < 2 /* ES2015 */) {
55803                 checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
55804             }
55805             var arrayOrIterableType = checkExpression(node.expression, checkMode);
55806             return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
55807         }
55808         function hasDefaultValue(node) {
55809             return (node.kind === 191 /* BindingElement */ && !!node.initializer) ||
55810                 (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */);
55811         }
55812         function checkArrayLiteral(node, checkMode, forceTuple) {
55813             var elements = node.elements;
55814             var elementCount = elements.length;
55815             var elementTypes = [];
55816             var hasEndingSpreadElement = false;
55817             var hasNonEndingSpreadElement = false;
55818             var contextualType = getApparentTypeOfContextualType(node);
55819             var inDestructuringPattern = ts.isAssignmentTarget(node);
55820             var inConstContext = isConstContext(node);
55821             for (var i = 0; i < elementCount; i++) {
55822                 var e = elements[i];
55823                 var spread = e.kind === 213 /* SpreadElement */ && e.expression;
55824                 var spreadType = spread && checkExpression(spread, checkMode, forceTuple);
55825                 if (spreadType && isTupleType(spreadType)) {
55826                     elementTypes.push.apply(elementTypes, getTypeArguments(spreadType));
55827                     if (spreadType.target.hasRestElement) {
55828                         if (i === elementCount - 1)
55829                             hasEndingSpreadElement = true;
55830                         else
55831                             hasNonEndingSpreadElement = true;
55832                     }
55833                 }
55834                 else {
55835                     if (inDestructuringPattern && spreadType) {
55836                         // Given the following situation:
55837                         //    var c: {};
55838                         //    [...c] = ["", 0];
55839                         //
55840                         // c is represented in the tree as a spread element in an array literal.
55841                         // But c really functions as a rest element, and its purpose is to provide
55842                         // a contextual type for the right hand side of the assignment. Therefore,
55843                         // instead of calling checkExpression on "...c", which will give an error
55844                         // if c is not iterable/array-like, we need to act as if we are trying to
55845                         // get the contextual element type from it. So we do something similar to
55846                         // getContextualTypeForElementExpression, which will crucially not error
55847                         // if there is no index type / iterated type.
55848                         var restElementType = getIndexTypeOfType(spreadType, 1 /* Number */) ||
55849                             getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false);
55850                         if (restElementType) {
55851                             elementTypes.push(restElementType);
55852                         }
55853                     }
55854                     else {
55855                         var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
55856                         var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
55857                         elementTypes.push(type);
55858                     }
55859                     if (spread) { // tuples are done above, so these are only arrays
55860                         if (i === elementCount - 1)
55861                             hasEndingSpreadElement = true;
55862                         else
55863                             hasNonEndingSpreadElement = true;
55864                     }
55865                 }
55866             }
55867             if (!hasNonEndingSpreadElement) {
55868                 var minLength = elementTypes.length - (hasEndingSpreadElement ? 1 : 0);
55869                 // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
55870                 // that we get the same behavior for "var [x, y] = []" and "[x, y] = []".
55871                 var tupleResult = void 0;
55872                 if (inDestructuringPattern && minLength > 0) {
55873                     var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
55874                     type.pattern = node;
55875                     return type;
55876                 }
55877                 else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasEndingSpreadElement, elementTypes.length, inConstContext)) {
55878                     return createArrayLiteralType(tupleResult);
55879                 }
55880                 else if (forceTuple) {
55881                     return createArrayLiteralType(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
55882                 }
55883             }
55884             return createArrayLiteralType(createArrayType(elementTypes.length ?
55885                 getUnionType(elementTypes, 2 /* Subtype */) :
55886                 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
55887         }
55888         function createArrayLiteralType(type) {
55889             if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
55890                 return type;
55891             }
55892             var literalType = type.literalType;
55893             if (!literalType) {
55894                 literalType = type.literalType = cloneTypeReference(type);
55895                 literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
55896             }
55897             return literalType;
55898         }
55899         function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
55900             if (elementCount === void 0) { elementCount = elementTypes.length; }
55901             if (readonly === void 0) { readonly = false; }
55902             // Infer a tuple type when the contextual type is or contains a tuple-like type
55903             if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
55904                 return createTupleType(elementTypes, elementCount - (hasRestElement ? 1 : 0), hasRestElement, readonly);
55905             }
55906         }
55907         function isNumericName(name) {
55908             switch (name.kind) {
55909                 case 154 /* ComputedPropertyName */:
55910                     return isNumericComputedName(name);
55911                 case 75 /* Identifier */:
55912                     return isNumericLiteralName(name.escapedText);
55913                 case 8 /* NumericLiteral */:
55914                 case 10 /* StringLiteral */:
55915                     return isNumericLiteralName(name.text);
55916                 default:
55917                     return false;
55918             }
55919         }
55920         function isNumericComputedName(name) {
55921             // It seems odd to consider an expression of type Any to result in a numeric name,
55922             // but this behavior is consistent with checkIndexedAccess
55923             return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
55924         }
55925         function isInfinityOrNaNString(name) {
55926             return name === "Infinity" || name === "-Infinity" || name === "NaN";
55927         }
55928         function isNumericLiteralName(name) {
55929             // The intent of numeric names is that
55930             //     - they are names with text in a numeric form, and that
55931             //     - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
55932             //         acquired by applying the abstract 'ToNumber' operation on the name's text.
55933             //
55934             // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
55935             // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
55936             //
55937             // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
55938             // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
55939             // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
55940             // because their 'ToString' representation is not equal to their original text.
55941             // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
55942             //
55943             // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
55944             // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
55945             // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
55946             //
55947             // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
55948             // This is desired behavior, because when indexing with them as numeric entities, you are indexing
55949             // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
55950             return (+name).toString() === name;
55951         }
55952         function checkComputedPropertyName(node) {
55953             var links = getNodeLinks(node.expression);
55954             if (!links.resolvedType) {
55955                 links.resolvedType = checkExpression(node.expression);
55956                 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
55957                 // type, and any union of these types (like string | number).
55958                 if (links.resolvedType.flags & 98304 /* Nullable */ ||
55959                     !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
55960                         !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
55961                     error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
55962                 }
55963                 else {
55964                     checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
55965                 }
55966             }
55967             return links.resolvedType;
55968         }
55969         function getObjectLiteralIndexInfo(node, offset, properties, kind) {
55970             var propTypes = [];
55971             for (var i = 0; i < properties.length; i++) {
55972                 if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
55973                     propTypes.push(getTypeOfSymbol(properties[i]));
55974                 }
55975             }
55976             var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
55977             return createIndexInfo(unionType, isConstContext(node));
55978         }
55979         function getImmediateAliasedSymbol(symbol) {
55980             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
55981             var links = getSymbolLinks(symbol);
55982             if (!links.immediateTarget) {
55983                 var node = getDeclarationOfAliasSymbol(symbol);
55984                 if (!node)
55985                     return ts.Debug.fail();
55986                 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
55987             }
55988             return links.immediateTarget;
55989         }
55990         function checkObjectLiteral(node, checkMode) {
55991             var inDestructuringPattern = ts.isAssignmentTarget(node);
55992             // Grammar checking
55993             checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
55994             var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
55995             var propertiesTable = ts.createSymbolTable();
55996             var propertiesArray = [];
55997             var spread = emptyObjectType;
55998             var contextualType = getApparentTypeOfContextualType(node);
55999             var contextualTypeHasPattern = contextualType && contextualType.pattern &&
56000                 (contextualType.pattern.kind === 189 /* ObjectBindingPattern */ || contextualType.pattern.kind === 193 /* ObjectLiteralExpression */);
56001             var inConstContext = isConstContext(node);
56002             var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
56003             var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
56004             var enumTag = ts.getJSDocEnumTag(node);
56005             var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
56006             var objectFlags = freshObjectLiteralFlag;
56007             var patternWithComputedProperties = false;
56008             var hasComputedStringProperty = false;
56009             var hasComputedNumberProperty = false;
56010             // Spreads may cause an early bail; ensure computed names are always checked (this is cached)
56011             // As otherwise they may not be checked until exports for the type at this position are retrieved,
56012             // which may never occur.
56013             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
56014                 var elem = _a[_i];
56015                 if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) {
56016                     checkComputedPropertyName(elem.name);
56017                 }
56018             }
56019             var offset = 0;
56020             for (var i = 0; i < node.properties.length; i++) {
56021                 var memberDecl = node.properties[i];
56022                 var member = getSymbolOfNode(memberDecl);
56023                 var computedNameType = memberDecl.name && memberDecl.name.kind === 154 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
56024                     checkComputedPropertyName(memberDecl.name) : undefined;
56025                 if (memberDecl.kind === 281 /* PropertyAssignment */ ||
56026                     memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ||
56027                     ts.isObjectLiteralMethod(memberDecl)) {
56028                     var type = memberDecl.kind === 281 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
56029                         memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) :
56030                             checkObjectLiteralMethod(memberDecl, checkMode);
56031                     if (isInJavascript) {
56032                         var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
56033                         if (jsDocType) {
56034                             checkTypeAssignableTo(type, jsDocType, memberDecl);
56035                             type = jsDocType;
56036                         }
56037                         else if (enumTag && enumTag.typeExpression) {
56038                             checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
56039                         }
56040                     }
56041                     objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */;
56042                     var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
56043                     var prop = nameType ?
56044                         createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
56045                         createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
56046                     if (nameType) {
56047                         prop.nameType = nameType;
56048                     }
56049                     if (inDestructuringPattern) {
56050                         // If object literal is an assignment pattern and if the assignment pattern specifies a default value
56051                         // for the property, make the property optional.
56052                         var isOptional = (memberDecl.kind === 281 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
56053                             (memberDecl.kind === 282 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
56054                         if (isOptional) {
56055                             prop.flags |= 16777216 /* Optional */;
56056                         }
56057                     }
56058                     else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
56059                         // If object literal is contextually typed by the implied type of a binding pattern, and if the
56060                         // binding pattern specifies a default value for the property, make the property optional.
56061                         var impliedProp = getPropertyOfType(contextualType, member.escapedName);
56062                         if (impliedProp) {
56063                             prop.flags |= impliedProp.flags & 16777216 /* Optional */;
56064                         }
56065                         else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
56066                             error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
56067                         }
56068                     }
56069                     prop.declarations = member.declarations;
56070                     prop.parent = member.parent;
56071                     if (member.valueDeclaration) {
56072                         prop.valueDeclaration = member.valueDeclaration;
56073                     }
56074                     prop.type = type;
56075                     prop.target = member;
56076                     member = prop;
56077                     allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
56078                 }
56079                 else if (memberDecl.kind === 283 /* SpreadAssignment */) {
56080                     if (languageVersion < 2 /* ES2015 */) {
56081                         checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
56082                     }
56083                     if (propertiesArray.length > 0) {
56084                         spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56085                         propertiesArray = [];
56086                         propertiesTable = ts.createSymbolTable();
56087                         hasComputedStringProperty = false;
56088                         hasComputedNumberProperty = false;
56089                     }
56090                     var type = getReducedType(checkExpression(memberDecl.expression));
56091                     if (!isValidSpreadType(type)) {
56092                         error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
56093                         return errorType;
56094                     }
56095                     if (allPropertiesTable) {
56096                         checkSpreadPropOverrides(type, allPropertiesTable, memberDecl);
56097                     }
56098                     spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
56099                     offset = i + 1;
56100                     continue;
56101                 }
56102                 else {
56103                     // TypeScript 1.0 spec (April 2014)
56104                     // A get accessor declaration is processed in the same manner as
56105                     // an ordinary function declaration(section 6.1) with no parameters.
56106                     // A set accessor declaration is processed in the same manner
56107                     // as an ordinary function declaration with a single parameter and a Void return type.
56108                     ts.Debug.assert(memberDecl.kind === 163 /* GetAccessor */ || memberDecl.kind === 164 /* SetAccessor */);
56109                     checkNodeDeferred(memberDecl);
56110                 }
56111                 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
56112                     if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
56113                         if (isTypeAssignableTo(computedNameType, numberType)) {
56114                             hasComputedNumberProperty = true;
56115                         }
56116                         else {
56117                             hasComputedStringProperty = true;
56118                         }
56119                         if (inDestructuringPattern) {
56120                             patternWithComputedProperties = true;
56121                         }
56122                     }
56123                 }
56124                 else {
56125                     propertiesTable.set(member.escapedName, member);
56126                 }
56127                 propertiesArray.push(member);
56128             }
56129             // If object literal is contextually typed by the implied type of a binding pattern, augment the result
56130             // type with those properties for which the binding pattern specifies a default value.
56131             // If the object literal is spread into another object literal, skip this step and let the top-level object
56132             // literal handle it instead.
56133             if (contextualTypeHasPattern && node.parent.kind !== 283 /* SpreadAssignment */) {
56134                 for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) {
56135                     var prop = _c[_b];
56136                     if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) {
56137                         if (!(prop.flags & 16777216 /* Optional */)) {
56138                             error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
56139                         }
56140                         propertiesTable.set(prop.escapedName, prop);
56141                         propertiesArray.push(prop);
56142                     }
56143                 }
56144             }
56145             if (spread !== emptyObjectType) {
56146                 if (propertiesArray.length > 0) {
56147                     spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56148                     propertiesArray = [];
56149                     propertiesTable = ts.createSymbolTable();
56150                     hasComputedStringProperty = false;
56151                     hasComputedNumberProperty = false;
56152                 }
56153                 // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
56154                 return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
56155             }
56156             return createObjectLiteralType();
56157             function createObjectLiteralType() {
56158                 var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
56159                 var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
56160                 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
56161                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56162                 if (isJSObjectLiteral) {
56163                     result.objectFlags |= 16384 /* JSLiteral */;
56164                 }
56165                 if (patternWithComputedProperties) {
56166                     result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
56167                 }
56168                 if (inDestructuringPattern) {
56169                     result.pattern = node;
56170                 }
56171                 return result;
56172             }
56173         }
56174         function isValidSpreadType(type) {
56175             if (type.flags & 63176704 /* Instantiable */) {
56176                 var constraint = getBaseConstraintOfType(type);
56177                 if (constraint !== undefined) {
56178                     return isValidSpreadType(constraint);
56179                 }
56180             }
56181             return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
56182                 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
56183                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
56184         }
56185         function checkJsxSelfClosingElementDeferred(node) {
56186             checkJsxOpeningLikeElementOrOpeningFragment(node);
56187             resolveUntypedCall(node); // ensure type arguments and parameters are typechecked, even if there is an arity error
56188         }
56189         function checkJsxSelfClosingElement(node, _checkMode) {
56190             checkNodeDeferred(node);
56191             return getJsxElementTypeAt(node) || anyType;
56192         }
56193         function checkJsxElementDeferred(node) {
56194             // Check attributes
56195             checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
56196             // Perform resolution on the closing tag so that rename/go to definition/etc work
56197             if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
56198                 getIntrinsicTagSymbol(node.closingElement);
56199             }
56200             else {
56201                 checkExpression(node.closingElement.tagName);
56202             }
56203             checkJsxChildren(node);
56204         }
56205         function checkJsxElement(node, _checkMode) {
56206             checkNodeDeferred(node);
56207             return getJsxElementTypeAt(node) || anyType;
56208         }
56209         function checkJsxFragment(node) {
56210             checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
56211             if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
56212                 error(node, compilerOptions.jsxFactory
56213                     ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
56214                     : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
56215             }
56216             checkJsxChildren(node);
56217             return getJsxElementTypeAt(node) || anyType;
56218         }
56219         /**
56220          * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
56221          */
56222         function isUnhyphenatedJsxName(name) {
56223             // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
56224             return !ts.stringContains(name, "-");
56225         }
56226         /**
56227          * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
56228          */
56229         function isJsxIntrinsicIdentifier(tagName) {
56230             return tagName.kind === 75 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
56231         }
56232         function checkJsxAttribute(node, checkMode) {
56233             return node.initializer
56234                 ? checkExpressionForMutableLocation(node.initializer, checkMode)
56235                 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
56236         }
56237         /**
56238          * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
56239          *
56240          * @param openingLikeElement a JSX opening-like element
56241          * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
56242          * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
56243          * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
56244          * which also calls getSpreadType.
56245          */
56246         function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
56247             var attributes = openingLikeElement.attributes;
56248             var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
56249             var attributesTable = ts.createSymbolTable();
56250             var spread = emptyJsxObjectType;
56251             var hasSpreadAnyType = false;
56252             var typeToIntersect;
56253             var explicitlySpecifyChildrenAttribute = false;
56254             var objectFlags = 4096 /* JsxAttributes */;
56255             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
56256             for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
56257                 var attributeDecl = _a[_i];
56258                 var member = attributeDecl.symbol;
56259                 if (ts.isJsxAttribute(attributeDecl)) {
56260                     var exprType = checkJsxAttribute(attributeDecl, checkMode);
56261                     objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */;
56262                     var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
56263                     attributeSymbol.declarations = member.declarations;
56264                     attributeSymbol.parent = member.parent;
56265                     if (member.valueDeclaration) {
56266                         attributeSymbol.valueDeclaration = member.valueDeclaration;
56267                     }
56268                     attributeSymbol.type = exprType;
56269                     attributeSymbol.target = member;
56270                     attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56271                     allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56272                     if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
56273                         explicitlySpecifyChildrenAttribute = true;
56274                     }
56275                 }
56276                 else {
56277                     ts.Debug.assert(attributeDecl.kind === 275 /* JsxSpreadAttribute */);
56278                     if (attributesTable.size > 0) {
56279                         spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56280                         attributesTable = ts.createSymbolTable();
56281                     }
56282                     var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode));
56283                     if (isTypeAny(exprType)) {
56284                         hasSpreadAnyType = true;
56285                     }
56286                     if (isValidSpreadType(exprType)) {
56287                         spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
56288                         if (allAttributesTable) {
56289                             checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
56290                         }
56291                     }
56292                     else {
56293                         typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
56294                     }
56295                 }
56296             }
56297             if (!hasSpreadAnyType) {
56298                 if (attributesTable.size > 0) {
56299                     spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56300                 }
56301             }
56302             // Handle children attribute
56303             var parent = openingLikeElement.parent.kind === 266 /* JsxElement */ ? openingLikeElement.parent : undefined;
56304             // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
56305             if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
56306                 var childrenTypes = checkJsxChildren(parent, checkMode);
56307                 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
56308                     // Error if there is a attribute named "children" explicitly specified and children element.
56309                     // This is because children element will overwrite the value from attributes.
56310                     // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
56311                     if (explicitlySpecifyChildrenAttribute) {
56312                         error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
56313                     }
56314                     var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
56315                     var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
56316                     // 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
56317                     var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName);
56318                     childrenPropSymbol.type = childrenTypes.length === 1 ?
56319                         childrenTypes[0] :
56320                         (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes)));
56321                     // Fake up a property declaration for the children
56322                     childrenPropSymbol.valueDeclaration = ts.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined);
56323                     childrenPropSymbol.valueDeclaration.parent = attributes;
56324                     childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
56325                     var childPropMap = ts.createSymbolTable();
56326                     childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
56327                     spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
56328                 }
56329             }
56330             if (hasSpreadAnyType) {
56331                 return anyType;
56332             }
56333             if (typeToIntersect && spread !== emptyJsxObjectType) {
56334                 return getIntersectionType([typeToIntersect, spread]);
56335             }
56336             return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
56337             /**
56338              * Create anonymous type from given attributes symbol table.
56339              * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
56340              * @param attributesTable a symbol table of attributes property
56341              */
56342             function createJsxAttributesType() {
56343                 objectFlags |= freshObjectLiteralFlag;
56344                 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
56345                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56346                 return result;
56347             }
56348         }
56349         function checkJsxChildren(node, checkMode) {
56350             var childrenTypes = [];
56351             for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
56352                 var child = _a[_i];
56353                 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
56354                 // because then type of children property will have constituent of string type.
56355                 if (child.kind === 11 /* JsxText */) {
56356                     if (!child.containsOnlyTriviaWhiteSpaces) {
56357                         childrenTypes.push(stringType);
56358                     }
56359                 }
56360                 else {
56361                     childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
56362                 }
56363             }
56364             return childrenTypes;
56365         }
56366         function checkSpreadPropOverrides(type, props, spread) {
56367             for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
56368                 var right = _a[_i];
56369                 var left = props.get(right.escapedName);
56370                 var rightType = getTypeOfSymbol(right);
56371                 if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 3 /* AnyOrUnknown */) && right.flags & 16777216 /* Optional */)) {
56372                     var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName));
56373                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property));
56374                 }
56375             }
56376         }
56377         /**
56378          * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
56379          * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
56380          * @param node a JSXAttributes to be resolved of its type
56381          */
56382         function checkJsxAttributes(node, checkMode) {
56383             return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
56384         }
56385         function getJsxType(name, location) {
56386             var namespace = getJsxNamespaceAt(location);
56387             var exports = namespace && getExportsOfSymbol(namespace);
56388             var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
56389             return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
56390         }
56391         /**
56392          * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
56393          * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
56394          * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
56395          * May also return unknownSymbol if both of these lookups fail.
56396          */
56397         function getIntrinsicTagSymbol(node) {
56398             var links = getNodeLinks(node);
56399             if (!links.resolvedSymbol) {
56400                 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
56401                 if (intrinsicElementsType !== errorType) {
56402                     // Property case
56403                     if (!ts.isIdentifier(node.tagName))
56404                         return ts.Debug.fail();
56405                     var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
56406                     if (intrinsicProp) {
56407                         links.jsxFlags |= 1 /* IntrinsicNamedElement */;
56408                         return links.resolvedSymbol = intrinsicProp;
56409                     }
56410                     // Intrinsic string indexer case
56411                     var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56412                     if (indexSignatureType) {
56413                         links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
56414                         return links.resolvedSymbol = intrinsicElementsType.symbol;
56415                     }
56416                     // Wasn't found
56417                     error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
56418                     return links.resolvedSymbol = unknownSymbol;
56419                 }
56420                 else {
56421                     if (noImplicitAny) {
56422                         error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
56423                     }
56424                     return links.resolvedSymbol = unknownSymbol;
56425                 }
56426             }
56427             return links.resolvedSymbol;
56428         }
56429         function getJsxNamespaceAt(location) {
56430             var links = location && getNodeLinks(location);
56431             if (links && links.jsxNamespace) {
56432                 return links.jsxNamespace;
56433             }
56434             if (!links || links.jsxNamespace !== false) {
56435                 var namespaceName = getJsxNamespace(location);
56436                 var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
56437                 if (resolvedNamespace) {
56438                     var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
56439                     if (candidate) {
56440                         if (links) {
56441                             links.jsxNamespace = candidate;
56442                         }
56443                         return candidate;
56444                     }
56445                     if (links) {
56446                         links.jsxNamespace = false;
56447                     }
56448                 }
56449             }
56450             // JSX global fallback
56451             return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217
56452         }
56453         /**
56454          * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
56455          * Get a single property from that container if existed. Report an error if there are more than one property.
56456          *
56457          * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
56458          *          if other string is given or the container doesn't exist, return undefined.
56459          */
56460         function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
56461             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
56462             var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
56463             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
56464             var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
56465             // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
56466             var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
56467             if (propertiesOfJsxElementAttribPropInterface) {
56468                 // Element Attributes has zero properties, so the element attributes type will be the class instance type
56469                 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
56470                     return "";
56471                 }
56472                 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
56473                 // property of the class instance type
56474                 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
56475                     return propertiesOfJsxElementAttribPropInterface[0].escapedName;
56476                 }
56477                 else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
56478                     // More than one property on ElementAttributesProperty is an error
56479                     error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
56480                 }
56481             }
56482             return undefined;
56483         }
56484         function getJsxLibraryManagedAttributes(jsxNamespace) {
56485             // JSX.LibraryManagedAttributes [symbol]
56486             return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
56487         }
56488         /// e.g. "props" for React.d.ts,
56489         /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
56490         ///     non-intrinsic elements' attributes type is 'any'),
56491         /// or '' if it has 0 properties (which means every
56492         ///     non-intrinsic elements' attributes type is the element instance type)
56493         function getJsxElementPropertiesName(jsxNamespace) {
56494             return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
56495         }
56496         function getJsxElementChildrenPropertyName(jsxNamespace) {
56497             return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
56498         }
56499         function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
56500             if (elementType.flags & 4 /* String */) {
56501                 return [anySignature];
56502             }
56503             else if (elementType.flags & 128 /* StringLiteral */) {
56504                 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
56505                 if (!intrinsicType) {
56506                     error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
56507                     return ts.emptyArray;
56508                 }
56509                 else {
56510                     var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
56511                     return [fakeSignature];
56512                 }
56513             }
56514             var apparentElemType = getApparentType(elementType);
56515             // Resolve the signatures, preferring constructor
56516             var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
56517             if (signatures.length === 0) {
56518                 // No construct signatures, try call signatures
56519                 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
56520             }
56521             if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
56522                 // If each member has some combination of new/call signatures; make a union signature list for those
56523                 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
56524             }
56525             return signatures;
56526         }
56527         function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
56528             // 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
56529             // For example:
56530             //      var CustomTag: "h1" = "h1";
56531             //      <CustomTag> Hello World </CustomTag>
56532             var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
56533             if (intrinsicElementsType !== errorType) {
56534                 var stringLiteralTypeName = type.value;
56535                 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
56536                 if (intrinsicProp) {
56537                     return getTypeOfSymbol(intrinsicProp);
56538                 }
56539                 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56540                 if (indexSignatureType) {
56541                     return indexSignatureType;
56542                 }
56543                 return undefined;
56544             }
56545             // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
56546             return anyType;
56547         }
56548         function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
56549             if (refKind === 1 /* Function */) {
56550                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56551                 if (sfcReturnConstraint) {
56552                     checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56553                 }
56554             }
56555             else if (refKind === 0 /* Component */) {
56556                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56557                 if (classConstraint) {
56558                     // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that
56559                     checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56560                 }
56561             }
56562             else { // Mixed
56563                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56564                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56565                 if (!sfcReturnConstraint || !classConstraint) {
56566                     return;
56567                 }
56568                 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
56569                 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56570             }
56571             function generateInitialErrorChain() {
56572                 var componentName = ts.getTextOfNode(openingLikeElement.tagName);
56573                 return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName);
56574             }
56575         }
56576         /**
56577          * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
56578          * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
56579          * @param node an intrinsic JSX opening-like element
56580          */
56581         function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
56582             ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
56583             var links = getNodeLinks(node);
56584             if (!links.resolvedJsxElementAttributesType) {
56585                 var symbol = getIntrinsicTagSymbol(node);
56586                 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
56587                     return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
56588                 }
56589                 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
56590                     return links.resolvedJsxElementAttributesType =
56591                         getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */);
56592                 }
56593                 else {
56594                     return links.resolvedJsxElementAttributesType = errorType;
56595                 }
56596             }
56597             return links.resolvedJsxElementAttributesType;
56598         }
56599         function getJsxElementClassTypeAt(location) {
56600             var type = getJsxType(JsxNames.ElementClass, location);
56601             if (type === errorType)
56602                 return undefined;
56603             return type;
56604         }
56605         function getJsxElementTypeAt(location) {
56606             return getJsxType(JsxNames.Element, location);
56607         }
56608         function getJsxStatelessElementTypeAt(location) {
56609             var jsxElementType = getJsxElementTypeAt(location);
56610             if (jsxElementType) {
56611                 return getUnionType([jsxElementType, nullType]);
56612             }
56613         }
56614         /**
56615          * Returns all the properties of the Jsx.IntrinsicElements interface
56616          */
56617         function getJsxIntrinsicTagNamesAt(location) {
56618             var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
56619             return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
56620         }
56621         function checkJsxPreconditions(errorNode) {
56622             // Preconditions for using JSX
56623             if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
56624                 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
56625             }
56626             if (getJsxElementTypeAt(errorNode) === undefined) {
56627                 if (noImplicitAny) {
56628                     error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
56629                 }
56630             }
56631         }
56632         function checkJsxOpeningLikeElementOrOpeningFragment(node) {
56633             var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
56634             if (isNodeOpeningLikeElement) {
56635                 checkGrammarJsxElement(node);
56636             }
56637             checkJsxPreconditions(node);
56638             // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
56639             // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
56640             var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
56641             var reactNamespace = getJsxNamespace(node);
56642             var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
56643             var reactSym = resolveName(reactLocation, reactNamespace, 111551 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
56644             if (reactSym) {
56645                 // Mark local symbol as referenced here because it might not have been marked
56646                 // if jsx emit was not react as there wont be error being emitted
56647                 reactSym.isReferenced = 67108863 /* All */;
56648                 // If react symbol is alias, mark it as refereced
56649                 if (reactSym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(reactSym)) {
56650                     markAliasSymbolAsReferenced(reactSym);
56651                 }
56652             }
56653             if (isNodeOpeningLikeElement) {
56654                 var jsxOpeningLikeNode = node;
56655                 var sig = getResolvedSignature(jsxOpeningLikeNode);
56656                 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
56657             }
56658         }
56659         /**
56660          * Check if a property with the given name is known anywhere in the given type. In an object type, a property
56661          * is considered known if
56662          * 1. the object type is empty and the check is for assignability, or
56663          * 2. if the object type has index signatures, or
56664          * 3. if the property is actually declared in the object type
56665          *    (this means that 'toString', for example, is not usually a known property).
56666          * 4. In a union or intersection type,
56667          *    a property is considered known if it is known in any constituent type.
56668          * @param targetType a type to search a given name in
56669          * @param name a property name to search
56670          * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
56671          */
56672         function isKnownProperty(targetType, name, isComparingJsxAttributes) {
56673             if (targetType.flags & 524288 /* Object */) {
56674                 var resolved = resolveStructuredTypeMembers(targetType);
56675                 if (resolved.stringIndexInfo ||
56676                     resolved.numberIndexInfo && isNumericLiteralName(name) ||
56677                     getPropertyOfObjectType(targetType, name) ||
56678                     isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
56679                     // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
56680                     return true;
56681                 }
56682             }
56683             else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
56684                 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
56685                     var t = _a[_i];
56686                     if (isKnownProperty(t, name, isComparingJsxAttributes)) {
56687                         return true;
56688                     }
56689                 }
56690             }
56691             return false;
56692         }
56693         function isExcessPropertyCheckTarget(type) {
56694             return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
56695                 type.flags & 67108864 /* NonPrimitive */ ||
56696                 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
56697                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
56698         }
56699         function checkJsxExpression(node, checkMode) {
56700             checkGrammarJsxExpression(node);
56701             if (node.expression) {
56702                 var type = checkExpression(node.expression, checkMode);
56703                 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
56704                     error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
56705                 }
56706                 return type;
56707             }
56708             else {
56709                 return errorType;
56710             }
56711         }
56712         function getDeclarationNodeFlagsFromSymbol(s) {
56713             return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
56714         }
56715         /**
56716          * Return whether this symbol is a member of a prototype somewhere
56717          * Note that this is not tracked well within the compiler, so the answer may be incorrect.
56718          */
56719         function isPrototypeProperty(symbol) {
56720             if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
56721                 return true;
56722             }
56723             if (ts.isInJSFile(symbol.valueDeclaration)) {
56724                 var parent = symbol.valueDeclaration.parent;
56725                 return parent && ts.isBinaryExpression(parent) &&
56726                     ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
56727             }
56728         }
56729         /**
56730          * Check whether the requested property access is valid.
56731          * Returns true if node is a valid property access, and false otherwise.
56732          * @param node The node to be checked.
56733          * @param isSuper True if the access is from `super.`.
56734          * @param type The type of the object whose property is being accessed. (Not the type of the property.)
56735          * @param prop The symbol for the property being accessed.
56736          */
56737         function checkPropertyAccessibility(node, isSuper, type, prop) {
56738             var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
56739             var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name;
56740             if (isSuper) {
56741                 // TS 1.0 spec (April 2014): 4.8.2
56742                 // - In a constructor, instance member function, instance member accessor, or
56743                 //   instance member variable initializer where this references a derived class instance,
56744                 //   a super property access is permitted and must specify a public instance member function of the base class.
56745                 // - In a static member function or static member accessor
56746                 //   where this references the constructor function object of a derived class,
56747                 //   a super property access is permitted and must specify a public static member function of the base class.
56748                 if (languageVersion < 2 /* ES2015 */) {
56749                     if (symbolHasNonMethodDeclaration(prop)) {
56750                         error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
56751                         return false;
56752                     }
56753                 }
56754                 if (flags & 128 /* Abstract */) {
56755                     // A method cannot be accessed in a super property access if the method is abstract.
56756                     // This error could mask a private property access error. But, a member
56757                     // cannot simultaneously be private and abstract, so this will trigger an
56758                     // additional error elsewhere.
56759                     error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56760                     return false;
56761                 }
56762             }
56763             // Referencing abstract properties within their own constructors is not allowed
56764             if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
56765                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56766                 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
56767                     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
56768                     return false;
56769                 }
56770             }
56771             if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) {
56772                 if (!ts.getContainingClass(node)) {
56773                     error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
56774                     return false;
56775                 }
56776                 return true;
56777             }
56778             // Public properties are otherwise accessible.
56779             if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
56780                 return true;
56781             }
56782             // Property is known to be private or protected at this point
56783             // Private property is accessible if the property is within the declaring class
56784             if (flags & 8 /* Private */) {
56785                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56786                 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
56787                     error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56788                     return false;
56789                 }
56790                 return true;
56791             }
56792             // Property is known to be protected at this point
56793             // All protected properties of a supertype are accessible in a super access
56794             if (isSuper) {
56795                 return true;
56796             }
56797             // Find the first enclosing class that has the declaring classes of the protected constituents
56798             // of the property as base classes
56799             var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
56800                 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
56801                 return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
56802             });
56803             // A protected property is accessible if the property is within the declaring class or classes derived from it
56804             if (!enclosingClass) {
56805                 // allow PropertyAccessibility if context is in function with this parameter
56806                 // static member access is disallow
56807                 var thisParameter = void 0;
56808                 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
56809                     error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
56810                     return false;
56811                 }
56812                 var thisType = getTypeFromTypeNode(thisParameter.type);
56813                 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target;
56814             }
56815             // No further restrictions for static properties
56816             if (flags & 32 /* Static */) {
56817                 return true;
56818             }
56819             if (type.flags & 262144 /* TypeParameter */) {
56820                 // get the original type -- represented as the type constraint of the 'this' type
56821                 type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
56822             }
56823             if (!type || !hasBaseType(type, enclosingClass)) {
56824                 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
56825                 return false;
56826             }
56827             return true;
56828         }
56829         function getThisParameterFromNodeContext(node) {
56830             var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
56831             return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
56832         }
56833         function symbolHasNonMethodDeclaration(symbol) {
56834             return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
56835         }
56836         function checkNonNullExpression(node) {
56837             return checkNonNullType(checkExpression(node), node);
56838         }
56839         function isNullableType(type) {
56840             return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
56841         }
56842         function getNonNullableTypeIfNeeded(type) {
56843             return isNullableType(type) ? getNonNullableType(type) : type;
56844         }
56845         function reportObjectPossiblyNullOrUndefinedError(node, flags) {
56846             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
56847                 ts.Diagnostics.Object_is_possibly_null_or_undefined :
56848                 ts.Diagnostics.Object_is_possibly_undefined :
56849                 ts.Diagnostics.Object_is_possibly_null);
56850         }
56851         function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
56852             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
56853                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
56854                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
56855                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
56856         }
56857         function checkNonNullTypeWithReporter(type, node, reportError) {
56858             if (strictNullChecks && type.flags & 2 /* Unknown */) {
56859                 error(node, ts.Diagnostics.Object_is_of_type_unknown);
56860                 return errorType;
56861             }
56862             var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
56863             if (kind) {
56864                 reportError(node, kind);
56865                 var t = getNonNullableType(type);
56866                 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
56867             }
56868             return type;
56869         }
56870         function checkNonNullType(type, node) {
56871             return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
56872         }
56873         function checkNonNullNonVoidType(type, node) {
56874             var nonNullType = checkNonNullType(type, node);
56875             if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) {
56876                 error(node, ts.Diagnostics.Object_is_possibly_undefined);
56877             }
56878             return nonNullType;
56879         }
56880         function checkPropertyAccessExpression(node) {
56881             return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) :
56882                 checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name);
56883         }
56884         function checkPropertyAccessChain(node) {
56885             var leftType = checkExpression(node.expression);
56886             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
56887             return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType);
56888         }
56889         function checkQualifiedName(node) {
56890             return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right);
56891         }
56892         function isMethodAccessForCall(node) {
56893             while (node.parent.kind === 200 /* ParenthesizedExpression */) {
56894                 node = node.parent;
56895             }
56896             return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
56897         }
56898         // Lookup the private identifier lexically.
56899         function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
56900             for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
56901                 var symbol = containingClass.symbol;
56902                 var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
56903                 var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
56904                 if (prop) {
56905                     return prop;
56906                 }
56907             }
56908         }
56909         function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
56910             return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
56911         }
56912         function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
56913             // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
56914             // Find a private identifier with the same description on the type.
56915             var propertyOnType;
56916             var properties = getPropertiesOfType(leftType);
56917             if (properties) {
56918                 ts.forEach(properties, function (symbol) {
56919                     var decl = symbol.valueDeclaration;
56920                     if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
56921                         propertyOnType = symbol;
56922                         return true;
56923                     }
56924                 });
56925             }
56926             var diagName = diagnosticName(right);
56927             if (propertyOnType) {
56928                 var typeValueDecl = propertyOnType.valueDeclaration;
56929                 var typeClass_1 = ts.getContainingClass(typeValueDecl);
56930                 ts.Debug.assert(!!typeClass_1);
56931                 // We found a private identifier property with the same description.
56932                 // Either:
56933                 // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
56934                 // - It is an attempt to access the private identifier outside of the class.
56935                 if (lexicallyScopedIdentifier) {
56936                     var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
56937                     var lexicalClass = ts.getContainingClass(lexicalValueDecl);
56938                     ts.Debug.assert(!!lexicalClass);
56939                     if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
56940                         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));
56941                         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));
56942                         return true;
56943                     }
56944                 }
56945                 error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
56946                 return true;
56947             }
56948             return false;
56949         }
56950         function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) {
56951             var parentSymbol = getNodeLinks(left).resolvedSymbol;
56952             var assignmentKind = ts.getAssignmentTargetKind(node);
56953             var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
56954             if (ts.isPrivateIdentifier(right)) {
56955                 checkExternalEmitHelpers(node, 262144 /* ClassPrivateFieldGet */);
56956             }
56957             var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
56958             var prop;
56959             if (ts.isPrivateIdentifier(right)) {
56960                 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
56961                 if (isAnyLike) {
56962                     if (lexicallyScopedSymbol) {
56963                         return apparentType;
56964                     }
56965                     if (!ts.getContainingClass(right)) {
56966                         grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
56967                         return anyType;
56968                     }
56969                 }
56970                 prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
56971                 // Check for private-identifier-specific shadowing and lexical-scoping errors.
56972                 if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
56973                     return errorType;
56974                 }
56975             }
56976             else {
56977                 if (isAnyLike) {
56978                     if (ts.isIdentifier(left) && parentSymbol) {
56979                         markAliasReferenced(parentSymbol, node);
56980                     }
56981                     return apparentType;
56982                 }
56983                 prop = getPropertyOfType(apparentType, right.escapedText);
56984             }
56985             if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
56986                 markAliasReferenced(parentSymbol, node);
56987             }
56988             var propType;
56989             if (!prop) {
56990                 var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getIndexInfoOfType(apparentType, 0 /* String */) : undefined;
56991                 if (!(indexInfo && indexInfo.type)) {
56992                     if (isJSLiteralType(leftType)) {
56993                         return anyType;
56994                     }
56995                     if (leftType.symbol === globalThisSymbol) {
56996                         if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
56997                             error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
56998                         }
56999                         else if (noImplicitAny) {
57000                             error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
57001                         }
57002                         return anyType;
57003                     }
57004                     if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
57005                         reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
57006                     }
57007                     return errorType;
57008                 }
57009                 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
57010                     error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
57011                 }
57012                 propType = indexInfo.type;
57013             }
57014             else {
57015                 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
57016                 markPropertyAsReferenced(prop, node, left.kind === 104 /* ThisKeyword */);
57017                 getNodeLinks(node).resolvedSymbol = prop;
57018                 checkPropertyAccessibility(node, left.kind === 102 /* SuperKeyword */, apparentType, prop);
57019                 if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
57020                     error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
57021                     return errorType;
57022                 }
57023                 propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
57024             }
57025             return getFlowTypeOfAccessExpression(node, prop, propType, right);
57026         }
57027         function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) {
57028             // Only compute control flow type if this is a property access expression that isn't an
57029             // assignment target, and the referenced property was declared as a variable, property,
57030             // accessor, or optional method.
57031             var assignmentKind = ts.getAssignmentTargetKind(node);
57032             if (!ts.isAccessExpression(node) ||
57033                 assignmentKind === 1 /* Definite */ ||
57034                 prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
57035                 return propType;
57036             }
57037             // If strict null checks and strict property initialization checks are enabled, if we have
57038             // a this.xxx property access, if the property is an instance property without an initializer,
57039             // and if we are in a constructor of the same class as the property declaration, assume that
57040             // the property is uninitialized at the top of the control flow.
57041             var assumeUninitialized = false;
57042             if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 104 /* ThisKeyword */) {
57043                 var declaration = prop && prop.valueDeclaration;
57044                 if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
57045                     var flowContainer = getControlFlowContainer(node);
57046                     if (flowContainer.kind === 162 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
57047                         assumeUninitialized = true;
57048                     }
57049                 }
57050             }
57051             else if (strictNullChecks && prop && prop.valueDeclaration &&
57052                 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
57053                 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
57054                 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
57055                 assumeUninitialized = true;
57056             }
57057             var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
57058             if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
57059                 error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
57060                 // Return the declared type to reduce follow-on errors
57061                 return propType;
57062             }
57063             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
57064         }
57065         function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
57066             var valueDeclaration = prop.valueDeclaration;
57067             if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
57068                 return;
57069             }
57070             var diagnosticMessage;
57071             var declarationName = ts.idText(right);
57072             if (isInPropertyInitializer(node)
57073                 && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
57074                 && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
57075                 && !isPropertyDeclaredInAncestorClass(prop)) {
57076                 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
57077             }
57078             else if (valueDeclaration.kind === 245 /* ClassDeclaration */ &&
57079                 node.parent.kind !== 169 /* TypeReference */ &&
57080                 !(valueDeclaration.flags & 8388608 /* Ambient */) &&
57081                 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
57082                 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
57083             }
57084             if (diagnosticMessage) {
57085                 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
57086             }
57087         }
57088         function isInPropertyInitializer(node) {
57089             return !!ts.findAncestor(node, function (node) {
57090                 switch (node.kind) {
57091                     case 159 /* PropertyDeclaration */:
57092                         return true;
57093                     case 281 /* PropertyAssignment */:
57094                     case 161 /* MethodDeclaration */:
57095                     case 163 /* GetAccessor */:
57096                     case 164 /* SetAccessor */:
57097                     case 283 /* SpreadAssignment */:
57098                     case 154 /* ComputedPropertyName */:
57099                     case 221 /* TemplateSpan */:
57100                     case 276 /* JsxExpression */:
57101                     case 273 /* JsxAttribute */:
57102                     case 274 /* JsxAttributes */:
57103                     case 275 /* JsxSpreadAttribute */:
57104                     case 268 /* JsxOpeningElement */:
57105                     case 216 /* ExpressionWithTypeArguments */:
57106                     case 279 /* HeritageClause */:
57107                         return false;
57108                     default:
57109                         return ts.isExpressionNode(node) ? false : "quit";
57110                 }
57111             });
57112         }
57113         /**
57114          * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
57115          * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
57116          */
57117         function isPropertyDeclaredInAncestorClass(prop) {
57118             if (!(prop.parent.flags & 32 /* Class */)) {
57119                 return false;
57120             }
57121             var classType = getTypeOfSymbol(prop.parent);
57122             while (true) {
57123                 classType = classType.symbol && getSuperClass(classType);
57124                 if (!classType) {
57125                     return false;
57126                 }
57127                 var superProperty = getPropertyOfType(classType, prop.escapedName);
57128                 if (superProperty && superProperty.valueDeclaration) {
57129                     return true;
57130                 }
57131             }
57132         }
57133         function getSuperClass(classType) {
57134             var x = getBaseTypes(classType);
57135             if (x.length === 0) {
57136                 return undefined;
57137             }
57138             return getIntersectionType(x);
57139         }
57140         function reportNonexistentProperty(propNode, containingType) {
57141             var errorInfo;
57142             var relatedInfo;
57143             if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
57144                 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
57145                     var subtype = _a[_i];
57146                     if (!getPropertyOfType(subtype, propNode.escapedText) && !getIndexInfoOfType(subtype, 0 /* String */)) {
57147                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
57148                         break;
57149                     }
57150                 }
57151             }
57152             if (typeHasStaticProperty(propNode.escapedText, containingType)) {
57153                 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57154             }
57155             else {
57156                 var promisedType = getPromisedTypeOfPromise(containingType);
57157                 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
57158                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57159                     relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
57160                 }
57161                 else {
57162                     var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
57163                     if (suggestion !== undefined) {
57164                         var suggestedName = ts.symbolName(suggestion);
57165                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName);
57166                         relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
57167                     }
57168                     else {
57169                         errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57170                     }
57171                 }
57172             }
57173             var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
57174             if (relatedInfo) {
57175                 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
57176             }
57177             diagnostics.add(resultDiagnostic);
57178         }
57179         function typeHasStaticProperty(propName, containingType) {
57180             var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
57181             return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */);
57182         }
57183         function getSuggestedSymbolForNonexistentProperty(name, containingType) {
57184             return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */);
57185         }
57186         function getSuggestionForNonexistentProperty(name, containingType) {
57187             var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
57188             return suggestion && ts.symbolName(suggestion);
57189         }
57190         function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
57191             ts.Debug.assert(outerName !== undefined, "outername should always be defined");
57192             var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
57193                 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
57194                 var symbol = getSymbol(symbols, name, meaning);
57195                 // 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
57196                 // So the table *contains* `x` but `x` isn't actually in scope.
57197                 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
57198                 return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
57199             });
57200             return result;
57201         }
57202         function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
57203             var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
57204             return symbolResult && ts.symbolName(symbolResult);
57205         }
57206         function getSuggestedSymbolForNonexistentModule(name, targetModule) {
57207             return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
57208         }
57209         function getSuggestionForNonexistentExport(name, targetModule) {
57210             var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
57211             return suggestion && ts.symbolName(suggestion);
57212         }
57213         function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
57214             // check if object type has setter or getter
57215             function hasProp(name) {
57216                 var prop = getPropertyOfObjectType(objectType, name);
57217                 if (prop) {
57218                     var s = getSingleCallSignature(getTypeOfSymbol(prop));
57219                     return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
57220                 }
57221                 return false;
57222             }
57223             ;
57224             var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
57225             if (!hasProp(suggestedMethod)) {
57226                 return undefined;
57227             }
57228             var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
57229             if (suggestion === undefined) {
57230                 suggestion = suggestedMethod;
57231             }
57232             else {
57233                 suggestion += "." + suggestedMethod;
57234             }
57235             return suggestion;
57236         }
57237         /**
57238          * 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.
57239          * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
57240          *
57241          * If there is a candidate that's the same except for case, return that.
57242          * If there is a candidate that's within one edit of the name, return that.
57243          * Otherwise, return the candidate with the smallest Levenshtein distance,
57244          *    except for candidates:
57245          *      * With no name
57246          *      * Whose meaning doesn't match the `meaning` parameter.
57247          *      * Whose length differs from the target name by more than 0.34 of the length of the name.
57248          *      * Whose levenshtein distance is more than 0.4 of the length of the name
57249          *        (0.4 allows 1 substitution/transposition for every 5 characters,
57250          *         and 1 insertion/deletion at 3 characters)
57251          */
57252         function getSpellingSuggestionForName(name, symbols, meaning) {
57253             return ts.getSpellingSuggestion(name, symbols, getCandidateName);
57254             function getCandidateName(candidate) {
57255                 var candidateName = ts.symbolName(candidate);
57256                 if (ts.startsWith(candidateName, "\"")) {
57257                     return undefined;
57258                 }
57259                 if (candidate.flags & meaning) {
57260                     return candidateName;
57261                 }
57262                 if (candidate.flags & 2097152 /* Alias */) {
57263                     var alias = tryResolveAlias(candidate);
57264                     if (alias && alias.flags & meaning) {
57265                         return candidateName;
57266                     }
57267                 }
57268                 return undefined;
57269             }
57270         }
57271         function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
57272             var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
57273             if (!valueDeclaration) {
57274                 return;
57275             }
57276             var hasPrivateModifier = ts.hasModifier(valueDeclaration, 8 /* Private */);
57277             var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
57278             if (!hasPrivateModifier && !hasPrivateIdentifier) {
57279                 return;
57280             }
57281             if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
57282                 return;
57283             }
57284             if (isThisAccess) {
57285                 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
57286                 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
57287                 if (containingMethod && containingMethod.symbol === prop) {
57288                     return;
57289                 }
57290             }
57291             (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
57292         }
57293         function isValidPropertyAccess(node, propertyName) {
57294             switch (node.kind) {
57295                 case 194 /* PropertyAccessExpression */:
57296                     return isValidPropertyAccessWithType(node, node.expression.kind === 102 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
57297                 case 153 /* QualifiedName */:
57298                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
57299                 case 188 /* ImportType */:
57300                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
57301             }
57302         }
57303         function isValidPropertyAccessForCompletions(node, type, property) {
57304             return isValidPropertyAccessWithType(node, node.kind === 194 /* PropertyAccessExpression */ && node.expression.kind === 102 /* SuperKeyword */, property.escapedName, type);
57305             // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
57306         }
57307         function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
57308             if (type === errorType || isTypeAny(type)) {
57309                 return true;
57310             }
57311             var prop = getPropertyOfType(type, propertyName);
57312             if (prop) {
57313                 if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) {
57314                     var declClass_1 = ts.getContainingClass(prop.valueDeclaration);
57315                     return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
57316                 }
57317                 return checkPropertyAccessibility(node, isSuper, type, prop);
57318             }
57319             // In js files properties of unions are allowed in completion
57320             return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
57321         }
57322         /**
57323          * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
57324          */
57325         function getForInVariableSymbol(node) {
57326             var initializer = node.initializer;
57327             if (initializer.kind === 243 /* VariableDeclarationList */) {
57328                 var variable = initializer.declarations[0];
57329                 if (variable && !ts.isBindingPattern(variable.name)) {
57330                     return getSymbolOfNode(variable);
57331                 }
57332             }
57333             else if (initializer.kind === 75 /* Identifier */) {
57334                 return getResolvedSymbol(initializer);
57335             }
57336             return undefined;
57337         }
57338         /**
57339          * Return true if the given type is considered to have numeric property names.
57340          */
57341         function hasNumericPropertyNames(type) {
57342             return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
57343         }
57344         /**
57345          * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
57346          * that references a for-in variable for an object with numeric property names.
57347          */
57348         function isForInVariableForNumericPropertyNames(expr) {
57349             var e = ts.skipParentheses(expr);
57350             if (e.kind === 75 /* Identifier */) {
57351                 var symbol = getResolvedSymbol(e);
57352                 if (symbol.flags & 3 /* Variable */) {
57353                     var child = expr;
57354                     var node = expr.parent;
57355                     while (node) {
57356                         if (node.kind === 231 /* ForInStatement */ &&
57357                             child === node.statement &&
57358                             getForInVariableSymbol(node) === symbol &&
57359                             hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
57360                             return true;
57361                         }
57362                         child = node;
57363                         node = node.parent;
57364                     }
57365                 }
57366             }
57367             return false;
57368         }
57369         function checkIndexedAccess(node) {
57370             return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) :
57371                 checkElementAccessExpression(node, checkNonNullExpression(node.expression));
57372         }
57373         function checkElementAccessChain(node) {
57374             var exprType = checkExpression(node.expression);
57375             var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
57376             return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType);
57377         }
57378         function checkElementAccessExpression(node, exprType) {
57379             var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
57380             var indexExpression = node.argumentExpression;
57381             var indexType = checkExpression(indexExpression);
57382             if (objectType === errorType || objectType === silentNeverType) {
57383                 return objectType;
57384             }
57385             if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
57386                 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
57387                 return errorType;
57388             }
57389             var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
57390             var accessFlags = ts.isAssignmentTarget(node) ?
57391                 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) :
57392                 0 /* None */;
57393             var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType;
57394             return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node);
57395         }
57396         function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
57397             if (expressionType === errorType) {
57398                 // There is already an error, so no need to report one.
57399                 return false;
57400             }
57401             if (!ts.isWellKnownSymbolSyntactically(expression)) {
57402                 return false;
57403             }
57404             // Make sure the property type is the primitive symbol type
57405             if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
57406                 if (reportError) {
57407                     error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
57408                 }
57409                 return false;
57410             }
57411             // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
57412             // global Symbol object
57413             var leftHandSide = expression.expression;
57414             var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
57415             if (!leftHandSideSymbol) {
57416                 return false;
57417             }
57418             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
57419             if (!globalESSymbol) {
57420                 // Already errored when we tried to look up the symbol
57421                 return false;
57422             }
57423             if (leftHandSideSymbol !== globalESSymbol) {
57424                 if (reportError) {
57425                     error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
57426                 }
57427                 return false;
57428             }
57429             return true;
57430         }
57431         function callLikeExpressionMayHaveTypeArguments(node) {
57432             return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
57433         }
57434         function resolveUntypedCall(node) {
57435             if (callLikeExpressionMayHaveTypeArguments(node)) {
57436                 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
57437                 // This gets us diagnostics for the type arguments and marks them as referenced.
57438                 ts.forEach(node.typeArguments, checkSourceElement);
57439             }
57440             if (node.kind === 198 /* TaggedTemplateExpression */) {
57441                 checkExpression(node.template);
57442             }
57443             else if (ts.isJsxOpeningLikeElement(node)) {
57444                 checkExpression(node.attributes);
57445             }
57446             else if (node.kind !== 157 /* Decorator */) {
57447                 ts.forEach(node.arguments, function (argument) {
57448                     checkExpression(argument);
57449                 });
57450             }
57451             return anySignature;
57452         }
57453         function resolveErrorCall(node) {
57454             resolveUntypedCall(node);
57455             return unknownSignature;
57456         }
57457         // Re-order candidate signatures into the result array. Assumes the result array to be empty.
57458         // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
57459         // A nit here is that we reorder only signatures that belong to the same symbol,
57460         // so order how inherited signatures are processed is still preserved.
57461         // interface A { (x: string): void }
57462         // interface B extends A { (x: 'foo'): string }
57463         // const b: B;
57464         // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
57465         function reorderCandidates(signatures, result, callChainFlags) {
57466             var lastParent;
57467             var lastSymbol;
57468             var cutoffIndex = 0;
57469             var index;
57470             var specializedIndex = -1;
57471             var spliceIndex;
57472             ts.Debug.assert(!result.length);
57473             for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
57474                 var signature = signatures_7[_i];
57475                 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
57476                 var parent = signature.declaration && signature.declaration.parent;
57477                 if (!lastSymbol || symbol === lastSymbol) {
57478                     if (lastParent && parent === lastParent) {
57479                         index = index + 1;
57480                     }
57481                     else {
57482                         lastParent = parent;
57483                         index = cutoffIndex;
57484                     }
57485                 }
57486                 else {
57487                     // current declaration belongs to a different symbol
57488                     // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
57489                     index = cutoffIndex = result.length;
57490                     lastParent = parent;
57491                 }
57492                 lastSymbol = symbol;
57493                 // specialized signatures always need to be placed before non-specialized signatures regardless
57494                 // of the cutoff position; see GH#1133
57495                 if (signatureHasLiteralTypes(signature)) {
57496                     specializedIndex++;
57497                     spliceIndex = specializedIndex;
57498                     // The cutoff index always needs to be greater than or equal to the specialized signature index
57499                     // in order to prevent non-specialized signatures from being added before a specialized
57500                     // signature.
57501                     cutoffIndex++;
57502                 }
57503                 else {
57504                     spliceIndex = index;
57505                 }
57506                 result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
57507             }
57508         }
57509         function isSpreadArgument(arg) {
57510             return !!arg && (arg.kind === 213 /* SpreadElement */ || arg.kind === 220 /* SyntheticExpression */ && arg.isSpread);
57511         }
57512         function getSpreadArgumentIndex(args) {
57513             return ts.findIndex(args, isSpreadArgument);
57514         }
57515         function acceptsVoid(t) {
57516             return !!(t.flags & 16384 /* Void */);
57517         }
57518         function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
57519             if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
57520             var argCount;
57521             var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
57522             var effectiveParameterCount = getParameterCount(signature);
57523             var effectiveMinimumArguments = getMinArgumentCount(signature);
57524             if (node.kind === 198 /* TaggedTemplateExpression */) {
57525                 argCount = args.length;
57526                 if (node.template.kind === 211 /* TemplateExpression */) {
57527                     // If a tagged template expression lacks a tail literal, the call is incomplete.
57528                     // Specifically, a template only can end in a TemplateTail or a Missing literal.
57529                     var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
57530                     callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
57531                 }
57532                 else {
57533                     // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
57534                     // then this might actually turn out to be a TemplateHead in the future;
57535                     // so we consider the call to be incomplete.
57536                     var templateLiteral = node.template;
57537                     ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
57538                     callIsIncomplete = !!templateLiteral.isUnterminated;
57539                 }
57540             }
57541             else if (node.kind === 157 /* Decorator */) {
57542                 argCount = getDecoratorArgumentCount(node, signature);
57543             }
57544             else if (ts.isJsxOpeningLikeElement(node)) {
57545                 callIsIncomplete = node.attributes.end === node.end;
57546                 if (callIsIncomplete) {
57547                     return true;
57548                 }
57549                 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
57550                 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
57551                 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
57552             }
57553             else {
57554                 if (!node.arguments) {
57555                     // This only happens when we have something of the form: 'new C'
57556                     ts.Debug.assert(node.kind === 197 /* NewExpression */);
57557                     return getMinArgumentCount(signature) === 0;
57558                 }
57559                 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
57560                 // If we are missing the close parenthesis, the call is incomplete.
57561                 callIsIncomplete = node.arguments.end === node.end;
57562                 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
57563                 var spreadArgIndex = getSpreadArgumentIndex(args);
57564                 if (spreadArgIndex >= 0) {
57565                     return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
57566                 }
57567             }
57568             // Too many arguments implies incorrect arity.
57569             if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
57570                 return false;
57571             }
57572             // If the call is incomplete, we should skip the lower bound check.
57573             // JSX signatures can have extra parameters provided by the library which we don't check
57574             if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
57575                 return true;
57576             }
57577             for (var i = argCount; i < effectiveMinimumArguments; i++) {
57578                 var type = getTypeAtPosition(signature, i);
57579                 if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
57580                     return false;
57581                 }
57582             }
57583             return true;
57584         }
57585         function hasCorrectTypeArgumentArity(signature, typeArguments) {
57586             // If the user supplied type arguments, but the number of type arguments does not match
57587             // the declared number of type parameters, the call has an incorrect arity.
57588             var numTypeParameters = ts.length(signature.typeParameters);
57589             var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
57590             return !ts.some(typeArguments) ||
57591                 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
57592         }
57593         // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
57594         function getSingleCallSignature(type) {
57595             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
57596         }
57597         function getSingleCallOrConstructSignature(type) {
57598             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
57599                 getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
57600         }
57601         function getSingleSignature(type, kind, allowMembers) {
57602             if (type.flags & 524288 /* Object */) {
57603                 var resolved = resolveStructuredTypeMembers(type);
57604                 if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
57605                     if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
57606                         return resolved.callSignatures[0];
57607                     }
57608                     if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
57609                         return resolved.constructSignatures[0];
57610                     }
57611                 }
57612             }
57613             return undefined;
57614         }
57615         // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
57616         function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
57617             var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
57618             // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
57619             // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
57620             // for T but leave it possible to later infer '[any]' back to A.
57621             var restType = getEffectiveRestType(contextualSignature);
57622             var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
57623             var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
57624             applyToParameterTypes(sourceSignature, signature, function (source, target) {
57625                 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
57626                 inferTypes(context.inferences, source, target);
57627             });
57628             if (!inferenceContext) {
57629                 applyToReturnTypes(contextualSignature, signature, function (source, target) {
57630                     inferTypes(context.inferences, source, target, 32 /* ReturnType */);
57631                 });
57632             }
57633             return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
57634         }
57635         function inferJsxTypeArguments(node, signature, checkMode, context) {
57636             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57637             var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
57638             inferTypes(context.inferences, checkAttrType, paramType);
57639             return getInferredTypes(context);
57640         }
57641         function inferTypeArguments(node, signature, args, checkMode, context) {
57642             if (ts.isJsxOpeningLikeElement(node)) {
57643                 return inferJsxTypeArguments(node, signature, checkMode, context);
57644             }
57645             // If a contextual type is available, infer from that type to the return type of the call expression. For
57646             // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
57647             // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
57648             // return type of 'wrap'.
57649             if (node.kind !== 157 /* Decorator */) {
57650                 var contextualType = getContextualType(node);
57651                 if (contextualType) {
57652                     // We clone the inference context to avoid disturbing a resolution in progress for an
57653                     // outer call expression. Effectively we just want a snapshot of whatever has been
57654                     // inferred for any outer call expression so far.
57655                     var outerContext = getInferenceContext(node);
57656                     var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
57657                     var instantiatedType = instantiateType(contextualType, outerMapper);
57658                     // If the contextual type is a generic function type with a single call signature, we
57659                     // instantiate the type with its own type parameters and type arguments. This ensures that
57660                     // the type parameters are not erased to type any during type inference such that they can
57661                     // be inferred as actual types from the contextual type. For example:
57662                     //   declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
57663                     //   const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
57664                     // Above, the type of the 'value' parameter is inferred to be 'A'.
57665                     var contextualSignature = getSingleCallSignature(instantiatedType);
57666                     var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
57667                         getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
57668                         instantiatedType;
57669                     var inferenceTargetType = getReturnTypeOfSignature(signature);
57670                     // Inferences made from return types have lower priority than all other inferences.
57671                     inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 32 /* ReturnType */);
57672                     // Create a type mapper for instantiating generic contextual types using the inferences made
57673                     // from the return type. We need a separate inference pass here because (a) instantiation of
57674                     // the source type uses the outer context's return mapper (which excludes inferences made from
57675                     // outer arguments), and (b) we don't want any further inferences going into this context.
57676                     var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
57677                     var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
57678                     inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
57679                     context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
57680                 }
57681             }
57682             var thisType = getThisTypeOfSignature(signature);
57683             if (thisType) {
57684                 var thisArgumentNode = getThisArgumentOfCall(node);
57685                 var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
57686                 inferTypes(context.inferences, thisArgumentType, thisType);
57687             }
57688             var restType = getNonArrayRestType(signature);
57689             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
57690             for (var i = 0; i < argCount; i++) {
57691                 var arg = args[i];
57692                 if (arg.kind !== 215 /* OmittedExpression */) {
57693                     var paramType = getTypeAtPosition(signature, i);
57694                     var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
57695                     inferTypes(context.inferences, argType, paramType);
57696                 }
57697             }
57698             if (restType) {
57699                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context);
57700                 inferTypes(context.inferences, spreadType, restType);
57701             }
57702             return getInferredTypes(context);
57703         }
57704         function getArrayifiedType(type) {
57705             return type.flags & 1048576 /* Union */ ? mapType(type, getArrayifiedType) :
57706                 type.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isMutableArrayOrTuple(type) ? type :
57707                     isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.minLength, type.target.hasRestElement, /*readonly*/ false, type.target.associatedNames) :
57708                         createArrayType(getIndexedAccessType(type, numberType));
57709         }
57710         function getSpreadArgumentType(args, index, argCount, restType, context) {
57711             if (index >= argCount - 1) {
57712                 var arg = args[argCount - 1];
57713                 if (isSpreadArgument(arg)) {
57714                     // We are inferring from a spread expression in the last argument position, i.e. both the parameter
57715                     // and the argument are ...x forms.
57716                     return arg.kind === 220 /* SyntheticExpression */ ?
57717                         createArrayType(arg.type) :
57718                         getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
57719                 }
57720             }
57721             var types = [];
57722             var spreadIndex = -1;
57723             for (var i = index; i < argCount; i++) {
57724                 var contextualType = getIndexedAccessType(restType, getLiteralType(i - index));
57725                 var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
57726                 if (spreadIndex < 0 && isSpreadArgument(args[i])) {
57727                     spreadIndex = i - index;
57728                 }
57729                 var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */);
57730                 types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
57731             }
57732             return spreadIndex < 0 ?
57733                 createTupleType(types) :
57734                 createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true);
57735         }
57736         function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
57737             var isJavascript = ts.isInJSFile(signature.declaration);
57738             var typeParameters = signature.typeParameters;
57739             var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
57740             var mapper;
57741             for (var i = 0; i < typeArgumentNodes.length; i++) {
57742                 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
57743                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
57744                 if (constraint) {
57745                     var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
57746                     var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
57747                     if (!mapper) {
57748                         mapper = createTypeMapper(typeParameters, typeArgumentTypes);
57749                     }
57750                     var typeArgument = typeArgumentTypes[i];
57751                     if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
57752                         return undefined;
57753                     }
57754                 }
57755             }
57756             return typeArgumentTypes;
57757         }
57758         function getJsxReferenceKind(node) {
57759             if (isJsxIntrinsicIdentifier(node.tagName)) {
57760                 return 2 /* Mixed */;
57761             }
57762             var tagType = getApparentType(checkExpression(node.tagName));
57763             if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
57764                 return 0 /* Component */;
57765             }
57766             if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
57767                 return 1 /* Function */;
57768             }
57769             return 2 /* Mixed */;
57770         }
57771         /**
57772          * Check if the given signature can possibly be a signature called by the JSX opening-like element.
57773          * @param node a JSX opening-like element we are trying to figure its call signature
57774          * @param signature a candidate signature we are trying whether it is a call signature
57775          * @param relation a relationship to check parameter and argument type
57776          */
57777         function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
57778             // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
57779             // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
57780             // can be specified by users through attributes property.
57781             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57782             var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
57783             return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, 
57784             /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
57785             function checkTagNameDoesNotExpectTooManyArguments() {
57786                 var _a;
57787                 var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
57788                 if (!tagType) {
57789                     return true;
57790                 }
57791                 var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
57792                 if (!ts.length(tagCallSignatures)) {
57793                     return true;
57794                 }
57795                 var factory = getJsxFactoryEntity(node);
57796                 if (!factory) {
57797                     return true;
57798                 }
57799                 var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node);
57800                 if (!factorySymbol) {
57801                     return true;
57802                 }
57803                 var factoryType = getTypeOfSymbol(factorySymbol);
57804                 var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
57805                 if (!ts.length(callSignatures)) {
57806                     return true;
57807                 }
57808                 var hasFirstParamSignatures = false;
57809                 var maxParamCount = 0;
57810                 // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments
57811                 for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) {
57812                     var sig = callSignatures_1[_i];
57813                     var firstparam = getTypeAtPosition(sig, 0);
57814                     var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
57815                     if (!ts.length(signaturesOfParam))
57816                         continue;
57817                     for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) {
57818                         var paramSig = signaturesOfParam_1[_b];
57819                         hasFirstParamSignatures = true;
57820                         if (hasEffectiveRestParameter(paramSig)) {
57821                             return true; // some signature has a rest param, so function components can have an arbitrary number of arguments
57822                         }
57823                         var paramCount = getParameterCount(paramSig);
57824                         if (paramCount > maxParamCount) {
57825                             maxParamCount = paramCount;
57826                         }
57827                     }
57828                 }
57829                 if (!hasFirstParamSignatures) {
57830                     // Not a single signature had a first parameter which expected a signature - for back compat, and
57831                     // to guard against generic factories which won't have signatures directly, do not error
57832                     return true;
57833                 }
57834                 var absoluteMinArgCount = Infinity;
57835                 for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) {
57836                     var tagSig = tagCallSignatures_1[_c];
57837                     var tagRequiredArgCount = getMinArgumentCount(tagSig);
57838                     if (tagRequiredArgCount < absoluteMinArgCount) {
57839                         absoluteMinArgCount = tagRequiredArgCount;
57840                     }
57841                 }
57842                 if (absoluteMinArgCount <= maxParamCount) {
57843                     return true; // some signature accepts the number of arguments the function component provides
57844                 }
57845                 if (reportErrors) {
57846                     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);
57847                     var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
57848                     if (tagNameDeclaration) {
57849                         ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName)));
57850                     }
57851                     if (errorOutputContainer && errorOutputContainer.skipLogging) {
57852                         (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
57853                     }
57854                     if (!errorOutputContainer.skipLogging) {
57855                         diagnostics.add(diag);
57856                     }
57857                 }
57858                 return false;
57859             }
57860         }
57861         function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
57862             var errorOutputContainer = { errors: undefined, skipLogging: true };
57863             if (ts.isJsxOpeningLikeElement(node)) {
57864                 if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
57865                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
57866                     return errorOutputContainer.errors || ts.emptyArray;
57867                 }
57868                 return undefined;
57869             }
57870             var thisType = getThisTypeOfSignature(signature);
57871             if (thisType && thisType !== voidType && node.kind !== 197 /* NewExpression */) {
57872                 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
57873                 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
57874                 // If the expression is a new expression, then the check is skipped.
57875                 var thisArgumentNode = getThisArgumentOfCall(node);
57876                 var thisArgumentType = void 0;
57877                 if (thisArgumentNode) {
57878                     thisArgumentType = checkExpression(thisArgumentNode);
57879                     if (ts.isOptionalChainRoot(thisArgumentNode.parent)) {
57880                         thisArgumentType = getNonNullableType(thisArgumentType);
57881                     }
57882                     else if (ts.isOptionalChain(thisArgumentNode.parent)) {
57883                         thisArgumentType = removeOptionalTypeMarker(thisArgumentType);
57884                     }
57885                 }
57886                 else {
57887                     thisArgumentType = voidType;
57888                 }
57889                 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
57890                 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
57891                 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
57892                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
57893                     return errorOutputContainer.errors || ts.emptyArray;
57894                 }
57895             }
57896             var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
57897             var restType = getNonArrayRestType(signature);
57898             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
57899             for (var i = 0; i < argCount; i++) {
57900                 var arg = args[i];
57901                 if (arg.kind !== 215 /* OmittedExpression */) {
57902                     var paramType = getTypeAtPosition(signature, i);
57903                     var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
57904                     // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
57905                     // we obtain the regular type of any object literal arguments because we may not have inferred complete
57906                     // parameter types yet and therefore excess property checks may yield false positives (see #17041).
57907                     var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
57908                     if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
57909                         ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
57910                         maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
57911                         return errorOutputContainer.errors || ts.emptyArray;
57912                     }
57913                 }
57914             }
57915             if (restType) {
57916                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined);
57917                 var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
57918                 if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
57919                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
57920                     maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
57921                     return errorOutputContainer.errors || ts.emptyArray;
57922                 }
57923             }
57924             return undefined;
57925             function maybeAddMissingAwaitInfo(errorNode, source, target) {
57926                 if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
57927                     // Bail if target is Promise-like---something else is wrong
57928                     if (getAwaitedTypeOfPromise(target)) {
57929                         return;
57930                     }
57931                     var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
57932                     if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
57933                         ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
57934                     }
57935                 }
57936             }
57937         }
57938         /**
57939          * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
57940          */
57941         function getThisArgumentOfCall(node) {
57942             if (node.kind === 196 /* CallExpression */) {
57943                 var callee = ts.skipOuterExpressions(node.expression);
57944                 if (ts.isAccessExpression(callee)) {
57945                     return callee.expression;
57946                 }
57947             }
57948         }
57949         function createSyntheticExpression(parent, type, isSpread) {
57950             var result = ts.createNode(220 /* SyntheticExpression */, parent.pos, parent.end);
57951             result.parent = parent;
57952             result.type = type;
57953             result.isSpread = isSpread || false;
57954             return result;
57955         }
57956         /**
57957          * Returns the effective arguments for an expression that works like a function invocation.
57958          */
57959         function getEffectiveCallArguments(node) {
57960             if (node.kind === 198 /* TaggedTemplateExpression */) {
57961                 var template = node.template;
57962                 var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
57963                 if (template.kind === 211 /* TemplateExpression */) {
57964                     ts.forEach(template.templateSpans, function (span) {
57965                         args_3.push(span.expression);
57966                     });
57967                 }
57968                 return args_3;
57969             }
57970             if (node.kind === 157 /* Decorator */) {
57971                 return getEffectiveDecoratorArguments(node);
57972             }
57973             if (ts.isJsxOpeningLikeElement(node)) {
57974                 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
57975             }
57976             var args = node.arguments || ts.emptyArray;
57977             var length = args.length;
57978             if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) {
57979                 // We have a spread argument in the last position and no other spread arguments. If the type
57980                 // of the argument is a tuple type, spread the tuple elements into the argument list. We can
57981                 // call checkExpressionCached because spread expressions never have a contextual type.
57982                 var spreadArgument_1 = args[length - 1];
57983                 var type = flowLoopCount ? checkExpression(spreadArgument_1.expression) : checkExpressionCached(spreadArgument_1.expression);
57984                 if (isTupleType(type)) {
57985                     var typeArguments = getTypeArguments(type);
57986                     var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1;
57987                     var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); });
57988                     return ts.concatenate(args.slice(0, length - 1), syntheticArgs);
57989                 }
57990             }
57991             return args;
57992         }
57993         /**
57994          * Returns the synthetic argument list for a decorator invocation.
57995          */
57996         function getEffectiveDecoratorArguments(node) {
57997             var parent = node.parent;
57998             var expr = node.expression;
57999             switch (parent.kind) {
58000                 case 245 /* ClassDeclaration */:
58001                 case 214 /* ClassExpression */:
58002                     // For a class decorator, the `target` is the type of the class (e.g. the
58003                     // "static" or "constructor" side of the class).
58004                     return [
58005                         createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
58006                     ];
58007                 case 156 /* Parameter */:
58008                     // A parameter declaration decorator will have three arguments (see
58009                     // `ParameterDecorator` in core.d.ts).
58010                     var func = parent.parent;
58011                     return [
58012                         createSyntheticExpression(expr, parent.parent.kind === 162 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
58013                         createSyntheticExpression(expr, anyType),
58014                         createSyntheticExpression(expr, numberType)
58015                     ];
58016                 case 159 /* PropertyDeclaration */:
58017                 case 161 /* MethodDeclaration */:
58018                 case 163 /* GetAccessor */:
58019                 case 164 /* SetAccessor */:
58020                     // A method or accessor declaration decorator will have two or three arguments (see
58021                     // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
58022                     // for ES3, we will only pass two arguments.
58023                     var hasPropDesc = parent.kind !== 159 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
58024                     return [
58025                         createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
58026                         createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
58027                         createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
58028                     ];
58029             }
58030             return ts.Debug.fail();
58031         }
58032         /**
58033          * Returns the argument count for a decorator node that works like a function invocation.
58034          */
58035         function getDecoratorArgumentCount(node, signature) {
58036             switch (node.parent.kind) {
58037                 case 245 /* ClassDeclaration */:
58038                 case 214 /* ClassExpression */:
58039                     return 1;
58040                 case 159 /* PropertyDeclaration */:
58041                     return 2;
58042                 case 161 /* MethodDeclaration */:
58043                 case 163 /* GetAccessor */:
58044                 case 164 /* SetAccessor */:
58045                     // For ES3 or decorators with only two parameters we supply only two arguments
58046                     return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
58047                 case 156 /* Parameter */:
58048                     return 3;
58049                 default:
58050                     return ts.Debug.fail();
58051             }
58052         }
58053         function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
58054             var start;
58055             var length;
58056             var sourceFile = ts.getSourceFileOfNode(node);
58057             if (ts.isPropertyAccessExpression(node.expression)) {
58058                 var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
58059                 start = nameSpan.start;
58060                 length = doNotIncludeArguments ? nameSpan.length : node.end - start;
58061             }
58062             else {
58063                 var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
58064                 start = expressionSpan.start;
58065                 length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
58066             }
58067             return { start: start, length: length, sourceFile: sourceFile };
58068         }
58069         function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
58070             if (ts.isCallExpression(node)) {
58071                 var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length;
58072                 return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3);
58073             }
58074             else {
58075                 return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
58076             }
58077         }
58078         function getArgumentArityError(node, signatures, args) {
58079             var min = Number.POSITIVE_INFINITY;
58080             var max = Number.NEGATIVE_INFINITY;
58081             var belowArgCount = Number.NEGATIVE_INFINITY;
58082             var aboveArgCount = Number.POSITIVE_INFINITY;
58083             var argCount = args.length;
58084             var closestSignature;
58085             for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
58086                 var sig = signatures_8[_i];
58087                 var minCount = getMinArgumentCount(sig);
58088                 var maxCount = getParameterCount(sig);
58089                 if (minCount < argCount && minCount > belowArgCount)
58090                     belowArgCount = minCount;
58091                 if (argCount < maxCount && maxCount < aboveArgCount)
58092                     aboveArgCount = maxCount;
58093                 if (minCount < min) {
58094                     min = minCount;
58095                     closestSignature = sig;
58096                 }
58097                 max = Math.max(max, maxCount);
58098             }
58099             var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
58100             var paramRange = hasRestParameter ? min :
58101                 min < max ? min + "-" + max :
58102                     min;
58103             var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
58104             if (argCount <= max && hasSpreadArgument) {
58105                 argCount--;
58106             }
58107             var spanArray;
58108             var related;
58109             var error = hasRestParameter || hasSpreadArgument ? hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
58110                 hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
58111                     ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1;
58112             if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
58113                 var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
58114                 if (paramDecl) {
58115                     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);
58116                 }
58117             }
58118             if (min < argCount && argCount < max) {
58119                 return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
58120             }
58121             if (!hasSpreadArgument && argCount < min) {
58122                 var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount);
58123                 return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
58124             }
58125             if (hasRestParameter || hasSpreadArgument) {
58126                 spanArray = ts.createNodeArray(args);
58127                 if (hasSpreadArgument && argCount) {
58128                     var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
58129                     spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
58130                 }
58131             }
58132             else {
58133                 spanArray = ts.createNodeArray(args.slice(max));
58134             }
58135             spanArray.pos = ts.first(spanArray).pos;
58136             spanArray.end = ts.last(spanArray).end;
58137             if (spanArray.end === spanArray.pos) {
58138                 spanArray.end++;
58139             }
58140             var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
58141             return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
58142         }
58143         function getTypeArgumentArityError(node, signatures, typeArguments) {
58144             var argCount = typeArguments.length;
58145             // No overloads exist
58146             if (signatures.length === 1) {
58147                 var sig = signatures[0];
58148                 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
58149                 var max = ts.length(sig.typeParameters);
58150                 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);
58151             }
58152             // Overloads exist
58153             var belowArgCount = -Infinity;
58154             var aboveArgCount = Infinity;
58155             for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
58156                 var sig = signatures_9[_i];
58157                 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
58158                 var max = ts.length(sig.typeParameters);
58159                 if (min_2 > argCount) {
58160                     aboveArgCount = Math.min(aboveArgCount, min_2);
58161                 }
58162                 else if (max < argCount) {
58163                     belowArgCount = Math.max(belowArgCount, max);
58164                 }
58165             }
58166             if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
58167                 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);
58168             }
58169             return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
58170         }
58171         function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
58172             var isTaggedTemplate = node.kind === 198 /* TaggedTemplateExpression */;
58173             var isDecorator = node.kind === 157 /* Decorator */;
58174             var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
58175             var reportErrors = !candidatesOutArray;
58176             var typeArguments;
58177             if (!isDecorator) {
58178                 typeArguments = node.typeArguments;
58179                 // We already perform checking on the type arguments on the class declaration itself.
58180                 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 102 /* SuperKeyword */) {
58181                     ts.forEach(typeArguments, checkSourceElement);
58182                 }
58183             }
58184             var candidates = candidatesOutArray || [];
58185             // reorderCandidates fills up the candidates array directly
58186             reorderCandidates(signatures, candidates, callChainFlags);
58187             if (!candidates.length) {
58188                 if (reportErrors) {
58189                     diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
58190                 }
58191                 return resolveErrorCall(node);
58192             }
58193             var args = getEffectiveCallArguments(node);
58194             // The excludeArgument array contains true for each context sensitive argument (an argument
58195             // is context sensitive it is susceptible to a one-time permanent contextual typing).
58196             //
58197             // The idea is that we will perform type argument inference & assignability checking once
58198             // without using the susceptible parameters that are functions, and once more for those
58199             // parameters, contextually typing each as we go along.
58200             //
58201             // For a tagged template, then the first argument be 'undefined' if necessary because it
58202             // represents a TemplateStringsArray.
58203             //
58204             // For a decorator, no arguments are susceptible to contextual typing due to the fact
58205             // decorators are applied to a declaration by the emitter, and not to an expression.
58206             var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
58207             var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
58208             // The following variables are captured and modified by calls to chooseOverload.
58209             // If overload resolution or type argument inference fails, we want to report the
58210             // best error possible. The best error is one which says that an argument was not
58211             // assignable to a parameter. This implies that everything else about the overload
58212             // was fine. So if there is any overload that is only incorrect because of an
58213             // argument, we will report an error on that one.
58214             //
58215             //     function foo(s: string): void;
58216             //     function foo(n: number): void; // Report argument error on this overload
58217             //     function foo(): void;
58218             //     foo(true);
58219             //
58220             // If none of the overloads even made it that far, there are two possibilities.
58221             // There was a problem with type arguments for some overload, in which case
58222             // report an error on that. Or none of the overloads even had correct arity,
58223             // in which case give an arity error.
58224             //
58225             //     function foo<T extends string>(x: T): void; // Report type argument error
58226             //     function foo(): void;
58227             //     foo<number>(0);
58228             //
58229             var candidatesForArgumentError;
58230             var candidateForArgumentArityError;
58231             var candidateForTypeArgumentError;
58232             var result;
58233             // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
58234             // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
58235             var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 196 /* CallExpression */ && node.arguments.hasTrailingComma;
58236             // Section 4.12.1:
58237             // if the candidate list contains one or more signatures for which the type of each argument
58238             // expression is a subtype of each corresponding parameter type, the return type of the first
58239             // of those signatures becomes the return type of the function call.
58240             // Otherwise, the return type of the first signature in the candidate list becomes the return
58241             // type of the function call.
58242             //
58243             // Whether the call is an error is determined by assignability of the arguments. The subtype pass
58244             // is just important for choosing the best signature. So in the case where there is only one
58245             // signature, the subtype pass is useless. So skipping it is an optimization.
58246             if (candidates.length > 1) {
58247                 result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
58248             }
58249             if (!result) {
58250                 result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma);
58251             }
58252             if (result) {
58253                 return result;
58254             }
58255             // No signatures were applicable. Now report errors based on the last applicable signature with
58256             // no arguments excluded from assignability checks.
58257             // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
58258             // skip the checkApplicableSignature check.
58259             if (reportErrors) {
58260                 if (candidatesForArgumentError) {
58261                     if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
58262                         var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
58263                         var chain_1;
58264                         if (candidatesForArgumentError.length > 3) {
58265                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
58266                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
58267                         }
58268                         var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
58269                         if (diags) {
58270                             for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
58271                                 var d = diags_1[_i];
58272                                 if (last_2.declaration && candidatesForArgumentError.length > 3) {
58273                                     ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
58274                                 }
58275                                 diagnostics.add(d);
58276                             }
58277                         }
58278                         else {
58279                             ts.Debug.fail("No error for last overload signature");
58280                         }
58281                     }
58282                     else {
58283                         var allDiagnostics = [];
58284                         var max = 0;
58285                         var min_3 = Number.MAX_VALUE;
58286                         var minIndex = 0;
58287                         var i_1 = 0;
58288                         var _loop_17 = function (c) {
58289                             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)); };
58290                             var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
58291                             if (diags_2) {
58292                                 if (diags_2.length <= min_3) {
58293                                     min_3 = diags_2.length;
58294                                     minIndex = i_1;
58295                                 }
58296                                 max = Math.max(max, diags_2.length);
58297                                 allDiagnostics.push(diags_2);
58298                             }
58299                             else {
58300                                 ts.Debug.fail("No error for 3 or fewer overload signatures");
58301                             }
58302                             i_1++;
58303                         };
58304                         for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
58305                             var c = candidatesForArgumentError_1[_a];
58306                             _loop_17(c);
58307                         }
58308                         var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
58309                         ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
58310                         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);
58311                         var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; });
58312                         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; })) {
58313                             var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length;
58314                             diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related });
58315                         }
58316                         else {
58317                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related));
58318                         }
58319                     }
58320                 }
58321                 else if (candidateForArgumentArityError) {
58322                     diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
58323                 }
58324                 else if (candidateForTypeArgumentError) {
58325                     checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
58326                 }
58327                 else {
58328                     var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
58329                     if (signaturesWithCorrectTypeArgumentArity.length === 0) {
58330                         diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
58331                     }
58332                     else if (!isDecorator) {
58333                         diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
58334                     }
58335                     else if (fallbackError) {
58336                         diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
58337                     }
58338                 }
58339             }
58340             return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
58341             function chooseOverload(candidates, relation, signatureHelpTrailingComma) {
58342                 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
58343                 candidatesForArgumentError = undefined;
58344                 candidateForArgumentArityError = undefined;
58345                 candidateForTypeArgumentError = undefined;
58346                 if (isSingleNonGenericCandidate) {
58347                     var candidate = candidates[0];
58348                     if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58349                         return undefined;
58350                     }
58351                     if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58352                         candidatesForArgumentError = [candidate];
58353                         return undefined;
58354                     }
58355                     return candidate;
58356                 }
58357                 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
58358                     var candidate = candidates[candidateIndex];
58359                     if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58360                         continue;
58361                     }
58362                     var checkCandidate = void 0;
58363                     var inferenceContext = void 0;
58364                     if (candidate.typeParameters) {
58365                         var typeArgumentTypes = void 0;
58366                         if (ts.some(typeArguments)) {
58367                             typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
58368                             if (!typeArgumentTypes) {
58369                                 candidateForTypeArgumentError = candidate;
58370                                 continue;
58371                             }
58372                         }
58373                         else {
58374                             inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58375                             typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
58376                             argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
58377                         }
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                     else {
58387                         checkCandidate = candidate;
58388                     }
58389                     if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58390                         // Give preference to error candidates that have no rest parameters (as they are more specific)
58391                         (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58392                         continue;
58393                     }
58394                     if (argCheckMode) {
58395                         // If one or more context sensitive arguments were excluded, we start including
58396                         // them now (and keeping do so for any subsequent candidates) and perform a second
58397                         // round of type inference and applicability checking for this particular candidate.
58398                         argCheckMode = 0 /* Normal */;
58399                         if (inferenceContext) {
58400                             var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
58401                             checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
58402                             // If the original signature has a generic rest type, instantiation may produce a
58403                             // signature with different arity and we need to perform another arity check.
58404                             if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
58405                                 candidateForArgumentArityError = checkCandidate;
58406                                 continue;
58407                             }
58408                         }
58409                         if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58410                             // Give preference to error candidates that have no rest parameters (as they are more specific)
58411                             (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58412                             continue;
58413                         }
58414                     }
58415                     candidates[candidateIndex] = checkCandidate;
58416                     return checkCandidate;
58417                 }
58418                 return undefined;
58419             }
58420         }
58421         // No signature was applicable. We have already reported the errors for the invalid signature.
58422         function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
58423             ts.Debug.assert(candidates.length > 0); // Else should not have called this.
58424             checkNodeDeferred(node);
58425             // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
58426             // Don't do this if there is a `candidatesOutArray`,
58427             // because then we want the chosen best candidate to be one of the overloads, not a combination.
58428             return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
58429                 ? pickLongestCandidateSignature(node, candidates, args)
58430                 : createUnionOfSignaturesForOverloadFailure(candidates);
58431         }
58432         function createUnionOfSignaturesForOverloadFailure(candidates) {
58433             var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
58434             var thisParameter;
58435             if (thisParameters.length) {
58436                 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
58437             }
58438             var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
58439             var parameters = [];
58440             var _loop_18 = function (i) {
58441                 var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
58442                     i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
58443                     i < s.parameters.length ? s.parameters[i] : undefined; });
58444                 ts.Debug.assert(symbols.length !== 0);
58445                 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
58446             };
58447             for (var i = 0; i < maxNonRestParam; i++) {
58448                 _loop_18(i);
58449             }
58450             var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
58451             var flags = 0 /* None */;
58452             if (restParameterSymbols.length !== 0) {
58453                 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
58454                 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
58455                 flags |= 1 /* HasRestParameter */;
58456             }
58457             if (candidates.some(signatureHasLiteralTypes)) {
58458                 flags |= 2 /* HasLiteralTypes */;
58459             }
58460             return createSignature(candidates[0].declaration, 
58461             /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
58462             thisParameter, parameters, 
58463             /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), 
58464             /*typePredicate*/ undefined, minArgumentCount, flags);
58465         }
58466         function getNumNonRestParameters(signature) {
58467             var numParams = signature.parameters.length;
58468             return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
58469         }
58470         function createCombinedSymbolFromTypes(sources, types) {
58471             return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
58472         }
58473         function createCombinedSymbolForOverloadFailure(sources, type) {
58474             // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
58475             return createSymbolWithType(ts.first(sources), type);
58476         }
58477         function pickLongestCandidateSignature(node, candidates, args) {
58478             // Pick the longest signature. This way we can get a contextual type for cases like:
58479             //     declare function f(a: { xa: number; xb: number; }, b: number);
58480             //     f({ |
58481             // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
58482             //     declare function f<T>(k: keyof T);
58483             //     f<Foo>("
58484             var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
58485             var candidate = candidates[bestIndex];
58486             var typeParameters = candidate.typeParameters;
58487             if (!typeParameters) {
58488                 return candidate;
58489             }
58490             var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
58491             var instantiated = typeArgumentNodes
58492                 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
58493                 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
58494             candidates[bestIndex] = instantiated;
58495             return instantiated;
58496         }
58497         function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
58498             var typeArguments = typeArgumentNodes.map(getTypeOfNode);
58499             while (typeArguments.length > typeParameters.length) {
58500                 typeArguments.pop();
58501             }
58502             while (typeArguments.length < typeParameters.length) {
58503                 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
58504             }
58505             return typeArguments;
58506         }
58507         function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
58508             var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58509             var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
58510             return createSignatureInstantiation(candidate, typeArgumentTypes);
58511         }
58512         function getLongestCandidateIndex(candidates, argsCount) {
58513             var maxParamsIndex = -1;
58514             var maxParams = -1;
58515             for (var i = 0; i < candidates.length; i++) {
58516                 var candidate = candidates[i];
58517                 var paramCount = getParameterCount(candidate);
58518                 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
58519                     return i;
58520                 }
58521                 if (paramCount > maxParams) {
58522                     maxParams = paramCount;
58523                     maxParamsIndex = i;
58524                 }
58525             }
58526             return maxParamsIndex;
58527         }
58528         function resolveCallExpression(node, candidatesOutArray, checkMode) {
58529             if (node.expression.kind === 102 /* SuperKeyword */) {
58530                 var superType = checkSuperExpression(node.expression);
58531                 if (isTypeAny(superType)) {
58532                     for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
58533                         var arg = _a[_i];
58534                         checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
58535                     }
58536                     return anySignature;
58537                 }
58538                 if (superType !== errorType) {
58539                     // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
58540                     // with the type arguments specified in the extends clause.
58541                     var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
58542                     if (baseTypeNode) {
58543                         var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
58544                         return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
58545                     }
58546                 }
58547                 return resolveUntypedCall(node);
58548             }
58549             var callChainFlags;
58550             var funcType = checkExpression(node.expression);
58551             if (ts.isCallChain(node)) {
58552                 var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
58553                 callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
58554                     ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ :
58555                         4 /* IsInnerCallChain */;
58556                 funcType = nonOptionalType;
58557             }
58558             else {
58559                 callChainFlags = 0 /* None */;
58560             }
58561             funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
58562             if (funcType === silentNeverType) {
58563                 return silentNeverSignature;
58564             }
58565             var apparentType = getApparentType(funcType);
58566             if (apparentType === errorType) {
58567                 // Another error has already been reported
58568                 return resolveErrorCall(node);
58569             }
58570             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58571             // but we are not including call signatures that may have been added to the Object or
58572             // Function interface, since they have none by default. This is a bit of a leap of faith
58573             // that the user will not add any.
58574             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58575             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58576             // TS 1.0 Spec: 4.12
58577             // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
58578             // types are provided for the argument expressions, and the result is always of type Any.
58579             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
58580                 // The unknownType indicates that an error already occurred (and was reported).  No
58581                 // need to report another error in this case.
58582                 if (funcType !== errorType && node.typeArguments) {
58583                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58584                 }
58585                 return resolveUntypedCall(node);
58586             }
58587             // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
58588             // TypeScript employs overload resolution in typed function calls in order to support functions
58589             // with multiple call signatures.
58590             if (!callSignatures.length) {
58591                 if (numConstructSignatures) {
58592                     error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58593                 }
58594                 else {
58595                     var relatedInformation = void 0;
58596                     if (node.arguments.length === 1) {
58597                         var text = ts.getSourceFileOfNode(node).text;
58598                         if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
58599                             relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon);
58600                         }
58601                     }
58602                     invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
58603                 }
58604                 return resolveErrorCall(node);
58605             }
58606             // When a call to a generic function is an argument to an outer call to a generic function for which
58607             // inference is in process, we have a choice to make. If the inner call relies on inferences made from
58608             // its contextual type to its return type, deferring the inner call processing allows the best possible
58609             // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
58610             // the inner call, the inner call should be processed early. There's no sure way to know which choice is
58611             // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
58612             // If no type arguments are specified in the inner call and at least one call signature is generic and
58613             // returns a function type, we choose to defer processing. This narrowly permits function composition
58614             // operators to flow inferences through return types, but otherwise processes calls right away. We
58615             // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
58616             // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
58617             // from which we never make inferences).
58618             if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
58619                 skippedGenericFunction(node, checkMode);
58620                 return resolvingSignature;
58621             }
58622             // If the function is explicitly marked with `@class`, then it must be constructed.
58623             if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
58624                 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58625                 return resolveErrorCall(node);
58626             }
58627             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
58628         }
58629         function isGenericFunctionReturningFunction(signature) {
58630             return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
58631         }
58632         /**
58633          * TS 1.0 spec: 4.12
58634          * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
58635          * but is a subtype of the Function interface, the call is an untyped function call.
58636          */
58637         function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
58638             // We exclude union types because we may have a union of function types that happen to have no common signatures.
58639             return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
58640                 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
58641         }
58642         function resolveNewExpression(node, candidatesOutArray, checkMode) {
58643             if (node.arguments && languageVersion < 1 /* ES5 */) {
58644                 var spreadIndex = getSpreadArgumentIndex(node.arguments);
58645                 if (spreadIndex >= 0) {
58646                     error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
58647                 }
58648             }
58649             var expressionType = checkNonNullExpression(node.expression);
58650             if (expressionType === silentNeverType) {
58651                 return silentNeverSignature;
58652             }
58653             // If expressionType's apparent type(section 3.8.1) is an object type with one or
58654             // more construct signatures, the expression is processed in the same manner as a
58655             // function call, but using the construct signatures as the initial set of candidate
58656             // signatures for overload resolution. The result type of the function call becomes
58657             // the result type of the operation.
58658             expressionType = getApparentType(expressionType);
58659             if (expressionType === errorType) {
58660                 // Another error has already been reported
58661                 return resolveErrorCall(node);
58662             }
58663             // TS 1.0 spec: 4.11
58664             // If expressionType is of type Any, Args can be any argument
58665             // list and the result of the operation is of type Any.
58666             if (isTypeAny(expressionType)) {
58667                 if (node.typeArguments) {
58668                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58669                 }
58670                 return resolveUntypedCall(node);
58671             }
58672             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58673             // but we are not including construct signatures that may have been added to the Object or
58674             // Function interface, since they have none by default. This is a bit of a leap of faith
58675             // that the user will not add any.
58676             var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
58677             if (constructSignatures.length) {
58678                 if (!isConstructorAccessible(node, constructSignatures[0])) {
58679                     return resolveErrorCall(node);
58680                 }
58681                 // If the expression is a class of abstract type, then it cannot be instantiated.
58682                 // Note, only class declarations can be declared abstract.
58683                 // In the case of a merged class-module or class-interface declaration,
58684                 // only the class declaration node will have the Abstract flag set.
58685                 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
58686                 if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) {
58687                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
58688                     return resolveErrorCall(node);
58689                 }
58690                 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
58691             }
58692             // If expressionType's apparent type is an object type with no construct signatures but
58693             // one or more call signatures, the expression is processed as a function call. A compile-time
58694             // error occurs if the result of the function call is not Void. The type of the result of the
58695             // operation is Any. It is an error to have a Void this type.
58696             var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
58697             if (callSignatures.length) {
58698                 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
58699                 if (!noImplicitAny) {
58700                     if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
58701                         error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
58702                     }
58703                     if (getThisTypeOfSignature(signature) === voidType) {
58704                         error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
58705                     }
58706                 }
58707                 return signature;
58708             }
58709             invocationError(node.expression, expressionType, 1 /* Construct */);
58710             return resolveErrorCall(node);
58711         }
58712         function typeHasProtectedAccessibleBase(target, type) {
58713             var baseTypes = getBaseTypes(type);
58714             if (!ts.length(baseTypes)) {
58715                 return false;
58716             }
58717             var firstBase = baseTypes[0];
58718             if (firstBase.flags & 2097152 /* Intersection */) {
58719                 var types = firstBase.types;
58720                 var mixinFlags = findMixins(types);
58721                 var i = 0;
58722                 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
58723                     var intersectionMember = _a[_i];
58724                     // We want to ignore mixin ctors
58725                     if (!mixinFlags[i]) {
58726                         if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
58727                             if (intersectionMember.symbol === target) {
58728                                 return true;
58729                             }
58730                             if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
58731                                 return true;
58732                             }
58733                         }
58734                     }
58735                     i++;
58736                 }
58737                 return false;
58738             }
58739             if (firstBase.symbol === target) {
58740                 return true;
58741             }
58742             return typeHasProtectedAccessibleBase(target, firstBase);
58743         }
58744         function isConstructorAccessible(node, signature) {
58745             if (!signature || !signature.declaration) {
58746                 return true;
58747             }
58748             var declaration = signature.declaration;
58749             var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
58750             // (1) Public constructors and (2) constructor functions are always accessible.
58751             if (!modifiers || declaration.kind !== 162 /* Constructor */) {
58752                 return true;
58753             }
58754             var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
58755             var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
58756             // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
58757             if (!isNodeWithinClass(node, declaringClassDeclaration)) {
58758                 var containingClass = ts.getContainingClass(node);
58759                 if (containingClass && modifiers & 16 /* Protected */) {
58760                     var containingType = getTypeOfNode(containingClass);
58761                     if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
58762                         return true;
58763                     }
58764                 }
58765                 if (modifiers & 8 /* Private */) {
58766                     error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58767                 }
58768                 if (modifiers & 16 /* Protected */) {
58769                     error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58770                 }
58771                 return false;
58772             }
58773             return true;
58774         }
58775         function invocationErrorDetails(apparentType, kind) {
58776             var errorInfo;
58777             var isCall = kind === 0 /* Call */;
58778             var awaitedType = getAwaitedType(apparentType);
58779             var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
58780             if (apparentType.flags & 1048576 /* Union */) {
58781                 var types = apparentType.types;
58782                 var hasSignatures = false;
58783                 for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
58784                     var constituent = types_18[_i];
58785                     var signatures = getSignaturesOfType(constituent, kind);
58786                     if (signatures.length !== 0) {
58787                         hasSignatures = true;
58788                         if (errorInfo) {
58789                             // Bail early if we already have an error, no chance of "No constituent of type is callable"
58790                             break;
58791                         }
58792                     }
58793                     else {
58794                         // Error on the first non callable constituent only
58795                         if (!errorInfo) {
58796                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58797                                 ts.Diagnostics.Type_0_has_no_call_signatures :
58798                                 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
58799                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58800                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
58801                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
58802                         }
58803                         if (hasSignatures) {
58804                             // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
58805                             break;
58806                         }
58807                     }
58808                 }
58809                 if (!hasSignatures) {
58810                     errorInfo = ts.chainDiagnosticMessages(
58811                     /* detials */ undefined, isCall ?
58812                         ts.Diagnostics.No_constituent_of_type_0_is_callable :
58813                         ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
58814                 }
58815                 if (!errorInfo) {
58816                     errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58817                         ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
58818                         ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
58819                 }
58820             }
58821             else {
58822                 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58823                     ts.Diagnostics.Type_0_has_no_call_signatures :
58824                     ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
58825             }
58826             return {
58827                 messageChain: ts.chainDiagnosticMessages(errorInfo, isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable),
58828                 relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
58829             };
58830         }
58831         function invocationError(errorTarget, apparentType, kind, relatedInformation) {
58832             var _a = invocationErrorDetails(apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
58833             var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
58834             if (relatedInfo) {
58835                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
58836             }
58837             if (ts.isCallExpression(errorTarget.parent)) {
58838                 var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length;
58839                 diagnostic.start = start;
58840                 diagnostic.length = length_7;
58841             }
58842             diagnostics.add(diagnostic);
58843             invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
58844         }
58845         function invocationErrorRecovery(apparentType, kind, diagnostic) {
58846             if (!apparentType.symbol) {
58847                 return;
58848             }
58849             var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
58850             // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
58851             //  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
58852             if (importNode && !ts.isImportCall(importNode)) {
58853                 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
58854                 if (!sigs || !sigs.length)
58855                     return;
58856                 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));
58857             }
58858         }
58859         function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
58860             var tagType = checkExpression(node.tag);
58861             var apparentType = getApparentType(tagType);
58862             if (apparentType === errorType) {
58863                 // Another error has already been reported
58864                 return resolveErrorCall(node);
58865             }
58866             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58867             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58868             if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
58869                 return resolveUntypedCall(node);
58870             }
58871             if (!callSignatures.length) {
58872                 invocationError(node.tag, apparentType, 0 /* Call */);
58873                 return resolveErrorCall(node);
58874             }
58875             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
58876         }
58877         /**
58878          * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
58879          */
58880         function getDiagnosticHeadMessageForDecoratorResolution(node) {
58881             switch (node.parent.kind) {
58882                 case 245 /* ClassDeclaration */:
58883                 case 214 /* ClassExpression */:
58884                     return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
58885                 case 156 /* Parameter */:
58886                     return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
58887                 case 159 /* PropertyDeclaration */:
58888                     return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
58889                 case 161 /* MethodDeclaration */:
58890                 case 163 /* GetAccessor */:
58891                 case 164 /* SetAccessor */:
58892                     return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
58893                 default:
58894                     return ts.Debug.fail();
58895             }
58896         }
58897         /**
58898          * Resolves a decorator as if it were a call expression.
58899          */
58900         function resolveDecorator(node, candidatesOutArray, checkMode) {
58901             var funcType = checkExpression(node.expression);
58902             var apparentType = getApparentType(funcType);
58903             if (apparentType === errorType) {
58904                 return resolveErrorCall(node);
58905             }
58906             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58907             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58908             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
58909                 return resolveUntypedCall(node);
58910             }
58911             if (isPotentiallyUncalledDecorator(node, callSignatures)) {
58912                 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
58913                 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);
58914                 return resolveErrorCall(node);
58915             }
58916             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
58917             if (!callSignatures.length) {
58918                 var errorDetails = invocationErrorDetails(apparentType, 0 /* Call */);
58919                 var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
58920                 var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
58921                 if (errorDetails.relatedMessage) {
58922                     ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
58923                 }
58924                 diagnostics.add(diag);
58925                 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
58926                 return resolveErrorCall(node);
58927             }
58928             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
58929         }
58930         function createSignatureForJSXIntrinsic(node, result) {
58931             var namespace = getJsxNamespaceAt(node);
58932             var exports = namespace && getExportsOfSymbol(namespace);
58933             // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
58934             // file would probably be preferable.
58935             var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
58936             var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
58937             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 */));
58938             var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
58939             parameterSymbol.type = result;
58940             return createSignature(declaration, 
58941             /*typeParameters*/ undefined, 
58942             /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, 
58943             /*returnTypePredicate*/ undefined, 1, 0 /* None */);
58944         }
58945         function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
58946             if (isJsxIntrinsicIdentifier(node.tagName)) {
58947                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
58948                 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
58949                 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
58950                 return fakeSignature;
58951             }
58952             var exprTypes = checkExpression(node.tagName);
58953             var apparentType = getApparentType(exprTypes);
58954             if (apparentType === errorType) {
58955                 return resolveErrorCall(node);
58956             }
58957             var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
58958             if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
58959                 return resolveUntypedCall(node);
58960             }
58961             if (signatures.length === 0) {
58962                 // We found no signatures at all, which is an error
58963                 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
58964                 return resolveErrorCall(node);
58965             }
58966             return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
58967         }
58968         /**
58969          * Sometimes, we have a decorator that could accept zero arguments,
58970          * but is receiving too many arguments as part of the decorator invocation.
58971          * In those cases, a user may have meant to *call* the expression before using it as a decorator.
58972          */
58973         function isPotentiallyUncalledDecorator(decorator, signatures) {
58974             return signatures.length && ts.every(signatures, function (signature) {
58975                 return signature.minArgumentCount === 0 &&
58976                     !signatureHasRestParameter(signature) &&
58977                     signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
58978             });
58979         }
58980         function resolveSignature(node, candidatesOutArray, checkMode) {
58981             switch (node.kind) {
58982                 case 196 /* CallExpression */:
58983                     return resolveCallExpression(node, candidatesOutArray, checkMode);
58984                 case 197 /* NewExpression */:
58985                     return resolveNewExpression(node, candidatesOutArray, checkMode);
58986                 case 198 /* TaggedTemplateExpression */:
58987                     return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
58988                 case 157 /* Decorator */:
58989                     return resolveDecorator(node, candidatesOutArray, checkMode);
58990                 case 268 /* JsxOpeningElement */:
58991                 case 267 /* JsxSelfClosingElement */:
58992                     return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
58993             }
58994             throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
58995         }
58996         /**
58997          * Resolve a signature of a given call-like expression.
58998          * @param node a call-like expression to try resolve a signature for
58999          * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
59000          *                           the function will fill it up with appropriate candidate signatures
59001          * @return a signature of the call-like expression or undefined if one can't be found
59002          */
59003         function getResolvedSignature(node, candidatesOutArray, checkMode) {
59004             var links = getNodeLinks(node);
59005             // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
59006             // However, it is possible that either candidatesOutArray was not passed in the first time,
59007             // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
59008             // to correctly fill the candidatesOutArray.
59009             var cached = links.resolvedSignature;
59010             if (cached && cached !== resolvingSignature && !candidatesOutArray) {
59011                 return cached;
59012             }
59013             links.resolvedSignature = resolvingSignature;
59014             var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
59015             // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
59016             // resolution should be deferred.
59017             if (result !== resolvingSignature) {
59018                 // If signature resolution originated in control flow type analysis (for example to compute the
59019                 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
59020                 // types from the control flow analysis.
59021                 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
59022             }
59023             return result;
59024         }
59025         /**
59026          * Indicates whether a declaration can be treated as a constructor in a JavaScript
59027          * file.
59028          */
59029         function isJSConstructor(node) {
59030             if (!node || !ts.isInJSFile(node)) {
59031                 return false;
59032             }
59033             var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
59034                 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
59035                     undefined;
59036             if (func) {
59037                 // If the node has a @class tag, treat it like a constructor.
59038                 if (ts.getJSDocClassTag(node))
59039                     return true;
59040                 // If the symbol of the node has members, treat it like a constructor.
59041                 var symbol = getSymbolOfNode(func);
59042                 return !!symbol && ts.hasEntries(symbol.members);
59043             }
59044             return false;
59045         }
59046         function mergeJSSymbols(target, source) {
59047             if (source) {
59048                 var links = getSymbolLinks(source);
59049                 if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) {
59050                     var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
59051                     inferred.exports = inferred.exports || ts.createSymbolTable();
59052                     inferred.members = inferred.members || ts.createSymbolTable();
59053                     inferred.flags |= source.flags & 32 /* Class */;
59054                     if (ts.hasEntries(source.exports)) {
59055                         mergeSymbolTable(inferred.exports, source.exports);
59056                     }
59057                     if (ts.hasEntries(source.members)) {
59058                         mergeSymbolTable(inferred.members, source.members);
59059                     }
59060                     (links.inferredClassSymbol || (links.inferredClassSymbol = ts.createMap())).set("" + getSymbolId(inferred), inferred);
59061                     return inferred;
59062                 }
59063                 return links.inferredClassSymbol.get("" + getSymbolId(target));
59064             }
59065         }
59066         function getAssignedClassSymbol(decl) {
59067             var assignmentSymbol = decl && decl.parent &&
59068                 (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) ||
59069                     ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) ||
59070                     ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent));
59071             var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype");
59072             var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration);
59073             return init ? getSymbolOfNode(init) : undefined;
59074         }
59075         function getAssignedJSPrototype(node) {
59076             if (!node.parent) {
59077                 return false;
59078             }
59079             var parent = node.parent;
59080             while (parent && parent.kind === 194 /* PropertyAccessExpression */) {
59081                 parent = parent.parent;
59082             }
59083             if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) {
59084                 var right = ts.getInitializerOfBinaryExpression(parent);
59085                 return ts.isObjectLiteralExpression(right) && right;
59086             }
59087         }
59088         /**
59089          * Syntactically and semantically checks a call or new expression.
59090          * @param node The call/new expression to be checked.
59091          * @returns On success, the expression's signature's return type. On failure, anyType.
59092          */
59093         function checkCallExpression(node, checkMode) {
59094             if (!checkGrammarTypeArguments(node, node.typeArguments))
59095                 checkGrammarArguments(node.arguments);
59096             var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
59097             if (signature === resolvingSignature) {
59098                 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
59099                 // returns a function type. We defer checking and return nonInferrableType.
59100                 return nonInferrableType;
59101             }
59102             if (node.expression.kind === 102 /* SuperKeyword */) {
59103                 return voidType;
59104             }
59105             if (node.kind === 197 /* NewExpression */) {
59106                 var declaration = signature.declaration;
59107                 if (declaration &&
59108                     declaration.kind !== 162 /* Constructor */ &&
59109                     declaration.kind !== 166 /* ConstructSignature */ &&
59110                     declaration.kind !== 171 /* ConstructorType */ &&
59111                     !ts.isJSDocConstructSignature(declaration) &&
59112                     !isJSConstructor(declaration)) {
59113                     // When resolved signature is a call signature (and not a construct signature) the result type is any
59114                     if (noImplicitAny) {
59115                         error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
59116                     }
59117                     return anyType;
59118                 }
59119             }
59120             // In JavaScript files, calls to any identifier 'require' are treated as external module imports
59121             if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
59122                 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
59123             }
59124             var returnType = getReturnTypeOfSignature(signature);
59125             // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
59126             // as a fresh unique symbol literal type.
59127             if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
59128                 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
59129             }
59130             if (node.kind === 196 /* CallExpression */ && node.parent.kind === 226 /* ExpressionStatement */ &&
59131                 returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
59132                 if (!ts.isDottedName(node.expression)) {
59133                     error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
59134                 }
59135                 else if (!getEffectsSignature(node)) {
59136                     var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
59137                     getTypeOfDottedName(node.expression, diagnostic);
59138                 }
59139             }
59140             if (ts.isInJSFile(node)) {
59141                 var decl = ts.getDeclarationOfExpando(node);
59142                 if (decl) {
59143                     var jsSymbol = getSymbolOfNode(decl);
59144                     if (jsSymbol && ts.hasEntries(jsSymbol.exports)) {
59145                         var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
59146                         jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
59147                         return getIntersectionType([returnType, jsAssignmentType]);
59148                     }
59149                 }
59150             }
59151             return returnType;
59152         }
59153         function isSymbolOrSymbolForCall(node) {
59154             if (!ts.isCallExpression(node))
59155                 return false;
59156             var left = node.expression;
59157             if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
59158                 left = left.expression;
59159             }
59160             if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
59161                 return false;
59162             }
59163             // make sure `Symbol` is the global symbol
59164             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
59165             if (!globalESSymbol) {
59166                 return false;
59167             }
59168             return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
59169         }
59170         function checkImportCallExpression(node) {
59171             // Check grammar of dynamic import
59172             if (!checkGrammarArguments(node.arguments))
59173                 checkGrammarImportCallExpression(node);
59174             if (node.arguments.length === 0) {
59175                 return createPromiseReturnType(node, anyType);
59176             }
59177             var specifier = node.arguments[0];
59178             var specifierType = checkExpressionCached(specifier);
59179             // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
59180             for (var i = 1; i < node.arguments.length; ++i) {
59181                 checkExpressionCached(node.arguments[i]);
59182             }
59183             if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
59184                 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
59185             }
59186             // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
59187             var moduleSymbol = resolveExternalModuleName(node, specifier);
59188             if (moduleSymbol) {
59189                 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
59190                 if (esModuleSymbol) {
59191                     return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
59192                 }
59193             }
59194             return createPromiseReturnType(node, anyType);
59195         }
59196         function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
59197             if (allowSyntheticDefaultImports && type && type !== errorType) {
59198                 var synthType = type;
59199                 if (!synthType.syntheticType) {
59200                     var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
59201                     var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
59202                     if (hasSyntheticDefault) {
59203                         var memberTable = ts.createSymbolTable();
59204                         var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
59205                         newSymbol.nameType = getLiteralType("default");
59206                         newSymbol.target = resolveSymbol(symbol);
59207                         memberTable.set("default" /* Default */, newSymbol);
59208                         var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
59209                         var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
59210                         anonymousSymbol.type = defaultContainingObject;
59211                         synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
59212                     }
59213                     else {
59214                         synthType.syntheticType = type;
59215                     }
59216                 }
59217                 return synthType.syntheticType;
59218             }
59219             return type;
59220         }
59221         function isCommonJsRequire(node) {
59222             if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
59223                 return false;
59224             }
59225             // Make sure require is not a local function
59226             if (!ts.isIdentifier(node.expression))
59227                 return ts.Debug.fail();
59228             var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
59229             if (resolvedRequire === requireSymbol) {
59230                 return true;
59231             }
59232             // project includes symbol named 'require' - make sure that it is ambient and local non-alias
59233             if (resolvedRequire.flags & 2097152 /* Alias */) {
59234                 return false;
59235             }
59236             var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
59237                 ? 244 /* FunctionDeclaration */
59238                 : resolvedRequire.flags & 3 /* Variable */
59239                     ? 242 /* VariableDeclaration */
59240                     : 0 /* Unknown */;
59241             if (targetDeclarationKind !== 0 /* Unknown */) {
59242                 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
59243                 // function/variable declaration should be ambient
59244                 return !!decl && !!(decl.flags & 8388608 /* Ambient */);
59245             }
59246             return false;
59247         }
59248         function checkTaggedTemplateExpression(node) {
59249             if (!checkGrammarTaggedTemplateChain(node))
59250                 checkGrammarTypeArguments(node, node.typeArguments);
59251             if (languageVersion < 2 /* ES2015 */) {
59252                 checkExternalEmitHelpers(node, 131072 /* MakeTemplateObject */);
59253             }
59254             return getReturnTypeOfSignature(getResolvedSignature(node));
59255         }
59256         function checkAssertion(node) {
59257             return checkAssertionWorker(node, node.type, node.expression);
59258         }
59259         function isValidConstAssertionArgument(node) {
59260             switch (node.kind) {
59261                 case 10 /* StringLiteral */:
59262                 case 14 /* NoSubstitutionTemplateLiteral */:
59263                 case 8 /* NumericLiteral */:
59264                 case 9 /* BigIntLiteral */:
59265                 case 106 /* TrueKeyword */:
59266                 case 91 /* FalseKeyword */:
59267                 case 192 /* ArrayLiteralExpression */:
59268                 case 193 /* ObjectLiteralExpression */:
59269                     return true;
59270                 case 200 /* ParenthesizedExpression */:
59271                     return isValidConstAssertionArgument(node.expression);
59272                 case 207 /* PrefixUnaryExpression */:
59273                     var op = node.operator;
59274                     var arg = node.operand;
59275                     return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
59276                         op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
59277                 case 194 /* PropertyAccessExpression */:
59278                 case 195 /* ElementAccessExpression */:
59279                     var expr = node.expression;
59280                     if (ts.isIdentifier(expr)) {
59281                         var symbol = getSymbolAtLocation(expr);
59282                         if (symbol && symbol.flags & 2097152 /* Alias */) {
59283                             symbol = resolveAlias(symbol);
59284                         }
59285                         return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
59286                     }
59287             }
59288             return false;
59289         }
59290         function checkAssertionWorker(errNode, type, expression, checkMode) {
59291             var exprType = checkExpression(expression, checkMode);
59292             if (ts.isConstTypeReference(type)) {
59293                 if (!isValidConstAssertionArgument(expression)) {
59294                     error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
59295                 }
59296                 return getRegularTypeOfLiteralType(exprType);
59297             }
59298             checkSourceElement(type);
59299             exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
59300             var targetType = getTypeFromTypeNode(type);
59301             if (produceDiagnostics && targetType !== errorType) {
59302                 var widenedType = getWidenedType(exprType);
59303                 if (!isTypeComparableTo(targetType, widenedType)) {
59304                     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);
59305                 }
59306             }
59307             return targetType;
59308         }
59309         function checkNonNullChain(node) {
59310             var leftType = checkExpression(node.expression);
59311             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
59312             return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
59313         }
59314         function checkNonNullAssertion(node) {
59315             return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) :
59316                 getNonNullableType(checkExpression(node.expression));
59317         }
59318         function checkMetaProperty(node) {
59319             checkGrammarMetaProperty(node);
59320             if (node.keywordToken === 99 /* NewKeyword */) {
59321                 return checkNewTargetMetaProperty(node);
59322             }
59323             if (node.keywordToken === 96 /* ImportKeyword */) {
59324                 return checkImportMetaProperty(node);
59325             }
59326             return ts.Debug.assertNever(node.keywordToken);
59327         }
59328         function checkNewTargetMetaProperty(node) {
59329             var container = ts.getNewTargetContainer(node);
59330             if (!container) {
59331                 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
59332                 return errorType;
59333             }
59334             else if (container.kind === 162 /* Constructor */) {
59335                 var symbol = getSymbolOfNode(container.parent);
59336                 return getTypeOfSymbol(symbol);
59337             }
59338             else {
59339                 var symbol = getSymbolOfNode(container);
59340                 return getTypeOfSymbol(symbol);
59341             }
59342         }
59343         function checkImportMetaProperty(node) {
59344             if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) {
59345                 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system);
59346             }
59347             var file = ts.getSourceFileOfNode(node);
59348             ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
59349             ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
59350             return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
59351         }
59352         function getTypeOfParameter(symbol) {
59353             var type = getTypeOfSymbol(symbol);
59354             if (strictNullChecks) {
59355                 var declaration = symbol.valueDeclaration;
59356                 if (declaration && ts.hasInitializer(declaration)) {
59357                     return getOptionalType(type);
59358                 }
59359             }
59360             return type;
59361         }
59362         function getParameterNameAtPosition(signature, pos) {
59363             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59364             if (pos < paramCount) {
59365                 return signature.parameters[pos].escapedName;
59366             }
59367             var restParameter = signature.parameters[paramCount] || unknownSymbol;
59368             var restType = getTypeOfSymbol(restParameter);
59369             if (isTupleType(restType)) {
59370                 var associatedNames = restType.target.associatedNames;
59371                 var index = pos - paramCount;
59372                 return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
59373             }
59374             return restParameter.escapedName;
59375         }
59376         function getTypeAtPosition(signature, pos) {
59377             return tryGetTypeAtPosition(signature, pos) || anyType;
59378         }
59379         function tryGetTypeAtPosition(signature, pos) {
59380             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59381             if (pos < paramCount) {
59382                 return getTypeOfParameter(signature.parameters[pos]);
59383             }
59384             if (signatureHasRestParameter(signature)) {
59385                 // We want to return the value undefined for an out of bounds parameter position,
59386                 // so we need to check bounds here before calling getIndexedAccessType (which
59387                 // otherwise would return the type 'undefined').
59388                 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
59389                 var index = pos - paramCount;
59390                 if (!isTupleType(restType) || restType.target.hasRestElement || index < getTypeArguments(restType).length) {
59391                     return getIndexedAccessType(restType, getLiteralType(index));
59392                 }
59393             }
59394             return undefined;
59395         }
59396         function getRestTypeAtPosition(source, pos) {
59397             var paramCount = getParameterCount(source);
59398             var restType = getEffectiveRestType(source);
59399             var nonRestCount = paramCount - (restType ? 1 : 0);
59400             if (restType && pos === nonRestCount) {
59401                 return restType;
59402             }
59403             var types = [];
59404             var names = [];
59405             for (var i = pos; i < nonRestCount; i++) {
59406                 types.push(getTypeAtPosition(source, i));
59407                 names.push(getParameterNameAtPosition(source, i));
59408             }
59409             if (restType) {
59410                 types.push(getIndexedAccessType(restType, numberType));
59411                 names.push(getParameterNameAtPosition(source, nonRestCount));
59412             }
59413             var minArgumentCount = getMinArgumentCount(source);
59414             var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
59415             return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
59416         }
59417         function getParameterCount(signature) {
59418             var length = signature.parameters.length;
59419             if (signatureHasRestParameter(signature)) {
59420                 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
59421                 if (isTupleType(restType)) {
59422                     return length + getTypeArguments(restType).length - 1;
59423                 }
59424             }
59425             return length;
59426         }
59427         function getMinArgumentCount(signature, strongArityForUntypedJS) {
59428             if (signatureHasRestParameter(signature)) {
59429                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59430                 if (isTupleType(restType)) {
59431                     var minLength = restType.target.minLength;
59432                     if (minLength > 0) {
59433                         return signature.parameters.length - 1 + minLength;
59434                     }
59435                 }
59436             }
59437             if (!strongArityForUntypedJS && signature.flags & 16 /* IsUntypedSignatureInJSFile */) {
59438                 return 0;
59439             }
59440             return signature.minArgumentCount;
59441         }
59442         function hasEffectiveRestParameter(signature) {
59443             if (signatureHasRestParameter(signature)) {
59444                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59445                 return !isTupleType(restType) || restType.target.hasRestElement;
59446             }
59447             return false;
59448         }
59449         function getEffectiveRestType(signature) {
59450             if (signatureHasRestParameter(signature)) {
59451                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59452                 return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType;
59453             }
59454             return undefined;
59455         }
59456         function getNonArrayRestType(signature) {
59457             var restType = getEffectiveRestType(signature);
59458             return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined;
59459         }
59460         function getTypeOfFirstParameterOfSignature(signature) {
59461             return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
59462         }
59463         function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
59464             return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
59465         }
59466         function inferFromAnnotatedParameters(signature, context, inferenceContext) {
59467             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59468             for (var i = 0; i < len; i++) {
59469                 var declaration = signature.parameters[i].valueDeclaration;
59470                 if (declaration.type) {
59471                     var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
59472                     if (typeNode) {
59473                         inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
59474                     }
59475                 }
59476             }
59477             var restType = getEffectiveRestType(context);
59478             if (restType && restType.flags & 262144 /* TypeParameter */) {
59479                 // The contextual signature has a generic rest parameter. We first instantiate the contextual
59480                 // signature (without fixing type parameters) and assign types to contextually typed parameters.
59481                 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
59482                 assignContextualParameterTypes(signature, instantiatedContext);
59483                 // We then infer from a tuple type representing the parameters that correspond to the contextual
59484                 // rest parameter.
59485                 var restPos = getParameterCount(context) - 1;
59486                 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
59487             }
59488         }
59489         function assignContextualParameterTypes(signature, context) {
59490             signature.typeParameters = context.typeParameters;
59491             if (context.thisParameter) {
59492                 var parameter = signature.thisParameter;
59493                 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
59494                     if (!parameter) {
59495                         signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
59496                     }
59497                     assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
59498                 }
59499             }
59500             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59501             for (var i = 0; i < len; i++) {
59502                 var parameter = signature.parameters[i];
59503                 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59504                     var contextualParameterType = tryGetTypeAtPosition(context, i);
59505                     assignParameterType(parameter, contextualParameterType);
59506                 }
59507             }
59508             if (signatureHasRestParameter(signature)) {
59509                 // parameter might be a transient symbol generated by use of `arguments` in the function body.
59510                 var parameter = ts.last(signature.parameters);
59511                 if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59512                     var contextualParameterType = getRestTypeAtPosition(context, len);
59513                     assignParameterType(parameter, contextualParameterType);
59514                 }
59515             }
59516         }
59517         function assignNonContextualParameterTypes(signature) {
59518             if (signature.thisParameter) {
59519                 assignParameterType(signature.thisParameter);
59520             }
59521             for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
59522                 var parameter = _a[_i];
59523                 assignParameterType(parameter);
59524             }
59525         }
59526         function assignParameterType(parameter, type) {
59527             var links = getSymbolLinks(parameter);
59528             if (!links.type) {
59529                 var declaration = parameter.valueDeclaration;
59530                 links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
59531                 if (declaration.name.kind !== 75 /* Identifier */) {
59532                     // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
59533                     if (links.type === unknownType) {
59534                         links.type = getTypeFromBindingPattern(declaration.name);
59535                     }
59536                     assignBindingElementTypes(declaration.name);
59537                 }
59538             }
59539         }
59540         // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
59541         // the destructured type into the contained binding elements.
59542         function assignBindingElementTypes(pattern) {
59543             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
59544                 var element = _a[_i];
59545                 if (!ts.isOmittedExpression(element)) {
59546                     if (element.name.kind === 75 /* Identifier */) {
59547                         getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
59548                     }
59549                     else {
59550                         assignBindingElementTypes(element.name);
59551                     }
59552                 }
59553             }
59554         }
59555         function createPromiseType(promisedType) {
59556             // creates a `Promise<T>` type where `T` is the promisedType argument
59557             var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
59558             if (globalPromiseType !== emptyGenericType) {
59559                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59560                 promisedType = getAwaitedType(promisedType) || unknownType;
59561                 return createTypeReference(globalPromiseType, [promisedType]);
59562             }
59563             return unknownType;
59564         }
59565         function createPromiseLikeType(promisedType) {
59566             // creates a `PromiseLike<T>` type where `T` is the promisedType argument
59567             var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
59568             if (globalPromiseLikeType !== emptyGenericType) {
59569                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59570                 promisedType = getAwaitedType(promisedType) || unknownType;
59571                 return createTypeReference(globalPromiseLikeType, [promisedType]);
59572             }
59573             return unknownType;
59574         }
59575         function createPromiseReturnType(func, promisedType) {
59576             var promiseType = createPromiseType(promisedType);
59577             if (promiseType === unknownType) {
59578                 error(func, ts.isImportCall(func) ?
59579                     ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
59580                     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);
59581                 return errorType;
59582             }
59583             else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
59584                 error(func, ts.isImportCall(func) ?
59585                     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 :
59586                     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);
59587             }
59588             return promiseType;
59589         }
59590         function getReturnTypeFromBody(func, checkMode) {
59591             if (!func.body) {
59592                 return errorType;
59593             }
59594             var functionFlags = ts.getFunctionFlags(func);
59595             var isAsync = (functionFlags & 2 /* Async */) !== 0;
59596             var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
59597             var returnType;
59598             var yieldType;
59599             var nextType;
59600             var fallbackReturnType = voidType;
59601             if (func.body.kind !== 223 /* Block */) { // Async or normal arrow function
59602                 returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59603                 if (isAsync) {
59604                     // From within an async function you can return either a non-promise value or a promise. Any
59605                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59606                     // return type of the body should be unwrapped to its awaited type, which we will wrap in
59607                     // the native Promise<T> type later in this function.
59608                     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);
59609                 }
59610             }
59611             else if (isGenerator) { // Generator or AsyncGenerator function
59612                 var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
59613                 if (!returnTypes) {
59614                     fallbackReturnType = neverType;
59615                 }
59616                 else if (returnTypes.length > 0) {
59617                     returnType = getUnionType(returnTypes, 2 /* Subtype */);
59618                 }
59619                 var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
59620                 yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
59621                 nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
59622             }
59623             else { // Async or normal function
59624                 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
59625                 if (!types) {
59626                     // For an async function, the return type will not be never, but rather a Promise for never.
59627                     return functionFlags & 2 /* Async */
59628                         ? createPromiseReturnType(func, neverType) // Async function
59629                         : neverType; // Normal function
59630                 }
59631                 if (types.length === 0) {
59632                     // For an async function, the return type will not be void, but rather a Promise for void.
59633                     return functionFlags & 2 /* Async */
59634                         ? createPromiseReturnType(func, voidType) // Async function
59635                         : voidType; // Normal function
59636                 }
59637                 // Return a union of the return expression types.
59638                 returnType = getUnionType(types, 2 /* Subtype */);
59639             }
59640             if (returnType || yieldType || nextType) {
59641                 if (yieldType)
59642                     reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
59643                 if (returnType)
59644                     reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
59645                 if (nextType)
59646                     reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
59647                 if (returnType && isUnitType(returnType) ||
59648                     yieldType && isUnitType(yieldType) ||
59649                     nextType && isUnitType(nextType)) {
59650                     var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
59651                     var contextualType = !contextualSignature ? undefined :
59652                         contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
59653                             instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
59654                     if (isGenerator) {
59655                         yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
59656                         returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
59657                         nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
59658                     }
59659                     else {
59660                         returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
59661                     }
59662                 }
59663                 if (yieldType)
59664                     yieldType = getWidenedType(yieldType);
59665                 if (returnType)
59666                     returnType = getWidenedType(returnType);
59667                 if (nextType)
59668                     nextType = getWidenedType(nextType);
59669             }
59670             if (isGenerator) {
59671                 return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
59672             }
59673             else {
59674                 // From within an async function you can return either a non-promise value or a promise. Any
59675                 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59676                 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
59677                 return isAsync
59678                     ? createPromiseType(returnType || fallbackReturnType)
59679                     : returnType || fallbackReturnType;
59680             }
59681         }
59682         function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
59683             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
59684             var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
59685             yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
59686             returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
59687             nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
59688             if (globalGeneratorType === emptyGenericType) {
59689                 // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
59690                 // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
59691                 // nextType.
59692                 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
59693                 var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
59694                 var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
59695                 var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
59696                 if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
59697                     isTypeAssignableTo(iterableIteratorNextType, nextType)) {
59698                     if (globalType !== emptyGenericType) {
59699                         return createTypeFromGenericGlobalType(globalType, [yieldType]);
59700                     }
59701                     // The global IterableIterator type doesn't exist, so report an error
59702                     resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
59703                     return emptyObjectType;
59704                 }
59705                 // The global Generator type doesn't exist, so report an error
59706                 resolver.getGlobalGeneratorType(/*reportErrors*/ true);
59707                 return emptyObjectType;
59708             }
59709             return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
59710         }
59711         function checkAndAggregateYieldOperandTypes(func, checkMode) {
59712             var yieldTypes = [];
59713             var nextTypes = [];
59714             var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
59715             ts.forEachYieldExpression(func.body, function (yieldExpression) {
59716                 var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
59717                 ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
59718                 var nextType;
59719                 if (yieldExpression.asteriskToken) {
59720                     var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
59721                     nextType = iterationTypes && iterationTypes.nextType;
59722                 }
59723                 else {
59724                     nextType = getContextualType(yieldExpression);
59725                 }
59726                 if (nextType)
59727                     ts.pushIfUnique(nextTypes, nextType);
59728             });
59729             return { yieldTypes: yieldTypes, nextTypes: nextTypes };
59730         }
59731         function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
59732             var errorNode = node.expression || node;
59733             // A `yield*` expression effectively yields everything that its operand yields
59734             var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
59735             return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
59736                 ? 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
59737                 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
59738         }
59739         /**
59740          * Collect the TypeFacts learned from a typeof switch with
59741          * total clauses `witnesses`, and the active clause ranging
59742          * from `start` to `end`. Parameter `hasDefault` denotes
59743          * whether the active clause contains a default clause.
59744          */
59745         function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
59746             var facts = 0 /* None */;
59747             // When in the default we only collect inequality facts
59748             // because default is 'in theory' a set of infinite
59749             // equalities.
59750             if (hasDefault) {
59751                 // Value is not equal to any types after the active clause.
59752                 for (var i = end; i < witnesses.length; i++) {
59753                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59754                 }
59755                 // Remove inequalities for types that appear in the
59756                 // active clause because they appear before other
59757                 // types collected so far.
59758                 for (var i = start; i < end; i++) {
59759                     facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
59760                 }
59761                 // Add inequalities for types before the active clause unconditionally.
59762                 for (var i = 0; i < start; i++) {
59763                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59764                 }
59765             }
59766             // When in an active clause without default the set of
59767             // equalities is finite.
59768             else {
59769                 // Add equalities for all types in the active clause.
59770                 for (var i = start; i < end; i++) {
59771                     facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
59772                 }
59773                 // Remove equalities for types that appear before the
59774                 // active clause.
59775                 for (var i = 0; i < start; i++) {
59776                     facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
59777                 }
59778             }
59779             return facts;
59780         }
59781         function isExhaustiveSwitchStatement(node) {
59782             var links = getNodeLinks(node);
59783             return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
59784         }
59785         function computeExhaustiveSwitchStatement(node) {
59786             if (node.expression.kind === 204 /* TypeOfExpression */) {
59787                 var operandType = getTypeOfExpression(node.expression.expression);
59788                 var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
59789                 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
59790                 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
59791                 var type_3 = getBaseConstraintOfType(operandType) || operandType;
59792                 return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
59793             }
59794             var type = getTypeOfExpression(node.expression);
59795             if (!isLiteralType(type)) {
59796                 return false;
59797             }
59798             var switchTypes = getSwitchClauseTypes(node);
59799             if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
59800                 return false;
59801             }
59802             return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
59803         }
59804         function functionHasImplicitReturn(func) {
59805             return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
59806         }
59807         /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
59808         function checkAndAggregateReturnExpressionTypes(func, checkMode) {
59809             var functionFlags = ts.getFunctionFlags(func);
59810             var aggregatedTypes = [];
59811             var hasReturnWithNoExpression = functionHasImplicitReturn(func);
59812             var hasReturnOfTypeNever = false;
59813             ts.forEachReturnStatement(func.body, function (returnStatement) {
59814                 var expr = returnStatement.expression;
59815                 if (expr) {
59816                     var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59817                     if (functionFlags & 2 /* Async */) {
59818                         // From within an async function you can return either a non-promise value or a promise. Any
59819                         // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59820                         // return type of the body should be unwrapped to its awaited type, which should be wrapped in
59821                         // the native Promise<T> type by the caller.
59822                         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);
59823                     }
59824                     if (type.flags & 131072 /* Never */) {
59825                         hasReturnOfTypeNever = true;
59826                     }
59827                     ts.pushIfUnique(aggregatedTypes, type);
59828                 }
59829                 else {
59830                     hasReturnWithNoExpression = true;
59831                 }
59832             });
59833             if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
59834                 return undefined;
59835             }
59836             if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
59837                 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
59838                 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
59839                 ts.pushIfUnique(aggregatedTypes, undefinedType);
59840             }
59841             return aggregatedTypes;
59842         }
59843         function mayReturnNever(func) {
59844             switch (func.kind) {
59845                 case 201 /* FunctionExpression */:
59846                 case 202 /* ArrowFunction */:
59847                     return true;
59848                 case 161 /* MethodDeclaration */:
59849                     return func.parent.kind === 193 /* ObjectLiteralExpression */;
59850                 default:
59851                     return false;
59852             }
59853         }
59854         /**
59855          * TypeScript Specification 1.0 (6.3) - July 2014
59856          *   An explicitly typed function whose return type isn't the Void type,
59857          *   the Any type, or a union type containing the Void or Any type as a constituent
59858          *   must have at least one return statement somewhere in its body.
59859          *   An exception to this rule is if the function implementation consists of a single 'throw' statement.
59860          *
59861          * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
59862          */
59863         function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
59864             if (!produceDiagnostics) {
59865                 return;
59866             }
59867             var functionFlags = ts.getFunctionFlags(func);
59868             var type = returnType && unwrapReturnType(returnType, functionFlags);
59869             // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
59870             if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
59871                 return;
59872             }
59873             // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
59874             // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
59875             if (func.kind === 160 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 223 /* Block */ || !functionHasImplicitReturn(func)) {
59876                 return;
59877             }
59878             var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
59879             if (type && type.flags & 131072 /* Never */) {
59880                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
59881             }
59882             else if (type && !hasExplicitReturn) {
59883                 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
59884                 // this function does not conform to the specification.
59885                 // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
59886                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
59887             }
59888             else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
59889                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
59890             }
59891             else if (compilerOptions.noImplicitReturns) {
59892                 if (!type) {
59893                     // If return type annotation is omitted check if function has any explicit return statements.
59894                     // If it does not have any - its inferred return type is void - don't do any checks.
59895                     // Otherwise get inferred return type from function body and report error only if it is not void / anytype
59896                     if (!hasExplicitReturn) {
59897                         return;
59898                     }
59899                     var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
59900                     if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
59901                         return;
59902                     }
59903                 }
59904                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
59905             }
59906         }
59907         function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
59908             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
59909             checkNodeDeferred(node);
59910             // The identityMapper object is used to indicate that function expressions are wildcards
59911             if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
59912                 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
59913                 if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
59914                     // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
59915                     var contextualSignature = getContextualSignature(node);
59916                     if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
59917                         var links = getNodeLinks(node);
59918                         if (links.contextFreeType) {
59919                             return links.contextFreeType;
59920                         }
59921                         var returnType = getReturnTypeFromBody(node, checkMode);
59922                         var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
59923                         var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
59924                         returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */;
59925                         return links.contextFreeType = returnOnlyType;
59926                     }
59927                 }
59928                 return anyFunctionType;
59929             }
59930             // Grammar checking
59931             var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
59932             if (!hasGrammarError && node.kind === 201 /* FunctionExpression */) {
59933                 checkGrammarForGenerator(node);
59934             }
59935             contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
59936             return getTypeOfSymbol(getSymbolOfNode(node));
59937         }
59938         function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
59939             var links = getNodeLinks(node);
59940             // Check if function expression is contextually typed and assign parameter types if so.
59941             if (!(links.flags & 1024 /* ContextChecked */)) {
59942                 var contextualSignature = getContextualSignature(node);
59943                 // If a type check is started at a function expression that is an argument of a function call, obtaining the
59944                 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
59945                 // already assigned contextual types.
59946                 if (!(links.flags & 1024 /* ContextChecked */)) {
59947                     links.flags |= 1024 /* ContextChecked */;
59948                     var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
59949                     if (!signature) {
59950                         return;
59951                     }
59952                     if (isContextSensitive(node)) {
59953                         if (contextualSignature) {
59954                             var inferenceContext = getInferenceContext(node);
59955                             if (checkMode && checkMode & 2 /* Inferential */) {
59956                                 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
59957                             }
59958                             var instantiatedContextualSignature = inferenceContext ?
59959                                 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
59960                             assignContextualParameterTypes(signature, instantiatedContextualSignature);
59961                         }
59962                         else {
59963                             // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
59964                             assignNonContextualParameterTypes(signature);
59965                         }
59966                     }
59967                     if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
59968                         var returnType = getReturnTypeFromBody(node, checkMode);
59969                         if (!signature.resolvedReturnType) {
59970                             signature.resolvedReturnType = returnType;
59971                         }
59972                     }
59973                     checkSignatureDeclaration(node);
59974                 }
59975             }
59976         }
59977         function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
59978             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
59979             var functionFlags = ts.getFunctionFlags(node);
59980             var returnType = getReturnTypeFromAnnotation(node);
59981             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
59982             if (node.body) {
59983                 if (!ts.getEffectiveReturnTypeNode(node)) {
59984                     // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
59985                     // we need. An example is the noImplicitAny errors resulting from widening the return expression
59986                     // of a function. Because checking of function expression bodies is deferred, there was never an
59987                     // appropriate time to do this during the main walk of the file (see the comment at the top of
59988                     // checkFunctionExpressionBodies). So it must be done now.
59989                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
59990                 }
59991                 if (node.body.kind === 223 /* Block */) {
59992                     checkSourceElement(node.body);
59993                 }
59994                 else {
59995                     // From within an async function you can return either a non-promise value or a promise. Any
59996                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
59997                     // should not be checking assignability of a promise to the return type. Instead, we need to
59998                     // check assignability of the awaited type of the expression body against the promised type of
59999                     // its return type annotation.
60000                     var exprType = checkExpression(node.body);
60001                     var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
60002                     if (returnOrPromisedType) {
60003                         if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
60004                             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);
60005                             checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
60006                         }
60007                         else { // Normal function
60008                             checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
60009                         }
60010                     }
60011                 }
60012             }
60013         }
60014         function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
60015             if (isAwaitValid === void 0) { isAwaitValid = false; }
60016             if (!isTypeAssignableTo(type, numberOrBigIntType)) {
60017                 var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
60018                 errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
60019                 return false;
60020             }
60021             return true;
60022         }
60023         function isReadonlyAssignmentDeclaration(d) {
60024             if (!ts.isCallExpression(d)) {
60025                 return false;
60026             }
60027             if (!ts.isBindableObjectDefinePropertyCall(d)) {
60028                 return false;
60029             }
60030             var objectLitType = checkExpressionCached(d.arguments[2]);
60031             var valueType = getTypeOfPropertyOfType(objectLitType, "value");
60032             if (valueType) {
60033                 var writableProp = getPropertyOfType(objectLitType, "writable");
60034                 var writableType = writableProp && getTypeOfSymbol(writableProp);
60035                 if (!writableType || writableType === falseType || writableType === regularFalseType) {
60036                     return true;
60037                 }
60038                 // We include this definition whereupon we walk back and check the type at the declaration because
60039                 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
60040                 // argument types, should the type be contextualized by the call itself.
60041                 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
60042                     var initializer = writableProp.valueDeclaration.initializer;
60043                     var rawOriginalType = checkExpression(initializer);
60044                     if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
60045                         return true;
60046                     }
60047                 }
60048                 return false;
60049             }
60050             var setProp = getPropertyOfType(objectLitType, "set");
60051             return !setProp;
60052         }
60053         function isReadonlySymbol(symbol) {
60054             // The following symbols are considered read-only:
60055             // Properties with a 'readonly' modifier
60056             // Variables declared with 'const'
60057             // Get accessors without matching set accessors
60058             // Enum members
60059             // Object.defineProperty assignments with writable false or no setter
60060             // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
60061             return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
60062                 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
60063                 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
60064                 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
60065                 symbol.flags & 8 /* EnumMember */ ||
60066                 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
60067         }
60068         function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
60069             var _a, _b;
60070             if (assignmentKind === 0 /* None */) {
60071                 // no assigment means it doesn't matter whether the entity is readonly
60072                 return false;
60073             }
60074             if (isReadonlySymbol(symbol)) {
60075                 // Allow assignments to readonly properties within constructors of the same class declaration.
60076                 if (symbol.flags & 4 /* Property */ &&
60077                     ts.isAccessExpression(expr) &&
60078                     expr.expression.kind === 104 /* ThisKeyword */) {
60079                     // Look for if this is the constructor for the class that `symbol` is a property of.
60080                     var ctor = ts.getContainingFunction(expr);
60081                     if (!(ctor && ctor.kind === 162 /* Constructor */)) {
60082                         return true;
60083                     }
60084                     if (symbol.valueDeclaration) {
60085                         var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
60086                         var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
60087                         var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
60088                         var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
60089                         var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
60090                         var isWriteableSymbol = isLocalPropertyDeclaration
60091                             || isLocalParameterProperty
60092                             || isLocalThisPropertyAssignment
60093                             || isLocalThisPropertyAssignmentConstructorFunction;
60094                         return !isWriteableSymbol;
60095                     }
60096                 }
60097                 return true;
60098             }
60099             if (ts.isAccessExpression(expr)) {
60100                 // references through namespace import should be readonly
60101                 var node = ts.skipParentheses(expr.expression);
60102                 if (node.kind === 75 /* Identifier */) {
60103                     var symbol_2 = getNodeLinks(node).resolvedSymbol;
60104                     if (symbol_2.flags & 2097152 /* Alias */) {
60105                         var declaration = getDeclarationOfAliasSymbol(symbol_2);
60106                         return !!declaration && declaration.kind === 256 /* NamespaceImport */;
60107                     }
60108                 }
60109             }
60110             return false;
60111         }
60112         function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
60113             // References are combinations of identifiers, parentheses, and property accesses.
60114             var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
60115             if (node.kind !== 75 /* Identifier */ && !ts.isAccessExpression(node)) {
60116                 error(expr, invalidReferenceMessage);
60117                 return false;
60118             }
60119             if (node.flags & 32 /* OptionalChain */) {
60120                 error(expr, invalidOptionalChainMessage);
60121                 return false;
60122             }
60123             return true;
60124         }
60125         function checkDeleteExpression(node) {
60126             checkExpression(node.expression);
60127             var expr = ts.skipParentheses(node.expression);
60128             if (!ts.isAccessExpression(expr)) {
60129                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
60130                 return booleanType;
60131             }
60132             // eslint-disable-next-line
60133             if (expr.kind === 194 /* PropertyAccessExpression */ && ts.isPrivateIdentifier(expr.name)) {
60134                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
60135             }
60136             var links = getNodeLinks(expr);
60137             var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
60138             if (symbol && isReadonlySymbol(symbol)) {
60139                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
60140             }
60141             return booleanType;
60142         }
60143         function checkTypeOfExpression(node) {
60144             checkExpression(node.expression);
60145             return typeofType;
60146         }
60147         function checkVoidExpression(node) {
60148             checkExpression(node.expression);
60149             return undefinedWideningType;
60150         }
60151         function isTopLevelAwait(node) {
60152             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ true);
60153             return ts.isSourceFile(container);
60154         }
60155         function checkAwaitExpression(node) {
60156             // Grammar checking
60157             if (produceDiagnostics) {
60158                 if (!(node.flags & 32768 /* AwaitContext */)) {
60159                     if (isTopLevelAwait(node)) {
60160                         var sourceFile = ts.getSourceFileOfNode(node);
60161                         if (!hasParseDiagnostics(sourceFile)) {
60162                             var span = void 0;
60163                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
60164                                 if (!span)
60165                                     span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60166                                 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);
60167                                 diagnostics.add(diagnostic);
60168                             }
60169                             if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
60170                                 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60171                                 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);
60172                                 diagnostics.add(diagnostic);
60173                             }
60174                         }
60175                     }
60176                     else {
60177                         // use of 'await' in non-async function
60178                         var sourceFile = ts.getSourceFileOfNode(node);
60179                         if (!hasParseDiagnostics(sourceFile)) {
60180                             var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60181                             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);
60182                             var func = ts.getContainingFunction(node);
60183                             if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) {
60184                                 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
60185                                 ts.addRelatedInfo(diagnostic, relatedInfo);
60186                             }
60187                             diagnostics.add(diagnostic);
60188                         }
60189                     }
60190                 }
60191                 if (isInParameterInitializerBeforeContainingFunction(node)) {
60192                     error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
60193                 }
60194             }
60195             var operandType = checkExpression(node.expression);
60196             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);
60197             if (awaitedType === operandType && awaitedType !== errorType && !(operandType.flags & 3 /* AnyOrUnknown */)) {
60198                 addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
60199             }
60200             return awaitedType;
60201         }
60202         function checkPrefixUnaryExpression(node) {
60203             var operandType = checkExpression(node.operand);
60204             if (operandType === silentNeverType) {
60205                 return silentNeverType;
60206             }
60207             switch (node.operand.kind) {
60208                 case 8 /* NumericLiteral */:
60209                     switch (node.operator) {
60210                         case 40 /* MinusToken */:
60211                             return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
60212                         case 39 /* PlusToken */:
60213                             return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
60214                     }
60215                     break;
60216                 case 9 /* BigIntLiteral */:
60217                     if (node.operator === 40 /* MinusToken */) {
60218                         return getFreshTypeOfLiteralType(getLiteralType({
60219                             negative: true,
60220                             base10Value: ts.parsePseudoBigInt(node.operand.text)
60221                         }));
60222                     }
60223             }
60224             switch (node.operator) {
60225                 case 39 /* PlusToken */:
60226                 case 40 /* MinusToken */:
60227                 case 54 /* TildeToken */:
60228                     checkNonNullType(operandType, node.operand);
60229                     if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
60230                         error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
60231                     }
60232                     if (node.operator === 39 /* PlusToken */) {
60233                         if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60234                             error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
60235                         }
60236                         return numberType;
60237                     }
60238                     return getUnaryResultType(operandType);
60239                 case 53 /* ExclamationToken */:
60240                     checkTruthinessExpression(node.operand);
60241                     var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
60242                     return facts === 4194304 /* Truthy */ ? falseType :
60243                         facts === 8388608 /* Falsy */ ? trueType :
60244                             booleanType;
60245                 case 45 /* PlusPlusToken */:
60246                 case 46 /* MinusMinusToken */:
60247                     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);
60248                     if (ok) {
60249                         // run check only if former checks succeeded to avoid reporting cascading errors
60250                         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);
60251                     }
60252                     return getUnaryResultType(operandType);
60253             }
60254             return errorType;
60255         }
60256         function checkPostfixUnaryExpression(node) {
60257             var operandType = checkExpression(node.operand);
60258             if (operandType === silentNeverType) {
60259                 return silentNeverType;
60260             }
60261             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);
60262             if (ok) {
60263                 // run check only if former checks succeeded to avoid reporting cascading errors
60264                 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);
60265             }
60266             return getUnaryResultType(operandType);
60267         }
60268         function getUnaryResultType(operandType) {
60269             if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60270                 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
60271                     ? numberOrBigIntType
60272                     : bigintType;
60273             }
60274             // If it's not a bigint type, implicit coercion will result in a number
60275             return numberType;
60276         }
60277         // Return true if type might be of the given kind. A union or intersection type might be of a given
60278         // kind if at least one constituent type is of the given kind.
60279         function maybeTypeOfKind(type, kind) {
60280             if (type.flags & kind) {
60281                 return true;
60282             }
60283             if (type.flags & 3145728 /* UnionOrIntersection */) {
60284                 var types = type.types;
60285                 for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
60286                     var t = types_19[_i];
60287                     if (maybeTypeOfKind(t, kind)) {
60288                         return true;
60289                     }
60290                 }
60291             }
60292             return false;
60293         }
60294         function isTypeAssignableToKind(source, kind, strict) {
60295             if (source.flags & kind) {
60296                 return true;
60297             }
60298             if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
60299                 return false;
60300             }
60301             return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
60302                 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
60303                 !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
60304                 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
60305                 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
60306                 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
60307                 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
60308                 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
60309                 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
60310                 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
60311         }
60312         function allTypesAssignableToKind(source, kind, strict) {
60313             return source.flags & 1048576 /* Union */ ?
60314                 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
60315                 isTypeAssignableToKind(source, kind, strict);
60316         }
60317         function isConstEnumObjectType(type) {
60318             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
60319         }
60320         function isConstEnumSymbol(symbol) {
60321             return (symbol.flags & 128 /* ConstEnum */) !== 0;
60322         }
60323         function checkInstanceOfExpression(left, right, leftType, rightType) {
60324             if (leftType === silentNeverType || rightType === silentNeverType) {
60325                 return silentNeverType;
60326             }
60327             // TypeScript 1.0 spec (April 2014): 4.15.4
60328             // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
60329             // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
60330             // The result is always of the Boolean primitive type.
60331             // NOTE: do not raise error if leftType is unknown as related error was already reported
60332             if (!isTypeAny(leftType) &&
60333                 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
60334                 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60335             }
60336             // NOTE: do not raise error if right is unknown as related error was already reported
60337             if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
60338                 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);
60339             }
60340             return booleanType;
60341         }
60342         function checkInExpression(left, right, leftType, rightType) {
60343             if (leftType === silentNeverType || rightType === silentNeverType) {
60344                 return silentNeverType;
60345             }
60346             leftType = checkNonNullType(leftType, left);
60347             rightType = checkNonNullType(rightType, right);
60348             // TypeScript 1.0 spec (April 2014): 4.15.5
60349             // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
60350             // and the right operand to be of type Any, an object type, or a type parameter type.
60351             // The result is always of the Boolean primitive type.
60352             if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) {
60353                 error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
60354             }
60355             if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
60356                 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60357             }
60358             return booleanType;
60359         }
60360         function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
60361             var properties = node.properties;
60362             if (strictNullChecks && properties.length === 0) {
60363                 return checkNonNullType(sourceType, node);
60364             }
60365             for (var i = 0; i < properties.length; i++) {
60366                 checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
60367             }
60368             return sourceType;
60369         }
60370         /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
60371         function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
60372             if (rightIsThis === void 0) { rightIsThis = false; }
60373             var properties = node.properties;
60374             var property = properties[propertyIndex];
60375             if (property.kind === 281 /* PropertyAssignment */ || property.kind === 282 /* ShorthandPropertyAssignment */) {
60376                 var name = property.name;
60377                 var exprType = getLiteralTypeFromPropertyName(name);
60378                 if (isTypeUsableAsPropertyName(exprType)) {
60379                     var text = getPropertyNameFromType(exprType);
60380                     var prop = getPropertyOfType(objectLiteralType, text);
60381                     if (prop) {
60382                         markPropertyAsReferenced(prop, property, rightIsThis);
60383                         checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
60384                     }
60385                 }
60386                 var elementType = getIndexedAccessType(objectLiteralType, exprType, name);
60387                 var type = getFlowTypeOfDestructuring(property, elementType);
60388                 return checkDestructuringAssignment(property.kind === 282 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
60389             }
60390             else if (property.kind === 283 /* SpreadAssignment */) {
60391                 if (propertyIndex < properties.length - 1) {
60392                     error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60393                 }
60394                 else {
60395                     if (languageVersion < 99 /* ESNext */) {
60396                         checkExternalEmitHelpers(property, 4 /* Rest */);
60397                     }
60398                     var nonRestNames = [];
60399                     if (allProperties) {
60400                         for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
60401                             var otherProperty = allProperties_1[_i];
60402                             if (!ts.isSpreadAssignment(otherProperty)) {
60403                                 nonRestNames.push(otherProperty.name);
60404                             }
60405                         }
60406                     }
60407                     var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
60408                     checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60409                     return checkDestructuringAssignment(property.expression, type);
60410                 }
60411             }
60412             else {
60413                 error(property, ts.Diagnostics.Property_assignment_expected);
60414             }
60415         }
60416         function checkArrayLiteralAssignment(node, sourceType, checkMode) {
60417             var elements = node.elements;
60418             if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
60419                 checkExternalEmitHelpers(node, 512 /* Read */);
60420             }
60421             // This elementType will be used if the specific property corresponding to this index is not
60422             // present (aka the tuple element property). This call also checks that the parentType is in
60423             // fact an iterable or array (depending on target language).
60424             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType;
60425             for (var i = 0; i < elements.length; i++) {
60426                 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
60427             }
60428             return sourceType;
60429         }
60430         function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
60431             var elements = node.elements;
60432             var element = elements[elementIndex];
60433             if (element.kind !== 215 /* OmittedExpression */) {
60434                 if (element.kind !== 213 /* SpreadElement */) {
60435                     var indexType = getLiteralType(elementIndex);
60436                     if (isArrayLikeType(sourceType)) {
60437                         // We create a synthetic expression so that getIndexedAccessType doesn't get confused
60438                         // when the element is a SyntaxKind.ElementAccessExpression.
60439                         var accessFlags = hasDefaultValue(element) ? 8 /* NoTupleBoundsCheck */ : 0;
60440                         var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, createSyntheticExpression(element, indexType), accessFlags) || errorType;
60441                         var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
60442                         var type = getFlowTypeOfDestructuring(element, assignedType);
60443                         return checkDestructuringAssignment(element, type, checkMode);
60444                     }
60445                     return checkDestructuringAssignment(element, elementType, checkMode);
60446                 }
60447                 if (elementIndex < elements.length - 1) {
60448                     error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60449                 }
60450                 else {
60451                     var restExpression = element.expression;
60452                     if (restExpression.kind === 209 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) {
60453                         error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
60454                     }
60455                     else {
60456                         checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60457                         var type = everyType(sourceType, isTupleType) ?
60458                             mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
60459                             createArrayType(elementType);
60460                         return checkDestructuringAssignment(restExpression, type, checkMode);
60461                     }
60462                 }
60463             }
60464             return undefined;
60465         }
60466         function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
60467             var target;
60468             if (exprOrAssignment.kind === 282 /* ShorthandPropertyAssignment */) {
60469                 var prop = exprOrAssignment;
60470                 if (prop.objectAssignmentInitializer) {
60471                     // In strict null checking mode, if a default value of a non-undefined type is specified, remove
60472                     // undefined from the final type.
60473                     if (strictNullChecks &&
60474                         !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
60475                         sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
60476                     }
60477                     checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
60478                 }
60479                 target = exprOrAssignment.name;
60480             }
60481             else {
60482                 target = exprOrAssignment;
60483             }
60484             if (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) {
60485                 checkBinaryExpression(target, checkMode);
60486                 target = target.left;
60487             }
60488             if (target.kind === 193 /* ObjectLiteralExpression */) {
60489                 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
60490             }
60491             if (target.kind === 192 /* ArrayLiteralExpression */) {
60492                 return checkArrayLiteralAssignment(target, sourceType, checkMode);
60493             }
60494             return checkReferenceAssignment(target, sourceType, checkMode);
60495         }
60496         function checkReferenceAssignment(target, sourceType, checkMode) {
60497             var targetType = checkExpression(target, checkMode);
60498             var error = target.parent.kind === 283 /* SpreadAssignment */ ?
60499                 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
60500                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
60501             var optionalError = target.parent.kind === 283 /* SpreadAssignment */ ?
60502                 ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
60503                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
60504             if (checkReferenceExpression(target, error, optionalError)) {
60505                 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
60506             }
60507             if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
60508                 checkExternalEmitHelpers(target.parent, 524288 /* ClassPrivateFieldSet */);
60509             }
60510             return sourceType;
60511         }
60512         /**
60513          * This is a *shallow* check: An expression is side-effect-free if the
60514          * evaluation of the expression *itself* cannot produce side effects.
60515          * For example, x++ / 3 is side-effect free because the / operator
60516          * does not have side effects.
60517          * The intent is to "smell test" an expression for correctness in positions where
60518          * its value is discarded (e.g. the left side of the comma operator).
60519          */
60520         function isSideEffectFree(node) {
60521             node = ts.skipParentheses(node);
60522             switch (node.kind) {
60523                 case 75 /* Identifier */:
60524                 case 10 /* StringLiteral */:
60525                 case 13 /* RegularExpressionLiteral */:
60526                 case 198 /* TaggedTemplateExpression */:
60527                 case 211 /* TemplateExpression */:
60528                 case 14 /* NoSubstitutionTemplateLiteral */:
60529                 case 8 /* NumericLiteral */:
60530                 case 9 /* BigIntLiteral */:
60531                 case 106 /* TrueKeyword */:
60532                 case 91 /* FalseKeyword */:
60533                 case 100 /* NullKeyword */:
60534                 case 146 /* UndefinedKeyword */:
60535                 case 201 /* FunctionExpression */:
60536                 case 214 /* ClassExpression */:
60537                 case 202 /* ArrowFunction */:
60538                 case 192 /* ArrayLiteralExpression */:
60539                 case 193 /* ObjectLiteralExpression */:
60540                 case 204 /* TypeOfExpression */:
60541                 case 218 /* NonNullExpression */:
60542                 case 267 /* JsxSelfClosingElement */:
60543                 case 266 /* JsxElement */:
60544                     return true;
60545                 case 210 /* ConditionalExpression */:
60546                     return isSideEffectFree(node.whenTrue) &&
60547                         isSideEffectFree(node.whenFalse);
60548                 case 209 /* BinaryExpression */:
60549                     if (ts.isAssignmentOperator(node.operatorToken.kind)) {
60550                         return false;
60551                     }
60552                     return isSideEffectFree(node.left) &&
60553                         isSideEffectFree(node.right);
60554                 case 207 /* PrefixUnaryExpression */:
60555                 case 208 /* PostfixUnaryExpression */:
60556                     // Unary operators ~, !, +, and - have no side effects.
60557                     // The rest do.
60558                     switch (node.operator) {
60559                         case 53 /* ExclamationToken */:
60560                         case 39 /* PlusToken */:
60561                         case 40 /* MinusToken */:
60562                         case 54 /* TildeToken */:
60563                             return true;
60564                     }
60565                     return false;
60566                 // Some forms listed here for clarity
60567                 case 205 /* VoidExpression */: // Explicit opt-out
60568                 case 199 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
60569                 case 217 /* AsExpression */: // Not SEF, but can produce useful type warnings
60570                 default:
60571                     return false;
60572             }
60573         }
60574         function isTypeEqualityComparableTo(source, target) {
60575             return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
60576         }
60577         var CheckBinaryExpressionState;
60578         (function (CheckBinaryExpressionState) {
60579             CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft";
60580             CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight";
60581             CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck";
60582         })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {}));
60583         function checkBinaryExpression(node, checkMode) {
60584             var workStacks = {
60585                 expr: [node],
60586                 state: [0 /* MaybeCheckLeft */],
60587                 leftType: [undefined]
60588             };
60589             var stackIndex = 0;
60590             var lastResult;
60591             while (stackIndex >= 0) {
60592                 node = workStacks.expr[stackIndex];
60593                 switch (workStacks.state[stackIndex]) {
60594                     case 0 /* MaybeCheckLeft */: {
60595                         if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
60596                             finishInvocation(checkExpression(node.right, checkMode));
60597                             break;
60598                         }
60599                         checkGrammarNullishCoalesceWithLogicalExpression(node);
60600                         var operator = node.operatorToken.kind;
60601                         if (operator === 62 /* EqualsToken */ && (node.left.kind === 193 /* ObjectLiteralExpression */ || node.left.kind === 192 /* ArrayLiteralExpression */)) {
60602                             finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 104 /* ThisKeyword */));
60603                             break;
60604                         }
60605                         advanceState(1 /* CheckRight */);
60606                         maybeCheckExpression(node.left);
60607                         break;
60608                     }
60609                     case 1 /* CheckRight */: {
60610                         var leftType = lastResult;
60611                         workStacks.leftType[stackIndex] = leftType;
60612                         var operator = node.operatorToken.kind;
60613                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60614                             checkTruthinessOfType(leftType, node.left);
60615                         }
60616                         advanceState(2 /* FinishCheck */);
60617                         maybeCheckExpression(node.right);
60618                         break;
60619                     }
60620                     case 2 /* FinishCheck */: {
60621                         var leftType = workStacks.leftType[stackIndex];
60622                         var rightType = lastResult;
60623                         finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node));
60624                         break;
60625                     }
60626                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression");
60627                 }
60628             }
60629             return lastResult;
60630             function finishInvocation(result) {
60631                 lastResult = result;
60632                 stackIndex--;
60633             }
60634             /**
60635              * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new
60636              * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution.
60637              */
60638             function advanceState(nextState) {
60639                 workStacks.state[stackIndex] = nextState;
60640             }
60641             function maybeCheckExpression(node) {
60642                 if (ts.isBinaryExpression(node)) {
60643                     stackIndex++;
60644                     workStacks.expr[stackIndex] = node;
60645                     workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */;
60646                     workStacks.leftType[stackIndex] = undefined;
60647                 }
60648                 else {
60649                     lastResult = checkExpression(node, checkMode);
60650                 }
60651             }
60652         }
60653         function checkGrammarNullishCoalesceWithLogicalExpression(node) {
60654             var left = node.left, operatorToken = node.operatorToken, right = node.right;
60655             if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
60656                 if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60657                     grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60658                 }
60659                 if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60660                     grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60661                 }
60662             }
60663         }
60664         // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
60665         // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
60666         function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
60667             var operator = operatorToken.kind;
60668             if (operator === 62 /* EqualsToken */ && (left.kind === 193 /* ObjectLiteralExpression */ || left.kind === 192 /* ArrayLiteralExpression */)) {
60669                 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 104 /* ThisKeyword */);
60670             }
60671             var leftType;
60672             if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60673                 leftType = checkTruthinessExpression(left, checkMode);
60674             }
60675             else {
60676                 leftType = checkExpression(left, checkMode);
60677             }
60678             var rightType = checkExpression(right, checkMode);
60679             return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
60680         }
60681         function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
60682             var operator = operatorToken.kind;
60683             switch (operator) {
60684                 case 41 /* AsteriskToken */:
60685                 case 42 /* AsteriskAsteriskToken */:
60686                 case 65 /* AsteriskEqualsToken */:
60687                 case 66 /* AsteriskAsteriskEqualsToken */:
60688                 case 43 /* SlashToken */:
60689                 case 67 /* SlashEqualsToken */:
60690                 case 44 /* PercentToken */:
60691                 case 68 /* PercentEqualsToken */:
60692                 case 40 /* MinusToken */:
60693                 case 64 /* MinusEqualsToken */:
60694                 case 47 /* LessThanLessThanToken */:
60695                 case 69 /* LessThanLessThanEqualsToken */:
60696                 case 48 /* GreaterThanGreaterThanToken */:
60697                 case 70 /* GreaterThanGreaterThanEqualsToken */:
60698                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60699                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60700                 case 51 /* BarToken */:
60701                 case 73 /* BarEqualsToken */:
60702                 case 52 /* CaretToken */:
60703                 case 74 /* CaretEqualsToken */:
60704                 case 50 /* AmpersandToken */:
60705                 case 72 /* AmpersandEqualsToken */:
60706                     if (leftType === silentNeverType || rightType === silentNeverType) {
60707                         return silentNeverType;
60708                     }
60709                     leftType = checkNonNullType(leftType, left);
60710                     rightType = checkNonNullType(rightType, right);
60711                     var suggestedOperator = void 0;
60712                     // if a user tries to apply a bitwise operator to 2 boolean operands
60713                     // try and return them a helpful suggestion
60714                     if ((leftType.flags & 528 /* BooleanLike */) &&
60715                         (rightType.flags & 528 /* BooleanLike */) &&
60716                         (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
60717                         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));
60718                         return numberType;
60719                     }
60720                     else {
60721                         // otherwise just check each operand separately and report errors as normal
60722                         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);
60723                         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);
60724                         var resultType_1;
60725                         // If both are any or unknown, allow operation; assume it will resolve to number
60726                         if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
60727                             // Or, if neither could be bigint, implicit coercion results in a number result
60728                             !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
60729                             resultType_1 = numberType;
60730                         }
60731                         // At least one is assignable to bigint, so check that both are
60732                         else if (bothAreBigIntLike(leftType, rightType)) {
60733                             switch (operator) {
60734                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60735                                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60736                                     reportOperatorError();
60737                             }
60738                             resultType_1 = bigintType;
60739                         }
60740                         // Exactly one of leftType/rightType is assignable to bigint
60741                         else {
60742                             reportOperatorError(bothAreBigIntLike);
60743                             resultType_1 = errorType;
60744                         }
60745                         if (leftOk && rightOk) {
60746                             checkAssignmentOperator(resultType_1);
60747                         }
60748                         return resultType_1;
60749                     }
60750                 case 39 /* PlusToken */:
60751                 case 63 /* PlusEqualsToken */:
60752                     if (leftType === silentNeverType || rightType === silentNeverType) {
60753                         return silentNeverType;
60754                     }
60755                     if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) {
60756                         leftType = checkNonNullType(leftType, left);
60757                         rightType = checkNonNullType(rightType, right);
60758                     }
60759                     var resultType = void 0;
60760                     if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
60761                         // Operands of an enum type are treated as having the primitive type Number.
60762                         // If both operands are of the Number primitive type, the result is of the Number primitive type.
60763                         resultType = numberType;
60764                     }
60765                     else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
60766                         // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
60767                         resultType = bigintType;
60768                     }
60769                     else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) {
60770                         // If one or both operands are of the String primitive type, the result is of the String primitive type.
60771                         resultType = stringType;
60772                     }
60773                     else if (isTypeAny(leftType) || isTypeAny(rightType)) {
60774                         // Otherwise, the result is of type Any.
60775                         // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
60776                         resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
60777                     }
60778                     // Symbols are not allowed at all in arithmetic expressions
60779                     if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
60780                         return resultType;
60781                     }
60782                     if (!resultType) {
60783                         // Types that have a reasonably good chance of being a valid operand type.
60784                         // If both types have an awaited type of one of these, we'll assume the user
60785                         // might be missing an await without doing an exhaustive check that inserting
60786                         // await(s) will actually be a completely valid binary expression.
60787                         var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 3 /* AnyOrUnknown */;
60788                         reportOperatorError(function (left, right) {
60789                             return isTypeAssignableToKind(left, closeEnoughKind_1) &&
60790                                 isTypeAssignableToKind(right, closeEnoughKind_1);
60791                         });
60792                         return anyType;
60793                     }
60794                     if (operator === 63 /* PlusEqualsToken */) {
60795                         checkAssignmentOperator(resultType);
60796                     }
60797                     return resultType;
60798                 case 29 /* LessThanToken */:
60799                 case 31 /* GreaterThanToken */:
60800                 case 32 /* LessThanEqualsToken */:
60801                 case 33 /* GreaterThanEqualsToken */:
60802                     if (checkForDisallowedESSymbolOperand(operator)) {
60803                         leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
60804                         rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
60805                         reportOperatorErrorUnless(function (left, right) {
60806                             return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
60807                         });
60808                     }
60809                     return booleanType;
60810                 case 34 /* EqualsEqualsToken */:
60811                 case 35 /* ExclamationEqualsToken */:
60812                 case 36 /* EqualsEqualsEqualsToken */:
60813                 case 37 /* ExclamationEqualsEqualsToken */:
60814                     reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
60815                     return booleanType;
60816                 case 98 /* InstanceOfKeyword */:
60817                     return checkInstanceOfExpression(left, right, leftType, rightType);
60818                 case 97 /* InKeyword */:
60819                     return checkInExpression(left, right, leftType, rightType);
60820                 case 55 /* AmpersandAmpersandToken */:
60821                     return getTypeFacts(leftType) & 4194304 /* Truthy */ ?
60822                         getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
60823                         leftType;
60824                 case 56 /* BarBarToken */:
60825                     return getTypeFacts(leftType) & 8388608 /* Falsy */ ?
60826                         getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
60827                         leftType;
60828                 case 60 /* QuestionQuestionToken */:
60829                     return getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
60830                         getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
60831                         leftType;
60832                 case 62 /* EqualsToken */:
60833                     var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
60834                     checkAssignmentDeclaration(declKind, rightType);
60835                     if (isAssignmentDeclaration(declKind)) {
60836                         if (!(rightType.flags & 524288 /* Object */) ||
60837                             declKind !== 2 /* ModuleExports */ &&
60838                                 declKind !== 6 /* Prototype */ &&
60839                                 !isEmptyObjectType(rightType) &&
60840                                 !isFunctionObjectType(rightType) &&
60841                                 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
60842                             // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
60843                             checkAssignmentOperator(rightType);
60844                         }
60845                         return leftType;
60846                     }
60847                     else {
60848                         checkAssignmentOperator(rightType);
60849                         return getRegularTypeOfObjectLiteral(rightType);
60850                     }
60851                 case 27 /* CommaToken */:
60852                     if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
60853                         error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
60854                     }
60855                     return rightType;
60856                 default:
60857                     return ts.Debug.fail();
60858             }
60859             function bothAreBigIntLike(left, right) {
60860                 return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
60861             }
60862             function checkAssignmentDeclaration(kind, rightType) {
60863                 if (kind === 2 /* ModuleExports */) {
60864                     for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
60865                         var prop = _a[_i];
60866                         var propType = getTypeOfSymbol(prop);
60867                         if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
60868                             var name = prop.escapedName;
60869                             var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
60870                             if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
60871                                 addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop);
60872                                 addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol);
60873                             }
60874                         }
60875                     }
60876                 }
60877             }
60878             function isEvalNode(node) {
60879                 return node.kind === 75 /* Identifier */ && node.escapedText === "eval";
60880             }
60881             // Return true if there was no error, false if there was an error.
60882             function checkForDisallowedESSymbolOperand(operator) {
60883                 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
60884                     maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
60885                         undefined;
60886                 if (offendingSymbolOperand) {
60887                     error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
60888                     return false;
60889                 }
60890                 return true;
60891             }
60892             function getSuggestedBooleanOperator(operator) {
60893                 switch (operator) {
60894                     case 51 /* BarToken */:
60895                     case 73 /* BarEqualsToken */:
60896                         return 56 /* BarBarToken */;
60897                     case 52 /* CaretToken */:
60898                     case 74 /* CaretEqualsToken */:
60899                         return 37 /* ExclamationEqualsEqualsToken */;
60900                     case 50 /* AmpersandToken */:
60901                     case 72 /* AmpersandEqualsToken */:
60902                         return 55 /* AmpersandAmpersandToken */;
60903                     default:
60904                         return undefined;
60905                 }
60906             }
60907             function checkAssignmentOperator(valueType) {
60908                 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
60909                     // TypeScript 1.0 spec (April 2014): 4.17
60910                     // An assignment of the form
60911                     //    VarExpr = ValueExpr
60912                     // requires VarExpr to be classified as a reference
60913                     // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
60914                     // and the type of the non-compound operation to be assignable to the type of VarExpr.
60915                     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)
60916                         && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
60917                         // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
60918                         checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
60919                     }
60920                 }
60921             }
60922             function isAssignmentDeclaration(kind) {
60923                 switch (kind) {
60924                     case 2 /* ModuleExports */:
60925                         return true;
60926                     case 1 /* ExportsProperty */:
60927                     case 5 /* Property */:
60928                     case 6 /* Prototype */:
60929                     case 3 /* PrototypeProperty */:
60930                     case 4 /* ThisProperty */:
60931                         var symbol = getSymbolOfNode(left);
60932                         var init = ts.getAssignedExpandoInitializer(right);
60933                         return init && ts.isObjectLiteralExpression(init) &&
60934                             symbol && ts.hasEntries(symbol.exports);
60935                     default:
60936                         return false;
60937                 }
60938             }
60939             /**
60940              * Returns true if an error is reported
60941              */
60942             function reportOperatorErrorUnless(typesAreCompatible) {
60943                 if (!typesAreCompatible(leftType, rightType)) {
60944                     reportOperatorError(typesAreCompatible);
60945                     return true;
60946                 }
60947                 return false;
60948             }
60949             function reportOperatorError(isRelated) {
60950                 var _a;
60951                 var wouldWorkWithAwait = false;
60952                 var errNode = errorNode || operatorToken;
60953                 if (isRelated) {
60954                     var awaitedLeftType = getAwaitedType(leftType);
60955                     var awaitedRightType = getAwaitedType(rightType);
60956                     wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
60957                         && !!(awaitedLeftType && awaitedRightType)
60958                         && isRelated(awaitedLeftType, awaitedRightType);
60959                 }
60960                 var effectiveLeft = leftType;
60961                 var effectiveRight = rightType;
60962                 if (!wouldWorkWithAwait && isRelated) {
60963                     _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
60964                 }
60965                 var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
60966                 if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
60967                     errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
60968                 }
60969             }
60970             function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
60971                 var typeName;
60972                 switch (operatorToken.kind) {
60973                     case 36 /* EqualsEqualsEqualsToken */:
60974                     case 34 /* EqualsEqualsToken */:
60975                         typeName = "false";
60976                         break;
60977                     case 37 /* ExclamationEqualsEqualsToken */:
60978                     case 35 /* ExclamationEqualsToken */:
60979                         typeName = "true";
60980                 }
60981                 if (typeName) {
60982                     return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
60983                 }
60984                 return undefined;
60985             }
60986         }
60987         function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
60988             var effectiveLeft = leftType;
60989             var effectiveRight = rightType;
60990             var leftBase = getBaseTypeOfLiteralType(leftType);
60991             var rightBase = getBaseTypeOfLiteralType(rightType);
60992             if (!isRelated(leftBase, rightBase)) {
60993                 effectiveLeft = leftBase;
60994                 effectiveRight = rightBase;
60995             }
60996             return [effectiveLeft, effectiveRight];
60997         }
60998         function checkYieldExpression(node) {
60999             // Grammar checking
61000             if (produceDiagnostics) {
61001                 if (!(node.flags & 8192 /* YieldContext */)) {
61002                     grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
61003                 }
61004                 if (isInParameterInitializerBeforeContainingFunction(node)) {
61005                     error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
61006                 }
61007             }
61008             var func = ts.getContainingFunction(node);
61009             if (!func)
61010                 return anyType;
61011             var functionFlags = ts.getFunctionFlags(func);
61012             if (!(functionFlags & 1 /* Generator */)) {
61013                 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
61014                 return anyType;
61015             }
61016             var isAsync = (functionFlags & 2 /* Async */) !== 0;
61017             if (node.asteriskToken) {
61018                 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
61019                 // and __asyncValues helpers
61020                 if (isAsync && languageVersion < 99 /* ESNext */) {
61021                     checkExternalEmitHelpers(node, 53248 /* AsyncDelegatorIncludes */);
61022                 }
61023                 // Generator functions prior to ES2015 require the __values helper
61024                 if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
61025                     checkExternalEmitHelpers(node, 256 /* Values */);
61026                 }
61027             }
61028             // There is no point in doing an assignability check if the function
61029             // has no explicit return type because the return type is directly computed
61030             // from the yield expressions.
61031             var returnType = getReturnTypeFromAnnotation(func);
61032             var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
61033             var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
61034             var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
61035             var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
61036             var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
61037             var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
61038             if (returnType && yieldedType) {
61039                 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
61040             }
61041             if (node.asteriskToken) {
61042                 var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
61043                 return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
61044                     || anyType;
61045             }
61046             else if (returnType) {
61047                 return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
61048                     || anyType;
61049             }
61050             return getContextualIterationType(2 /* Next */, func) || anyType;
61051         }
61052         function checkConditionalExpression(node, checkMode) {
61053             var type = checkTruthinessExpression(node.condition);
61054             checkTestingKnownTruthyCallableType(node.condition, node.whenTrue, type);
61055             var type1 = checkExpression(node.whenTrue, checkMode);
61056             var type2 = checkExpression(node.whenFalse, checkMode);
61057             return getUnionType([type1, type2], 2 /* Subtype */);
61058         }
61059         function checkTemplateExpression(node) {
61060             // We just want to check each expressions, but we are unconcerned with
61061             // the type of each expression, as any value may be coerced into a string.
61062             // It is worth asking whether this is what we really want though.
61063             // A place where we actually *are* concerned with the expressions' types are
61064             // in tagged templates.
61065             ts.forEach(node.templateSpans, function (templateSpan) {
61066                 if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) {
61067                     error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
61068                 }
61069             });
61070             return stringType;
61071         }
61072         function getContextNode(node) {
61073             if (node.kind === 274 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
61074                 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)
61075             }
61076             return node;
61077         }
61078         function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
61079             var context = getContextNode(node);
61080             var saveContextualType = context.contextualType;
61081             var saveInferenceContext = context.inferenceContext;
61082             try {
61083                 context.contextualType = contextualType;
61084                 context.inferenceContext = inferenceContext;
61085                 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
61086                 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
61087                 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
61088                 // here would be to not mark contextually typed literals as fresh in the first place.
61089                 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
61090                     getRegularTypeOfLiteralType(type) : type;
61091                 return result;
61092             }
61093             finally {
61094                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61095                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61096                 // may hold onto the checker that created it.
61097                 context.contextualType = saveContextualType;
61098                 context.inferenceContext = saveInferenceContext;
61099             }
61100         }
61101         function checkExpressionCached(node, checkMode) {
61102             var links = getNodeLinks(node);
61103             if (!links.resolvedType) {
61104                 if (checkMode && checkMode !== 0 /* Normal */) {
61105                     return checkExpression(node, checkMode);
61106                 }
61107                 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
61108                 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
61109                 // to the top of the stack ensures all transient types are computed from a known point.
61110                 var saveFlowLoopStart = flowLoopStart;
61111                 var saveFlowTypeCache = flowTypeCache;
61112                 flowLoopStart = flowLoopCount;
61113                 flowTypeCache = undefined;
61114                 links.resolvedType = checkExpression(node, checkMode);
61115                 flowTypeCache = saveFlowTypeCache;
61116                 flowLoopStart = saveFlowLoopStart;
61117             }
61118             return links.resolvedType;
61119         }
61120         function isTypeAssertion(node) {
61121             node = ts.skipParentheses(node);
61122             return node.kind === 199 /* TypeAssertionExpression */ || node.kind === 217 /* AsExpression */;
61123         }
61124         function checkDeclarationInitializer(declaration, contextualType) {
61125             var initializer = ts.getEffectiveInitializer(declaration);
61126             var type = getQuickTypeOfExpression(initializer) ||
61127                 (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
61128             return ts.isParameter(declaration) && declaration.name.kind === 190 /* ArrayBindingPattern */ &&
61129                 isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
61130                 padTupleType(type, declaration.name) : type;
61131         }
61132         function padTupleType(type, pattern) {
61133             var patternElements = pattern.elements;
61134             var arity = getTypeReferenceArity(type);
61135             var elementTypes = arity ? getTypeArguments(type).slice() : [];
61136             for (var i = arity; i < patternElements.length; i++) {
61137                 var e = patternElements[i];
61138                 if (i < patternElements.length - 1 || !(e.kind === 191 /* BindingElement */ && e.dotDotDotToken)) {
61139                     elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
61140                     if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
61141                         reportImplicitAny(e, anyType);
61142                     }
61143                 }
61144             }
61145             return createTupleType(elementTypes, type.target.minLength, /*hasRestElement*/ false, type.target.readonly);
61146         }
61147         function widenTypeInferredFromInitializer(declaration, type) {
61148             var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
61149             if (ts.isInJSFile(declaration)) {
61150                 if (widened.flags & 98304 /* Nullable */) {
61151                     reportImplicitAny(declaration, anyType);
61152                     return anyType;
61153                 }
61154                 else if (isEmptyArrayLiteralType(widened)) {
61155                     reportImplicitAny(declaration, anyArrayType);
61156                     return anyArrayType;
61157                 }
61158             }
61159             return widened;
61160         }
61161         function isLiteralOfContextualType(candidateType, contextualType) {
61162             if (contextualType) {
61163                 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
61164                     var types = contextualType.types;
61165                     return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
61166                 }
61167                 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
61168                     // If the contextual type is a type variable constrained to a primitive type, consider
61169                     // this a literal context for literals of that primitive type. For example, given a
61170                     // type parameter 'T extends string', infer string literal types for T.
61171                     var constraint = getBaseConstraintOfType(contextualType) || unknownType;
61172                     return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61173                         maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61174                         maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61175                         maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
61176                         isLiteralOfContextualType(candidateType, constraint);
61177                 }
61178                 // If the contextual type is a literal of a particular primitive type, we consider this a
61179                 // literal context for all literals of that primitive type.
61180                 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61181                     contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61182                     contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61183                     contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
61184                     contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
61185             }
61186             return false;
61187         }
61188         function isConstContext(node) {
61189             var parent = node.parent;
61190             return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
61191                 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
61192                 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
61193         }
61194         function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
61195             var type = checkExpression(node, checkMode, forceTuple);
61196             return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
61197                 isTypeAssertion(node) ? type :
61198                     getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
61199         }
61200         function checkPropertyAssignment(node, checkMode) {
61201             // Do not use hasDynamicName here, because that returns false for well known symbols.
61202             // We want to perform checkComputedPropertyName for all computed properties, including
61203             // well known symbols.
61204             if (node.name.kind === 154 /* ComputedPropertyName */) {
61205                 checkComputedPropertyName(node.name);
61206             }
61207             return checkExpressionForMutableLocation(node.initializer, checkMode);
61208         }
61209         function checkObjectLiteralMethod(node, checkMode) {
61210             // Grammar checking
61211             checkGrammarMethod(node);
61212             // Do not use hasDynamicName here, because that returns false for well known symbols.
61213             // We want to perform checkComputedPropertyName for all computed properties, including
61214             // well known symbols.
61215             if (node.name.kind === 154 /* ComputedPropertyName */) {
61216                 checkComputedPropertyName(node.name);
61217             }
61218             var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61219             return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61220         }
61221         function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
61222             if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
61223                 var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
61224                 var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
61225                 var signature = callSignature || constructSignature;
61226                 if (signature && signature.typeParameters) {
61227                     var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
61228                     if (contextualType) {
61229                         var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
61230                         if (contextualSignature && !contextualSignature.typeParameters) {
61231                             if (checkMode & 8 /* SkipGenericFunctions */) {
61232                                 skippedGenericFunction(node, checkMode);
61233                                 return anyFunctionType;
61234                             }
61235                             var context = getInferenceContext(node);
61236                             // We have an expression that is an argument of a generic function for which we are performing
61237                             // type argument inference. The expression is of a function type with a single generic call
61238                             // signature and a contextual function type with a single non-generic call signature. Now check
61239                             // if the outer function returns a function type with a single non-generic call signature and
61240                             // if some of the outer function type parameters have no inferences so far. If so, we can
61241                             // potentially add inferred type parameters to the outer function return type.
61242                             var returnType = context.signature && getReturnTypeOfSignature(context.signature);
61243                             var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
61244                             if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
61245                                 // Instantiate the signature with its own type parameters as type arguments, possibly
61246                                 // renaming the type parameters to ensure they have unique names.
61247                                 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
61248                                 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
61249                                 // Infer from the parameters of the instantiated signature to the parameters of the
61250                                 // contextual signature starting with an empty set of inference candidates.
61251                                 var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
61252                                 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
61253                                     inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
61254                                 });
61255                                 if (ts.some(inferences_3, hasInferenceCandidates)) {
61256                                     // We have inference candidates, indicating that one or more type parameters are referenced
61257                                     // in the parameter types of the contextual signature. Now also infer from the return type.
61258                                     applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
61259                                         inferTypes(inferences_3, source, target);
61260                                     });
61261                                     // If the type parameters for which we produced candidates do not have any inferences yet,
61262                                     // we adopt the new inference candidates and add the type parameters of the expression type
61263                                     // to the set of inferred type parameters for the outer function return type.
61264                                     if (!hasOverlappingInferences(context.inferences, inferences_3)) {
61265                                         mergeInferences(context.inferences, inferences_3);
61266                                         context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
61267                                         return getOrCreateTypeFromSignature(instantiatedSignature);
61268                                     }
61269                                 }
61270                             }
61271                             return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
61272                         }
61273                     }
61274                 }
61275             }
61276             return type;
61277         }
61278         function skippedGenericFunction(node, checkMode) {
61279             if (checkMode & 2 /* Inferential */) {
61280                 // We have skipped a generic function during inferential typing. Obtain the inference context and
61281                 // indicate this has occurred such that we know a second pass of inference is be needed.
61282                 var context = getInferenceContext(node);
61283                 context.flags |= 4 /* SkippedGenericFunction */;
61284             }
61285         }
61286         function hasInferenceCandidates(info) {
61287             return !!(info.candidates || info.contraCandidates);
61288         }
61289         function hasOverlappingInferences(a, b) {
61290             for (var i = 0; i < a.length; i++) {
61291                 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
61292                     return true;
61293                 }
61294             }
61295             return false;
61296         }
61297         function mergeInferences(target, source) {
61298             for (var i = 0; i < target.length; i++) {
61299                 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
61300                     target[i] = source[i];
61301                 }
61302             }
61303         }
61304         function getUniqueTypeParameters(context, typeParameters) {
61305             var result = [];
61306             var oldTypeParameters;
61307             var newTypeParameters;
61308             for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
61309                 var tp = typeParameters_2[_i];
61310                 var name = tp.symbol.escapedName;
61311                 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
61312                     var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
61313                     var symbol = createSymbol(262144 /* TypeParameter */, newName);
61314                     var newTypeParameter = createTypeParameter(symbol);
61315                     newTypeParameter.target = tp;
61316                     oldTypeParameters = ts.append(oldTypeParameters, tp);
61317                     newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
61318                     result.push(newTypeParameter);
61319                 }
61320                 else {
61321                     result.push(tp);
61322                 }
61323             }
61324             if (newTypeParameters) {
61325                 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
61326                 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
61327                     var tp = newTypeParameters_1[_a];
61328                     tp.mapper = mapper;
61329                 }
61330             }
61331             return result;
61332         }
61333         function hasTypeParameterByName(typeParameters, name) {
61334             return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
61335         }
61336         function getUniqueTypeParameterName(typeParameters, baseName) {
61337             var len = baseName.length;
61338             while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
61339                 len--;
61340             var s = baseName.slice(0, len);
61341             for (var index = 1; true; index++) {
61342                 var augmentedName = (s + index);
61343                 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
61344                     return augmentedName;
61345                 }
61346             }
61347         }
61348         function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
61349             var signature = getSingleCallSignature(funcType);
61350             if (signature && !signature.typeParameters) {
61351                 return getReturnTypeOfSignature(signature);
61352             }
61353         }
61354         function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
61355             var funcType = checkExpression(expr.expression);
61356             var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
61357             var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
61358             return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
61359         }
61360         /**
61361          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61362          * with computing the type and may not fully check all contained sub-expressions for errors.
61363          */
61364         function getTypeOfExpression(node) {
61365             // Don't bother caching types that require no flow analysis and are quick to compute.
61366             var quickType = getQuickTypeOfExpression(node);
61367             if (quickType) {
61368                 return quickType;
61369             }
61370             // If a type has been cached for the node, return it.
61371             if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
61372                 var cachedType = flowTypeCache[getNodeId(node)];
61373                 if (cachedType) {
61374                     return cachedType;
61375                 }
61376             }
61377             var startInvocationCount = flowInvocationCount;
61378             var type = checkExpression(node);
61379             // If control flow analysis was required to determine the type, it is worth caching.
61380             if (flowInvocationCount !== startInvocationCount) {
61381                 var cache = flowTypeCache || (flowTypeCache = []);
61382                 cache[getNodeId(node)] = type;
61383                 node.flags |= 67108864 /* TypeCached */;
61384             }
61385             return type;
61386         }
61387         function getQuickTypeOfExpression(node) {
61388             var expr = ts.skipParentheses(node);
61389             // Optimize for the common case of a call to a function with a single non-generic call
61390             // signature where we can just fetch the return type without checking the arguments.
61391             if (ts.isCallExpression(expr) && expr.expression.kind !== 102 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
61392                 var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
61393                     getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
61394                 if (type) {
61395                     return type;
61396                 }
61397             }
61398             else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
61399                 return getTypeFromTypeNode(expr.type);
61400             }
61401             else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
61402                 node.kind === 106 /* TrueKeyword */ || node.kind === 91 /* FalseKeyword */) {
61403                 return checkExpression(node);
61404             }
61405             return undefined;
61406         }
61407         /**
61408          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61409          * with computing the type and may not fully check all contained sub-expressions for errors.
61410          * It is intended for uses where you know there is no contextual type,
61411          * and requesting the contextual type might cause a circularity or other bad behaviour.
61412          * It sets the contextual type of the node to any before calling getTypeOfExpression.
61413          */
61414         function getContextFreeTypeOfExpression(node) {
61415             var links = getNodeLinks(node);
61416             if (links.contextFreeType) {
61417                 return links.contextFreeType;
61418             }
61419             var saveContextualType = node.contextualType;
61420             node.contextualType = anyType;
61421             try {
61422                 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
61423                 return type;
61424             }
61425             finally {
61426                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61427                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61428                 // may hold onto the checker that created it.
61429                 node.contextualType = saveContextualType;
61430             }
61431         }
61432         function checkExpression(node, checkMode, forceTuple) {
61433             var saveCurrentNode = currentNode;
61434             currentNode = node;
61435             instantiationCount = 0;
61436             var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
61437             var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61438             if (isConstEnumObjectType(type)) {
61439                 checkConstEnumAccess(node, type);
61440             }
61441             currentNode = saveCurrentNode;
61442             return type;
61443         }
61444         function checkConstEnumAccess(node, type) {
61445             // enum object type for const enums are only permitted in:
61446             // - 'left' in property access
61447             // - 'object' in indexed access
61448             // - target in rhs of import statement
61449             var ok = (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.expression === node) ||
61450                 (node.parent.kind === 195 /* ElementAccessExpression */ && node.parent.expression === node) ||
61451                 ((node.kind === 75 /* Identifier */ || node.kind === 153 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
61452                     (node.parent.kind === 172 /* TypeQuery */ && node.parent.exprName === node)) ||
61453                 (node.parent.kind === 263 /* ExportSpecifier */); // We allow reexporting const enums
61454             if (!ok) {
61455                 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);
61456             }
61457             if (compilerOptions.isolatedModules) {
61458                 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
61459                 var constEnumDeclaration = type.symbol.valueDeclaration;
61460                 if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
61461                     error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
61462                 }
61463             }
61464         }
61465         function checkParenthesizedExpression(node, checkMode) {
61466             var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
61467             if (tag) {
61468                 return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
61469             }
61470             return checkExpression(node.expression, checkMode);
61471         }
61472         function checkExpressionWorker(node, checkMode, forceTuple) {
61473             var kind = node.kind;
61474             if (cancellationToken) {
61475                 // Only bother checking on a few construct kinds.  We don't want to be excessively
61476                 // hitting the cancellation token on every node we check.
61477                 switch (kind) {
61478                     case 214 /* ClassExpression */:
61479                     case 201 /* FunctionExpression */:
61480                     case 202 /* ArrowFunction */:
61481                         cancellationToken.throwIfCancellationRequested();
61482                 }
61483             }
61484             switch (kind) {
61485                 case 75 /* Identifier */:
61486                     return checkIdentifier(node);
61487                 case 104 /* ThisKeyword */:
61488                     return checkThisExpression(node);
61489                 case 102 /* SuperKeyword */:
61490                     return checkSuperExpression(node);
61491                 case 100 /* NullKeyword */:
61492                     return nullWideningType;
61493                 case 14 /* NoSubstitutionTemplateLiteral */:
61494                 case 10 /* StringLiteral */:
61495                     return getFreshTypeOfLiteralType(getLiteralType(node.text));
61496                 case 8 /* NumericLiteral */:
61497                     checkGrammarNumericLiteral(node);
61498                     return getFreshTypeOfLiteralType(getLiteralType(+node.text));
61499                 case 9 /* BigIntLiteral */:
61500                     checkGrammarBigIntLiteral(node);
61501                     return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
61502                 case 106 /* TrueKeyword */:
61503                     return trueType;
61504                 case 91 /* FalseKeyword */:
61505                     return falseType;
61506                 case 211 /* TemplateExpression */:
61507                     return checkTemplateExpression(node);
61508                 case 13 /* RegularExpressionLiteral */:
61509                     return globalRegExpType;
61510                 case 192 /* ArrayLiteralExpression */:
61511                     return checkArrayLiteral(node, checkMode, forceTuple);
61512                 case 193 /* ObjectLiteralExpression */:
61513                     return checkObjectLiteral(node, checkMode);
61514                 case 194 /* PropertyAccessExpression */:
61515                     return checkPropertyAccessExpression(node);
61516                 case 153 /* QualifiedName */:
61517                     return checkQualifiedName(node);
61518                 case 195 /* ElementAccessExpression */:
61519                     return checkIndexedAccess(node);
61520                 case 196 /* CallExpression */:
61521                     if (node.expression.kind === 96 /* ImportKeyword */) {
61522                         return checkImportCallExpression(node);
61523                     }
61524                 // falls through
61525                 case 197 /* NewExpression */:
61526                     return checkCallExpression(node, checkMode);
61527                 case 198 /* TaggedTemplateExpression */:
61528                     return checkTaggedTemplateExpression(node);
61529                 case 200 /* ParenthesizedExpression */:
61530                     return checkParenthesizedExpression(node, checkMode);
61531                 case 214 /* ClassExpression */:
61532                     return checkClassExpression(node);
61533                 case 201 /* FunctionExpression */:
61534                 case 202 /* ArrowFunction */:
61535                     return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61536                 case 204 /* TypeOfExpression */:
61537                     return checkTypeOfExpression(node);
61538                 case 199 /* TypeAssertionExpression */:
61539                 case 217 /* AsExpression */:
61540                     return checkAssertion(node);
61541                 case 218 /* NonNullExpression */:
61542                     return checkNonNullAssertion(node);
61543                 case 219 /* MetaProperty */:
61544                     return checkMetaProperty(node);
61545                 case 203 /* DeleteExpression */:
61546                     return checkDeleteExpression(node);
61547                 case 205 /* VoidExpression */:
61548                     return checkVoidExpression(node);
61549                 case 206 /* AwaitExpression */:
61550                     return checkAwaitExpression(node);
61551                 case 207 /* PrefixUnaryExpression */:
61552                     return checkPrefixUnaryExpression(node);
61553                 case 208 /* PostfixUnaryExpression */:
61554                     return checkPostfixUnaryExpression(node);
61555                 case 209 /* BinaryExpression */:
61556                     return checkBinaryExpression(node, checkMode);
61557                 case 210 /* ConditionalExpression */:
61558                     return checkConditionalExpression(node, checkMode);
61559                 case 213 /* SpreadElement */:
61560                     return checkSpreadExpression(node, checkMode);
61561                 case 215 /* OmittedExpression */:
61562                     return undefinedWideningType;
61563                 case 212 /* YieldExpression */:
61564                     return checkYieldExpression(node);
61565                 case 220 /* SyntheticExpression */:
61566                     return node.type;
61567                 case 276 /* JsxExpression */:
61568                     return checkJsxExpression(node, checkMode);
61569                 case 266 /* JsxElement */:
61570                     return checkJsxElement(node, checkMode);
61571                 case 267 /* JsxSelfClosingElement */:
61572                     return checkJsxSelfClosingElement(node, checkMode);
61573                 case 270 /* JsxFragment */:
61574                     return checkJsxFragment(node);
61575                 case 274 /* JsxAttributes */:
61576                     return checkJsxAttributes(node, checkMode);
61577                 case 268 /* JsxOpeningElement */:
61578                     ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
61579             }
61580             return errorType;
61581         }
61582         // DECLARATION AND STATEMENT TYPE CHECKING
61583         function checkTypeParameter(node) {
61584             // Grammar Checking
61585             if (node.expression) {
61586                 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
61587             }
61588             checkSourceElement(node.constraint);
61589             checkSourceElement(node.default);
61590             var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
61591             // Resolve base constraint to reveal circularity errors
61592             getBaseConstraintOfType(typeParameter);
61593             if (!hasNonCircularTypeParameterDefault(typeParameter)) {
61594                 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
61595             }
61596             var constraintType = getConstraintOfTypeParameter(typeParameter);
61597             var defaultType = getDefaultFromTypeParameter(typeParameter);
61598             if (constraintType && defaultType) {
61599                 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
61600             }
61601             if (produceDiagnostics) {
61602                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
61603             }
61604         }
61605         function checkParameter(node) {
61606             // Grammar checking
61607             // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
61608             // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
61609             // or if its FunctionBody is strict code(11.1.5).
61610             checkGrammarDecoratorsAndModifiers(node);
61611             checkVariableLikeDeclaration(node);
61612             var func = ts.getContainingFunction(node);
61613             if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
61614                 if (!(func.kind === 162 /* Constructor */ && ts.nodeIsPresent(func.body))) {
61615                     error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
61616                 }
61617                 if (func.kind === 162 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") {
61618                     error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
61619                 }
61620             }
61621             if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
61622                 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
61623             }
61624             if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
61625                 if (func.parameters.indexOf(node) !== 0) {
61626                     error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
61627                 }
61628                 if (func.kind === 162 /* Constructor */ || func.kind === 166 /* ConstructSignature */ || func.kind === 171 /* ConstructorType */) {
61629                     error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
61630                 }
61631                 if (func.kind === 202 /* ArrowFunction */) {
61632                     error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
61633                 }
61634                 if (func.kind === 163 /* GetAccessor */ || func.kind === 164 /* SetAccessor */) {
61635                     error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
61636                 }
61637             }
61638             // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
61639             // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
61640             if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
61641                 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
61642             }
61643         }
61644         function checkTypePredicate(node) {
61645             var parent = getTypePredicateParent(node);
61646             if (!parent) {
61647                 // The parent must not be valid.
61648                 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
61649                 return;
61650             }
61651             var signature = getSignatureFromDeclaration(parent);
61652             var typePredicate = getTypePredicateOfSignature(signature);
61653             if (!typePredicate) {
61654                 return;
61655             }
61656             checkSourceElement(node.type);
61657             var parameterName = node.parameterName;
61658             if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
61659                 getTypeFromThisTypeNode(parameterName);
61660             }
61661             else {
61662                 if (typePredicate.parameterIndex >= 0) {
61663                     if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
61664                         error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
61665                     }
61666                     else {
61667                         if (typePredicate.type) {
61668                             var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
61669                             checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, 
61670                             /*headMessage*/ undefined, leadingError);
61671                         }
61672                     }
61673                 }
61674                 else if (parameterName) {
61675                     var hasReportedError = false;
61676                     for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
61677                         var name = _a[_i].name;
61678                         if (ts.isBindingPattern(name) &&
61679                             checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
61680                             hasReportedError = true;
61681                             break;
61682                         }
61683                     }
61684                     if (!hasReportedError) {
61685                         error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
61686                     }
61687                 }
61688             }
61689         }
61690         function getTypePredicateParent(node) {
61691             switch (node.parent.kind) {
61692                 case 202 /* ArrowFunction */:
61693                 case 165 /* CallSignature */:
61694                 case 244 /* FunctionDeclaration */:
61695                 case 201 /* FunctionExpression */:
61696                 case 170 /* FunctionType */:
61697                 case 161 /* MethodDeclaration */:
61698                 case 160 /* MethodSignature */:
61699                     var parent = node.parent;
61700                     if (node === parent.type) {
61701                         return parent;
61702                     }
61703             }
61704         }
61705         function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
61706             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
61707                 var element = _a[_i];
61708                 if (ts.isOmittedExpression(element)) {
61709                     continue;
61710                 }
61711                 var name = element.name;
61712                 if (name.kind === 75 /* Identifier */ && name.escapedText === predicateVariableName) {
61713                     error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
61714                     return true;
61715                 }
61716                 else if (name.kind === 190 /* ArrayBindingPattern */ || name.kind === 189 /* ObjectBindingPattern */) {
61717                     if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
61718                         return true;
61719                     }
61720                 }
61721             }
61722         }
61723         function checkSignatureDeclaration(node) {
61724             // Grammar checking
61725             if (node.kind === 167 /* IndexSignature */) {
61726                 checkGrammarIndexSignature(node);
61727             }
61728             // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
61729             else if (node.kind === 170 /* FunctionType */ || node.kind === 244 /* FunctionDeclaration */ || node.kind === 171 /* ConstructorType */ ||
61730                 node.kind === 165 /* CallSignature */ || node.kind === 162 /* Constructor */ ||
61731                 node.kind === 166 /* ConstructSignature */) {
61732                 checkGrammarFunctionLikeDeclaration(node);
61733             }
61734             var functionFlags = ts.getFunctionFlags(node);
61735             if (!(functionFlags & 4 /* Invalid */)) {
61736                 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
61737                 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
61738                     checkExternalEmitHelpers(node, 12288 /* AsyncGeneratorIncludes */);
61739                 }
61740                 // Async functions prior to ES2017 require the __awaiter helper
61741                 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
61742                     checkExternalEmitHelpers(node, 64 /* Awaiter */);
61743                 }
61744                 // Generator functions, Async functions, and Async Generator functions prior to
61745                 // ES2015 require the __generator helper
61746                 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
61747                     checkExternalEmitHelpers(node, 128 /* Generator */);
61748                 }
61749             }
61750             checkTypeParameters(node.typeParameters);
61751             ts.forEach(node.parameters, checkParameter);
61752             // TODO(rbuckton): Should we start checking JSDoc types?
61753             if (node.type) {
61754                 checkSourceElement(node.type);
61755             }
61756             if (produceDiagnostics) {
61757                 checkCollisionWithArgumentsInGeneratedCode(node);
61758                 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
61759                 if (noImplicitAny && !returnTypeNode) {
61760                     switch (node.kind) {
61761                         case 166 /* ConstructSignature */:
61762                             error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61763                             break;
61764                         case 165 /* CallSignature */:
61765                             error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61766                             break;
61767                     }
61768                 }
61769                 if (returnTypeNode) {
61770                     var functionFlags_1 = ts.getFunctionFlags(node);
61771                     if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
61772                         var returnType = getTypeFromTypeNode(returnTypeNode);
61773                         if (returnType === voidType) {
61774                             error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
61775                         }
61776                         else {
61777                             // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
61778                             // However, that would not catch the error in the following case.
61779                             //
61780                             //    interface BadGenerator extends Iterable<number>, Iterator<string> { }
61781                             //    function* g(): BadGenerator { } // Iterable and Iterator have different types!
61782                             //
61783                             var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
61784                             var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
61785                             var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
61786                             var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
61787                             checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
61788                         }
61789                     }
61790                     else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
61791                         checkAsyncFunctionReturnType(node, returnTypeNode);
61792                     }
61793                 }
61794                 if (node.kind !== 167 /* IndexSignature */ && node.kind !== 300 /* JSDocFunctionType */) {
61795                     registerForUnusedIdentifiersCheck(node);
61796                 }
61797             }
61798         }
61799         function checkClassForDuplicateDeclarations(node) {
61800             var instanceNames = ts.createUnderscoreEscapedMap();
61801             var staticNames = ts.createUnderscoreEscapedMap();
61802             // instance and static private identifiers share the same scope
61803             var privateIdentifiers = ts.createUnderscoreEscapedMap();
61804             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61805                 var member = _a[_i];
61806                 if (member.kind === 162 /* Constructor */) {
61807                     for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
61808                         var param = _c[_b];
61809                         if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
61810                             addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
61811                         }
61812                     }
61813                 }
61814                 else {
61815                     var isStatic = ts.hasModifier(member, 32 /* Static */);
61816                     var name = member.name;
61817                     if (!name) {
61818                         return;
61819                     }
61820                     var names = ts.isPrivateIdentifier(name) ? privateIdentifiers :
61821                         isStatic ? staticNames :
61822                             instanceNames;
61823                     var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
61824                     if (memberName) {
61825                         switch (member.kind) {
61826                             case 163 /* GetAccessor */:
61827                                 addName(names, name, memberName, 1 /* GetAccessor */);
61828                                 break;
61829                             case 164 /* SetAccessor */:
61830                                 addName(names, name, memberName, 2 /* SetAccessor */);
61831                                 break;
61832                             case 159 /* PropertyDeclaration */:
61833                                 addName(names, name, memberName, 3 /* GetOrSetAccessor */);
61834                                 break;
61835                             case 161 /* MethodDeclaration */:
61836                                 addName(names, name, memberName, 8 /* Method */);
61837                                 break;
61838                         }
61839                     }
61840                 }
61841             }
61842             function addName(names, location, name, meaning) {
61843                 var prev = names.get(name);
61844                 if (prev) {
61845                     if (prev & 8 /* Method */) {
61846                         if (meaning !== 8 /* Method */) {
61847                             error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
61848                         }
61849                     }
61850                     else if (prev & meaning) {
61851                         error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
61852                     }
61853                     else {
61854                         names.set(name, prev | meaning);
61855                     }
61856                 }
61857                 else {
61858                     names.set(name, meaning);
61859                 }
61860             }
61861         }
61862         /**
61863          * Static members being set on a constructor function may conflict with built-in properties
61864          * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
61865          * built-in properties. This check issues a transpile error when a class has a static
61866          * member with the same name as a non-writable built-in property.
61867          *
61868          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
61869          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
61870          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
61871          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
61872          */
61873         function checkClassForStaticPropertyNameConflicts(node) {
61874             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61875                 var member = _a[_i];
61876                 var memberNameNode = member.name;
61877                 var isStatic = ts.hasModifier(member, 32 /* Static */);
61878                 if (isStatic && memberNameNode) {
61879                     var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
61880                     switch (memberName) {
61881                         case "name":
61882                         case "length":
61883                         case "caller":
61884                         case "arguments":
61885                         case "prototype":
61886                             var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
61887                             var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
61888                             error(memberNameNode, message, memberName, className);
61889                             break;
61890                     }
61891                 }
61892             }
61893         }
61894         function checkObjectTypeForDuplicateDeclarations(node) {
61895             var names = ts.createMap();
61896             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61897                 var member = _a[_i];
61898                 if (member.kind === 158 /* PropertySignature */) {
61899                     var memberName = void 0;
61900                     var name = member.name;
61901                     switch (name.kind) {
61902                         case 10 /* StringLiteral */:
61903                         case 8 /* NumericLiteral */:
61904                             memberName = name.text;
61905                             break;
61906                         case 75 /* Identifier */:
61907                             memberName = ts.idText(name);
61908                             break;
61909                         default:
61910                             continue;
61911                     }
61912                     if (names.get(memberName)) {
61913                         error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
61914                         error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
61915                     }
61916                     else {
61917                         names.set(memberName, true);
61918                     }
61919                 }
61920             }
61921         }
61922         function checkTypeForDuplicateIndexSignatures(node) {
61923             if (node.kind === 246 /* InterfaceDeclaration */) {
61924                 var nodeSymbol = getSymbolOfNode(node);
61925                 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
61926                 // to prevent this run check only for the first declaration of a given kind
61927                 if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
61928                     return;
61929                 }
61930             }
61931             // TypeScript 1.0 spec (April 2014)
61932             // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
61933             // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
61934             var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
61935             if (indexSymbol) {
61936                 var seenNumericIndexer = false;
61937                 var seenStringIndexer = false;
61938                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
61939                     var decl = _a[_i];
61940                     var declaration = decl;
61941                     if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
61942                         switch (declaration.parameters[0].type.kind) {
61943                             case 143 /* StringKeyword */:
61944                                 if (!seenStringIndexer) {
61945                                     seenStringIndexer = true;
61946                                 }
61947                                 else {
61948                                     error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
61949                                 }
61950                                 break;
61951                             case 140 /* NumberKeyword */:
61952                                 if (!seenNumericIndexer) {
61953                                     seenNumericIndexer = true;
61954                                 }
61955                                 else {
61956                                     error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
61957                                 }
61958                                 break;
61959                         }
61960                     }
61961                 }
61962             }
61963         }
61964         function checkPropertyDeclaration(node) {
61965             // Grammar checking
61966             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
61967                 checkGrammarComputedPropertyName(node.name);
61968             checkVariableLikeDeclaration(node);
61969             // Private class fields transformation relies on WeakMaps.
61970             if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
61971                 for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
61972                     getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
61973                 }
61974             }
61975         }
61976         function checkPropertySignature(node) {
61977             if (ts.isPrivateIdentifier(node.name)) {
61978                 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
61979             }
61980             return checkPropertyDeclaration(node);
61981         }
61982         function checkMethodDeclaration(node) {
61983             // Grammar checking
61984             if (!checkGrammarMethod(node))
61985                 checkGrammarComputedPropertyName(node.name);
61986             if (ts.isPrivateIdentifier(node.name)) {
61987                 error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier);
61988             }
61989             // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
61990             checkFunctionOrMethodDeclaration(node);
61991             // Abstract methods cannot have an implementation.
61992             // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
61993             if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 161 /* MethodDeclaration */ && node.body) {
61994                 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
61995             }
61996         }
61997         function checkConstructorDeclaration(node) {
61998             // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
61999             checkSignatureDeclaration(node);
62000             // Grammar check for checking only related to constructorDeclaration
62001             if (!checkGrammarConstructorTypeParameters(node))
62002                 checkGrammarConstructorTypeAnnotation(node);
62003             checkSourceElement(node.body);
62004             var symbol = getSymbolOfNode(node);
62005             var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
62006             // Only type check the symbol once
62007             if (node === firstDeclaration) {
62008                 checkFunctionOrConstructorSymbol(symbol);
62009             }
62010             // exit early in the case of signature - super checks are not relevant to them
62011             if (ts.nodeIsMissing(node.body)) {
62012                 return;
62013             }
62014             if (!produceDiagnostics) {
62015                 return;
62016             }
62017             function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
62018                 if (ts.isPrivateIdentifierPropertyDeclaration(n)) {
62019                     return true;
62020                 }
62021                 return n.kind === 159 /* PropertyDeclaration */ &&
62022                     !ts.hasModifier(n, 32 /* Static */) &&
62023                     !!n.initializer;
62024             }
62025             // TS 1.0 spec (April 2014): 8.3.2
62026             // Constructors of classes with no extends clause may not contain super calls, whereas
62027             // constructors of derived classes must contain at least one super call somewhere in their function body.
62028             var containingClassDecl = node.parent;
62029             if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
62030                 captureLexicalThis(node.parent, containingClassDecl);
62031                 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
62032                 var superCall = getSuperCallInConstructor(node);
62033                 if (superCall) {
62034                     if (classExtendsNull) {
62035                         error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
62036                     }
62037                     // The first statement in the body of a constructor (excluding prologue directives) must be a super call
62038                     // if both of the following are true:
62039                     // - The containing class is a derived class.
62040                     // - The constructor declares parameter properties
62041                     //   or the containing class declares instance member variables with initializers.
62042                     var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) &&
62043                         (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
62044                             ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }));
62045                     // Skip past any prologue directives to find the first statement
62046                     // to ensure that it was a super call.
62047                     if (superCallShouldBeFirst) {
62048                         var statements = node.body.statements;
62049                         var superCallStatement = void 0;
62050                         for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
62051                             var statement = statements_3[_i];
62052                             if (statement.kind === 226 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
62053                                 superCallStatement = statement;
62054                                 break;
62055                             }
62056                             if (!ts.isPrologueDirective(statement)) {
62057                                 break;
62058                             }
62059                         }
62060                         if (!superCallStatement) {
62061                             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);
62062                         }
62063                     }
62064                 }
62065                 else if (!classExtendsNull) {
62066                     error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
62067                 }
62068             }
62069         }
62070         function checkAccessorDeclaration(node) {
62071             if (produceDiagnostics) {
62072                 // Grammar checking accessors
62073                 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
62074                     checkGrammarComputedPropertyName(node.name);
62075                 checkDecorators(node);
62076                 checkSignatureDeclaration(node);
62077                 if (node.kind === 163 /* GetAccessor */) {
62078                     if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
62079                         if (!(node.flags & 512 /* HasExplicitReturn */)) {
62080                             error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
62081                         }
62082                     }
62083                 }
62084                 // Do not use hasDynamicName here, because that returns false for well known symbols.
62085                 // We want to perform checkComputedPropertyName for all computed properties, including
62086                 // well known symbols.
62087                 if (node.name.kind === 154 /* ComputedPropertyName */) {
62088                     checkComputedPropertyName(node.name);
62089                 }
62090                 if (ts.isPrivateIdentifier(node.name)) {
62091                     error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
62092                 }
62093                 if (!hasNonBindableDynamicName(node)) {
62094                     // TypeScript 1.0 spec (April 2014): 8.4.3
62095                     // Accessors for the same member name must specify the same accessibility.
62096                     var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
62097                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
62098                     if (otherAccessor) {
62099                         var nodeFlags = ts.getModifierFlags(node);
62100                         var otherFlags = ts.getModifierFlags(otherAccessor);
62101                         if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
62102                             error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
62103                         }
62104                         if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
62105                             error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
62106                         }
62107                         // TypeScript 1.0 spec (April 2014): 4.5
62108                         // If both accessors include type annotations, the specified types must be identical.
62109                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
62110                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
62111                     }
62112                 }
62113                 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
62114                 if (node.kind === 163 /* GetAccessor */) {
62115                     checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
62116                 }
62117             }
62118             checkSourceElement(node.body);
62119         }
62120         function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
62121             var firstType = getAnnotatedType(first);
62122             var secondType = getAnnotatedType(second);
62123             if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
62124                 error(first, message);
62125             }
62126         }
62127         function checkMissingDeclaration(node) {
62128             checkDecorators(node);
62129         }
62130         function getEffectiveTypeArguments(node, typeParameters) {
62131             return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
62132         }
62133         function checkTypeArgumentConstraints(node, typeParameters) {
62134             var typeArguments;
62135             var mapper;
62136             var result = true;
62137             for (var i = 0; i < typeParameters.length; i++) {
62138                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
62139                 if (constraint) {
62140                     if (!typeArguments) {
62141                         typeArguments = getEffectiveTypeArguments(node, typeParameters);
62142                         mapper = createTypeMapper(typeParameters, typeArguments);
62143                     }
62144                     result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
62145                 }
62146             }
62147             return result;
62148         }
62149         function getTypeParametersForTypeReference(node) {
62150             var type = getTypeFromTypeReference(node);
62151             if (type !== errorType) {
62152                 var symbol = getNodeLinks(node).resolvedSymbol;
62153                 if (symbol) {
62154                     return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
62155                         (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
62156                 }
62157             }
62158             return undefined;
62159         }
62160         function checkTypeReferenceNode(node) {
62161             checkGrammarTypeArguments(node, node.typeArguments);
62162             if (node.kind === 169 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
62163                 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
62164             }
62165             ts.forEach(node.typeArguments, checkSourceElement);
62166             var type = getTypeFromTypeReference(node);
62167             if (type !== errorType) {
62168                 if (node.typeArguments && produceDiagnostics) {
62169                     var typeParameters = getTypeParametersForTypeReference(node);
62170                     if (typeParameters) {
62171                         checkTypeArgumentConstraints(node, typeParameters);
62172                     }
62173                 }
62174                 if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) {
62175                     error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
62176                 }
62177             }
62178         }
62179         function getTypeArgumentConstraint(node) {
62180             var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
62181             if (!typeReferenceNode)
62182                 return undefined;
62183             var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
62184             var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
62185             return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
62186         }
62187         function checkTypeQuery(node) {
62188             getTypeFromTypeQueryNode(node);
62189         }
62190         function checkTypeLiteral(node) {
62191             ts.forEach(node.members, checkSourceElement);
62192             if (produceDiagnostics) {
62193                 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
62194                 checkIndexConstraints(type);
62195                 checkTypeForDuplicateIndexSignatures(node);
62196                 checkObjectTypeForDuplicateDeclarations(node);
62197             }
62198         }
62199         function checkArrayType(node) {
62200             checkSourceElement(node.elementType);
62201         }
62202         function checkTupleType(node) {
62203             var elementTypes = node.elementTypes;
62204             var seenOptionalElement = false;
62205             for (var i = 0; i < elementTypes.length; i++) {
62206                 var e = elementTypes[i];
62207                 if (e.kind === 177 /* RestType */) {
62208                     if (i !== elementTypes.length - 1) {
62209                         grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
62210                         break;
62211                     }
62212                     if (!isArrayType(getTypeFromTypeNode(e.type))) {
62213                         error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
62214                     }
62215                 }
62216                 else if (e.kind === 176 /* OptionalType */) {
62217                     seenOptionalElement = true;
62218                 }
62219                 else if (seenOptionalElement) {
62220                     grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
62221                     break;
62222                 }
62223             }
62224             ts.forEach(node.elementTypes, checkSourceElement);
62225         }
62226         function checkUnionOrIntersectionType(node) {
62227             ts.forEach(node.types, checkSourceElement);
62228         }
62229         function checkIndexedAccessIndexType(type, accessNode) {
62230             if (!(type.flags & 8388608 /* IndexedAccess */)) {
62231                 return type;
62232             }
62233             // Check if the index type is assignable to 'keyof T' for the object type.
62234             var objectType = type.objectType;
62235             var indexType = type.indexType;
62236             if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
62237                 if (accessNode.kind === 195 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
62238                     ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
62239                     error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
62240                 }
62241                 return type;
62242             }
62243             // Check if we're indexing with a numeric type and if either object or index types
62244             // is a generic type with a constraint that has a numeric index signature.
62245             var apparentObjectType = getApparentType(objectType);
62246             if (getIndexInfoOfType(apparentObjectType, 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
62247                 return type;
62248             }
62249             if (isGenericObjectType(objectType)) {
62250                 var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
62251                 if (propertyName_1) {
62252                     var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
62253                     if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
62254                         error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
62255                         return errorType;
62256                     }
62257                 }
62258             }
62259             error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
62260             return errorType;
62261         }
62262         function checkIndexedAccessType(node) {
62263             checkSourceElement(node.objectType);
62264             checkSourceElement(node.indexType);
62265             checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
62266         }
62267         function checkMappedType(node) {
62268             checkSourceElement(node.typeParameter);
62269             checkSourceElement(node.type);
62270             if (!node.type) {
62271                 reportImplicitAny(node, anyType);
62272             }
62273             var type = getTypeFromMappedTypeNode(node);
62274             var constraintType = getConstraintTypeFromMappedType(type);
62275             checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
62276         }
62277         function checkThisType(node) {
62278             getTypeFromThisTypeNode(node);
62279         }
62280         function checkTypeOperator(node) {
62281             checkGrammarTypeOperatorNode(node);
62282             checkSourceElement(node.type);
62283         }
62284         function checkConditionalType(node) {
62285             ts.forEachChild(node, checkSourceElement);
62286         }
62287         function checkInferType(node) {
62288             if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 180 /* ConditionalType */ && n.parent.extendsType === n; })) {
62289                 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
62290             }
62291             checkSourceElement(node.typeParameter);
62292             registerForUnusedIdentifiersCheck(node);
62293         }
62294         function checkImportType(node) {
62295             checkSourceElement(node.argument);
62296             getTypeFromTypeNode(node);
62297         }
62298         function isPrivateWithinAmbient(node) {
62299             return (ts.hasModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
62300         }
62301         function getEffectiveDeclarationFlags(n, flagsToCheck) {
62302             var flags = ts.getCombinedModifierFlags(n);
62303             // children of classes (even ambient classes) should not be marked as ambient or export
62304             // because those flags have no useful semantics there.
62305             if (n.parent.kind !== 246 /* InterfaceDeclaration */ &&
62306                 n.parent.kind !== 245 /* ClassDeclaration */ &&
62307                 n.parent.kind !== 214 /* ClassExpression */ &&
62308                 n.flags & 8388608 /* Ambient */) {
62309                 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
62310                     // It is nested in an ambient context, which means it is automatically exported
62311                     flags |= 1 /* Export */;
62312                 }
62313                 flags |= 2 /* Ambient */;
62314             }
62315             return flags & flagsToCheck;
62316         }
62317         function checkFunctionOrConstructorSymbol(symbol) {
62318             if (!produceDiagnostics) {
62319                 return;
62320             }
62321             function getCanonicalOverload(overloads, implementation) {
62322                 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
62323                 // Error on all deviations from this canonical set of flags
62324                 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
62325                 // report the errors on those. To achieve this, we will say that the implementation is
62326                 // the canonical signature only if it is in the same container as the first overload
62327                 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
62328                 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
62329             }
62330             function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
62331                 // Error if some overloads have a flag that is not shared by all overloads. To find the
62332                 // deviations, we XOR someOverloadFlags with allOverloadFlags
62333                 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
62334                 if (someButNotAllOverloadFlags !== 0) {
62335                     var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
62336                     ts.forEach(overloads, function (o) {
62337                         var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
62338                         if (deviation & 1 /* Export */) {
62339                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
62340                         }
62341                         else if (deviation & 2 /* Ambient */) {
62342                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
62343                         }
62344                         else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
62345                             error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
62346                         }
62347                         else if (deviation & 128 /* Abstract */) {
62348                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
62349                         }
62350                     });
62351                 }
62352             }
62353             function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
62354                 if (someHaveQuestionToken !== allHaveQuestionToken) {
62355                     var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
62356                     ts.forEach(overloads, function (o) {
62357                         var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
62358                         if (deviation) {
62359                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
62360                         }
62361                     });
62362                 }
62363             }
62364             var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
62365             var someNodeFlags = 0 /* None */;
62366             var allNodeFlags = flagsToCheck;
62367             var someHaveQuestionToken = false;
62368             var allHaveQuestionToken = true;
62369             var hasOverloads = false;
62370             var bodyDeclaration;
62371             var lastSeenNonAmbientDeclaration;
62372             var previousDeclaration;
62373             var declarations = symbol.declarations;
62374             var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
62375             function reportImplementationExpectedError(node) {
62376                 if (node.name && ts.nodeIsMissing(node.name)) {
62377                     return;
62378                 }
62379                 var seen = false;
62380                 var subsequentNode = ts.forEachChild(node.parent, function (c) {
62381                     if (seen) {
62382                         return c;
62383                     }
62384                     else {
62385                         seen = c === node;
62386                     }
62387                 });
62388                 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
62389                 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
62390                 if (subsequentNode && subsequentNode.pos === node.end) {
62391                     if (subsequentNode.kind === node.kind) {
62392                         var errorNode_1 = subsequentNode.name || subsequentNode;
62393                         var subsequentName = subsequentNode.name;
62394                         if (node.name && subsequentName && (
62395                         // both are private identifiers
62396                         ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
62397                             // Both are computed property names
62398                             // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
62399                             ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
62400                             // Both are literal property names that are the same.
62401                             ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
62402                                 ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
62403                             var reportError = (node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */) &&
62404                                 ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */);
62405                             // we can get here in two cases
62406                             // 1. mixed static and instance class members
62407                             // 2. something with the same name was defined before the set of overloads that prevents them from merging
62408                             // here we'll report error only for the first case since for second we should already report error in binder
62409                             if (reportError) {
62410                                 var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
62411                                 error(errorNode_1, diagnostic);
62412                             }
62413                             return;
62414                         }
62415                         if (ts.nodeIsPresent(subsequentNode.body)) {
62416                             error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
62417                             return;
62418                         }
62419                     }
62420                 }
62421                 var errorNode = node.name || node;
62422                 if (isConstructor) {
62423                     error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
62424                 }
62425                 else {
62426                     // Report different errors regarding non-consecutive blocks of declarations depending on whether
62427                     // the node in question is abstract.
62428                     if (ts.hasModifier(node, 128 /* Abstract */)) {
62429                         error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
62430                     }
62431                     else {
62432                         error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
62433                     }
62434                 }
62435             }
62436             var duplicateFunctionDeclaration = false;
62437             var multipleConstructorImplementation = false;
62438             var hasNonAmbientClass = false;
62439             for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
62440                 var current = declarations_4[_i];
62441                 var node = current;
62442                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
62443                 var inAmbientContextOrInterface = node.parent.kind === 246 /* InterfaceDeclaration */ || node.parent.kind === 173 /* TypeLiteral */ || inAmbientContext;
62444                 if (inAmbientContextOrInterface) {
62445                     // check if declarations are consecutive only if they are non-ambient
62446                     // 1. ambient declarations can be interleaved
62447                     // i.e. this is legal
62448                     //     declare function foo();
62449                     //     declare function bar();
62450                     //     declare function foo();
62451                     // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
62452                     previousDeclaration = undefined;
62453                 }
62454                 if ((node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */) && !inAmbientContext) {
62455                     hasNonAmbientClass = true;
62456                 }
62457                 if (node.kind === 244 /* FunctionDeclaration */ || node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */ || node.kind === 162 /* Constructor */) {
62458                     var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
62459                     someNodeFlags |= currentNodeFlags;
62460                     allNodeFlags &= currentNodeFlags;
62461                     someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
62462                     allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
62463                     if (ts.nodeIsPresent(node.body) && bodyDeclaration) {
62464                         if (isConstructor) {
62465                             multipleConstructorImplementation = true;
62466                         }
62467                         else {
62468                             duplicateFunctionDeclaration = true;
62469                         }
62470                     }
62471                     else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) {
62472                         reportImplementationExpectedError(previousDeclaration);
62473                     }
62474                     if (ts.nodeIsPresent(node.body)) {
62475                         if (!bodyDeclaration) {
62476                             bodyDeclaration = node;
62477                         }
62478                     }
62479                     else {
62480                         hasOverloads = true;
62481                     }
62482                     previousDeclaration = node;
62483                     if (!inAmbientContextOrInterface) {
62484                         lastSeenNonAmbientDeclaration = node;
62485                     }
62486                 }
62487             }
62488             if (multipleConstructorImplementation) {
62489                 ts.forEach(declarations, function (declaration) {
62490                     error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
62491                 });
62492             }
62493             if (duplicateFunctionDeclaration) {
62494                 ts.forEach(declarations, function (declaration) {
62495                     error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation);
62496                 });
62497             }
62498             if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */) {
62499                 // A non-ambient class cannot be an implementation for a non-constructor function/class merge
62500                 // TODO: The below just replicates our older error from when classes and functions were
62501                 // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list"
62502                 // might be warranted. :shrug:
62503                 ts.forEach(declarations, function (declaration) {
62504                     addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations);
62505                 });
62506             }
62507             // Abstract methods can't have an implementation -- in particular, they don't need one.
62508             if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
62509                 !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
62510                 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
62511             }
62512             if (hasOverloads) {
62513                 checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
62514                 checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
62515                 if (bodyDeclaration) {
62516                     var signatures = getSignaturesOfSymbol(symbol);
62517                     var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
62518                     for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
62519                         var signature = signatures_10[_a];
62520                         if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
62521                             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));
62522                             break;
62523                         }
62524                     }
62525                 }
62526             }
62527         }
62528         function checkExportsOnMergedDeclarations(node) {
62529             if (!produceDiagnostics) {
62530                 return;
62531             }
62532             // if localSymbol is defined on node then node itself is exported - check is required
62533             var symbol = node.localSymbol;
62534             if (!symbol) {
62535                 // local symbol is undefined => this declaration is non-exported.
62536                 // however symbol might contain other declarations that are exported
62537                 symbol = getSymbolOfNode(node);
62538                 if (!symbol.exportSymbol) {
62539                     // this is a pure local symbol (all declarations are non-exported) - no need to check anything
62540                     return;
62541                 }
62542             }
62543             // run the check only for the first declaration in the list
62544             if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
62545                 return;
62546             }
62547             var exportedDeclarationSpaces = 0 /* None */;
62548             var nonExportedDeclarationSpaces = 0 /* None */;
62549             var defaultExportedDeclarationSpaces = 0 /* None */;
62550             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
62551                 var d = _a[_i];
62552                 var declarationSpaces = getDeclarationSpaces(d);
62553                 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
62554                 if (effectiveDeclarationFlags & 1 /* Export */) {
62555                     if (effectiveDeclarationFlags & 512 /* Default */) {
62556                         defaultExportedDeclarationSpaces |= declarationSpaces;
62557                     }
62558                     else {
62559                         exportedDeclarationSpaces |= declarationSpaces;
62560                     }
62561                 }
62562                 else {
62563                     nonExportedDeclarationSpaces |= declarationSpaces;
62564                 }
62565             }
62566             // Spaces for anything not declared a 'default export'.
62567             var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
62568             var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
62569             var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
62570             if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
62571                 // declaration spaces for exported and non-exported declarations intersect
62572                 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
62573                     var d = _c[_b];
62574                     var declarationSpaces = getDeclarationSpaces(d);
62575                     var name = ts.getNameOfDeclaration(d);
62576                     // Only error on the declarations that contributed to the intersecting spaces.
62577                     if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
62578                         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));
62579                     }
62580                     else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
62581                         error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
62582                     }
62583                 }
62584             }
62585             function getDeclarationSpaces(decl) {
62586                 var d = decl;
62587                 switch (d.kind) {
62588                     case 246 /* InterfaceDeclaration */:
62589                     case 247 /* TypeAliasDeclaration */:
62590                     // A jsdoc typedef and callback are, by definition, type aliases.
62591                     // falls through
62592                     case 322 /* JSDocTypedefTag */:
62593                     case 315 /* JSDocCallbackTag */:
62594                     case 316 /* JSDocEnumTag */:
62595                         return 2 /* ExportType */;
62596                     case 249 /* ModuleDeclaration */:
62597                         return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
62598                             ? 4 /* ExportNamespace */ | 1 /* ExportValue */
62599                             : 4 /* ExportNamespace */;
62600                     case 245 /* ClassDeclaration */:
62601                     case 248 /* EnumDeclaration */:
62602                     case 284 /* EnumMember */:
62603                         return 2 /* ExportType */ | 1 /* ExportValue */;
62604                     case 290 /* SourceFile */:
62605                         return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
62606                     case 259 /* ExportAssignment */:
62607                         // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
62608                         if (!ts.isEntityNameExpression(d.expression)) {
62609                             return 1 /* ExportValue */;
62610                         }
62611                         d = d.expression;
62612                     // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
62613                     // falls through
62614                     case 253 /* ImportEqualsDeclaration */:
62615                     case 256 /* NamespaceImport */:
62616                     case 255 /* ImportClause */:
62617                         var result_10 = 0 /* None */;
62618                         var target = resolveAlias(getSymbolOfNode(d));
62619                         ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); });
62620                         return result_10;
62621                     case 242 /* VariableDeclaration */:
62622                     case 191 /* BindingElement */:
62623                     case 244 /* FunctionDeclaration */:
62624                     case 258 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
62625                     case 75 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
62626                         // Identifiers are used as declarations of assignment declarations whose parents may be
62627                         // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
62628                         // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
62629                         // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
62630                         // all of which are pretty much always values, or at least imply a value meaning.
62631                         // It may be apprpriate to treat these as aliases in the future.
62632                         return 1 /* ExportValue */;
62633                     default:
62634                         return ts.Debug.failBadSyntaxKind(d);
62635                 }
62636             }
62637         }
62638         function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
62639             var promisedType = getPromisedTypeOfPromise(type, errorNode);
62640             return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62641         }
62642         /**
62643          * Gets the "promised type" of a promise.
62644          * @param type The type of the promise.
62645          * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
62646          */
62647         function getPromisedTypeOfPromise(type, errorNode) {
62648             //
62649             //  { // type
62650             //      then( // thenFunction
62651             //          onfulfilled: ( // onfulfilledParameterType
62652             //              value: T // valueParameterType
62653             //          ) => any
62654             //      ): any;
62655             //  }
62656             //
62657             if (isTypeAny(type)) {
62658                 return undefined;
62659             }
62660             var typeAsPromise = type;
62661             if (typeAsPromise.promisedTypeOfPromise) {
62662                 return typeAsPromise.promisedTypeOfPromise;
62663             }
62664             if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) {
62665                 return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
62666             }
62667             var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217
62668             if (isTypeAny(thenFunction)) {
62669                 return undefined;
62670             }
62671             var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
62672             if (thenSignatures.length === 0) {
62673                 if (errorNode) {
62674                     error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
62675                 }
62676                 return undefined;
62677             }
62678             var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
62679             if (isTypeAny(onfulfilledParameterType)) {
62680                 return undefined;
62681             }
62682             var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
62683             if (onfulfilledParameterSignatures.length === 0) {
62684                 if (errorNode) {
62685                     error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
62686                 }
62687                 return undefined;
62688             }
62689             return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
62690         }
62691         /**
62692          * Gets the "awaited type" of a type.
62693          * @param type The type to await.
62694          * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
62695          * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
62696          * The runtime behavior of the `await` keyword.
62697          */
62698         function checkAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62699             var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
62700             return awaitedType || errorType;
62701         }
62702         /**
62703          * Determines whether a type has a callable `then` member.
62704          */
62705         function isThenableType(type) {
62706             var thenFunction = getTypeOfPropertyOfType(type, "then");
62707             return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
62708         }
62709         /**
62710          * Gets the "awaited type" of a type.
62711          *
62712          * The "awaited type" of an expression is its "promised type" if the expression is a
62713          * Promise-like type; otherwise, it is the type of the expression. If the "promised
62714          * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a
62715          * non-promise type is found.
62716          *
62717          * This is used to reflect the runtime behavior of the `await` keyword.
62718          */
62719         function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62720             if (isTypeAny(type)) {
62721                 return type;
62722             }
62723             var typeAsAwaitable = type;
62724             if (typeAsAwaitable.awaitedTypeOfType) {
62725                 return typeAsAwaitable.awaitedTypeOfType;
62726             }
62727             // For a union, get a union of the awaited types of each constituent.
62728             //
62729             return typeAsAwaitable.awaitedTypeOfType =
62730                 mapType(type, errorNode ? function (constituentType) { return getAwaitedTypeWorker(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeWorker);
62731         }
62732         function getAwaitedTypeWorker(type, errorNode, diagnosticMessage, arg0) {
62733             var typeAsAwaitable = type;
62734             if (typeAsAwaitable.awaitedTypeOfType) {
62735                 return typeAsAwaitable.awaitedTypeOfType;
62736             }
62737             var promisedType = getPromisedTypeOfPromise(type);
62738             if (promisedType) {
62739                 if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
62740                     // Verify that we don't have a bad actor in the form of a promise whose
62741                     // promised type is the same as the promise type, or a mutually recursive
62742                     // promise. If so, we return undefined as we cannot guess the shape. If this
62743                     // were the actual case in the JavaScript, this Promise would never resolve.
62744                     //
62745                     // An example of a bad actor with a singly-recursive promise type might
62746                     // be:
62747                     //
62748                     //  interface BadPromise {
62749                     //      then(
62750                     //          onfulfilled: (value: BadPromise) => any,
62751                     //          onrejected: (error: any) => any): BadPromise;
62752                     //  }
62753                     //
62754                     // The above interface will pass the PromiseLike check, and return a
62755                     // promised type of `BadPromise`. Since this is a self reference, we
62756                     // don't want to keep recursing ad infinitum.
62757                     //
62758                     // An example of a bad actor in the form of a mutually-recursive
62759                     // promise type might be:
62760                     //
62761                     //  interface BadPromiseA {
62762                     //      then(
62763                     //          onfulfilled: (value: BadPromiseB) => any,
62764                     //          onrejected: (error: any) => any): BadPromiseB;
62765                     //  }
62766                     //
62767                     //  interface BadPromiseB {
62768                     //      then(
62769                     //          onfulfilled: (value: BadPromiseA) => any,
62770                     //          onrejected: (error: any) => any): BadPromiseA;
62771                     //  }
62772                     //
62773                     if (errorNode) {
62774                         error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
62775                     }
62776                     return undefined;
62777                 }
62778                 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
62779                 // See the comments above for more information.
62780                 awaitedTypeStack.push(type.id);
62781                 var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62782                 awaitedTypeStack.pop();
62783                 if (!awaitedType) {
62784                     return undefined;
62785                 }
62786                 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
62787             }
62788             // The type was not a promise, so it could not be unwrapped any further.
62789             // As long as the type does not have a callable "then" property, it is
62790             // safe to return the type; otherwise, an error is reported and we return
62791             // undefined.
62792             //
62793             // An example of a non-promise "thenable" might be:
62794             //
62795             //  await { then(): void {} }
62796             //
62797             // The "thenable" does not match the minimal definition for a promise. When
62798             // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
62799             // will never settle. We treat this as an error to help flag an early indicator
62800             // of a runtime problem. If the user wants to return this value from an async
62801             // function, they would need to wrap it in some other value. If they want it to
62802             // be treated as a promise, they can cast to <any>.
62803             if (isThenableType(type)) {
62804                 if (errorNode) {
62805                     if (!diagnosticMessage)
62806                         return ts.Debug.fail();
62807                     error(errorNode, diagnosticMessage, arg0);
62808                 }
62809                 return undefined;
62810             }
62811             return typeAsAwaitable.awaitedTypeOfType = type;
62812         }
62813         /**
62814          * Checks the return type of an async function to ensure it is a compatible
62815          * Promise implementation.
62816          *
62817          * This checks that an async function has a valid Promise-compatible return type.
62818          * An async function has a valid Promise-compatible return type if the resolved value
62819          * of the return type has a construct signature that takes in an `initializer` function
62820          * that in turn supplies a `resolve` function as one of its arguments and results in an
62821          * object with a callable `then` signature.
62822          *
62823          * @param node The signature to check
62824          */
62825         function checkAsyncFunctionReturnType(node, returnTypeNode) {
62826             // As part of our emit for an async function, we will need to emit the entity name of
62827             // the return type annotation as an expression. To meet the necessary runtime semantics
62828             // for __awaiter, we must also check that the type of the declaration (e.g. the static
62829             // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
62830             //
62831             // An example might be (from lib.es6.d.ts):
62832             //
62833             //  interface Promise<T> { ... }
62834             //  interface PromiseConstructor {
62835             //      new <T>(...): Promise<T>;
62836             //  }
62837             //  declare var Promise: PromiseConstructor;
62838             //
62839             // When an async function declares a return type annotation of `Promise<T>`, we
62840             // need to get the type of the `Promise` variable declaration above, which would
62841             // be `PromiseConstructor`.
62842             //
62843             // The same case applies to a class:
62844             //
62845             //  declare class Promise<T> {
62846             //      constructor(...);
62847             //      then<U>(...): Promise<U>;
62848             //  }
62849             //
62850             var returnType = getTypeFromTypeNode(returnTypeNode);
62851             if (languageVersion >= 2 /* ES2015 */) {
62852                 if (returnType === errorType) {
62853                     return;
62854                 }
62855                 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
62856                 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
62857                     // The promise type was not a valid type reference to the global promise type, so we
62858                     // report an error and return the unknown type.
62859                     error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
62860                     return;
62861                 }
62862             }
62863             else {
62864                 // Always mark the type node as referenced if it points to a value
62865                 markTypeNodeAsReferenced(returnTypeNode);
62866                 if (returnType === errorType) {
62867                     return;
62868                 }
62869                 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
62870                 if (promiseConstructorName === undefined) {
62871                     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));
62872                     return;
62873                 }
62874                 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
62875                 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
62876                 if (promiseConstructorType === errorType) {
62877                     if (promiseConstructorName.kind === 75 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
62878                         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);
62879                     }
62880                     else {
62881                         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));
62882                     }
62883                     return;
62884                 }
62885                 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
62886                 if (globalPromiseConstructorLikeType === emptyObjectType) {
62887                     // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
62888                     // compatibility with __awaiter.
62889                     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));
62890                     return;
62891                 }
62892                 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)) {
62893                     return;
62894                 }
62895                 // Verify there is no local declaration that could collide with the promise constructor.
62896                 var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
62897                 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
62898                 if (collidingSymbol) {
62899                     error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
62900                     return;
62901                 }
62902             }
62903             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);
62904         }
62905         /** Check a decorator */
62906         function checkDecorator(node) {
62907             var signature = getResolvedSignature(node);
62908             var returnType = getReturnTypeOfSignature(signature);
62909             if (returnType.flags & 1 /* Any */) {
62910                 return;
62911             }
62912             var expectedReturnType;
62913             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
62914             var errorInfo;
62915             switch (node.parent.kind) {
62916                 case 245 /* ClassDeclaration */:
62917                     var classSymbol = getSymbolOfNode(node.parent);
62918                     var classConstructorType = getTypeOfSymbol(classSymbol);
62919                     expectedReturnType = getUnionType([classConstructorType, voidType]);
62920                     break;
62921                 case 156 /* Parameter */:
62922                     expectedReturnType = voidType;
62923                     errorInfo = ts.chainDiagnosticMessages(
62924                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
62925                     break;
62926                 case 159 /* PropertyDeclaration */:
62927                     expectedReturnType = voidType;
62928                     errorInfo = ts.chainDiagnosticMessages(
62929                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
62930                     break;
62931                 case 161 /* MethodDeclaration */:
62932                 case 163 /* GetAccessor */:
62933                 case 164 /* SetAccessor */:
62934                     var methodType = getTypeOfNode(node.parent);
62935                     var descriptorType = createTypedPropertyDescriptorType(methodType);
62936                     expectedReturnType = getUnionType([descriptorType, voidType]);
62937                     break;
62938                 default:
62939                     return ts.Debug.fail();
62940             }
62941             checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
62942         }
62943         /**
62944          * If a TypeNode can be resolved to a value symbol imported from an external module, it is
62945          * marked as referenced to prevent import elision.
62946          */
62947         function markTypeNodeAsReferenced(node) {
62948             markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
62949         }
62950         function markEntityNameOrEntityExpressionAsReference(typeName) {
62951             if (!typeName)
62952                 return;
62953             var rootName = ts.getFirstIdentifier(typeName);
62954             var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
62955             var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
62956             if (rootSymbol
62957                 && rootSymbol.flags & 2097152 /* Alias */
62958                 && symbolIsValue(rootSymbol)
62959                 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
62960                 && !getTypeOnlyAliasDeclaration(rootSymbol)) {
62961                 markAliasSymbolAsReferenced(rootSymbol);
62962             }
62963         }
62964         /**
62965          * This function marks the type used for metadata decorator as referenced if it is import
62966          * from external module.
62967          * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
62968          * union and intersection type
62969          * @param node
62970          */
62971         function markDecoratorMedataDataTypeNodeAsReferenced(node) {
62972             var entityName = getEntityNameForDecoratorMetadata(node);
62973             if (entityName && ts.isEntityName(entityName)) {
62974                 markEntityNameOrEntityExpressionAsReference(entityName);
62975             }
62976         }
62977         function getEntityNameForDecoratorMetadata(node) {
62978             if (node) {
62979                 switch (node.kind) {
62980                     case 179 /* IntersectionType */:
62981                     case 178 /* UnionType */:
62982                         return getEntityNameForDecoratorMetadataFromTypeList(node.types);
62983                     case 180 /* ConditionalType */:
62984                         return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
62985                     case 182 /* ParenthesizedType */:
62986                         return getEntityNameForDecoratorMetadata(node.type);
62987                     case 169 /* TypeReference */:
62988                         return node.typeName;
62989                 }
62990             }
62991         }
62992         function getEntityNameForDecoratorMetadataFromTypeList(types) {
62993             var commonEntityName;
62994             for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
62995                 var typeNode = types_20[_i];
62996                 while (typeNode.kind === 182 /* ParenthesizedType */) {
62997                     typeNode = typeNode.type; // Skip parens if need be
62998                 }
62999                 if (typeNode.kind === 137 /* NeverKeyword */) {
63000                     continue; // Always elide `never` from the union/intersection if possible
63001                 }
63002                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
63003                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
63004                 }
63005                 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
63006                 if (!individualEntityName) {
63007                     // Individual is something like string number
63008                     // So it would be serialized to either that type or object
63009                     // Safe to return here
63010                     return undefined;
63011                 }
63012                 if (commonEntityName) {
63013                     // Note this is in sync with the transformation that happens for type node.
63014                     // Keep this in sync with serializeUnionOrIntersectionType
63015                     // Verify if they refer to same entity and is identifier
63016                     // return undefined if they dont match because we would emit object
63017                     if (!ts.isIdentifier(commonEntityName) ||
63018                         !ts.isIdentifier(individualEntityName) ||
63019                         commonEntityName.escapedText !== individualEntityName.escapedText) {
63020                         return undefined;
63021                     }
63022                 }
63023                 else {
63024                     commonEntityName = individualEntityName;
63025                 }
63026             }
63027             return commonEntityName;
63028         }
63029         function getParameterTypeNodeForDecoratorCheck(node) {
63030             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
63031             return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
63032         }
63033         /** Check the decorators of a node */
63034         function checkDecorators(node) {
63035             if (!node.decorators) {
63036                 return;
63037             }
63038             // skip this check for nodes that cannot have decorators. These should have already had an error reported by
63039             // checkGrammarDecorators.
63040             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
63041                 return;
63042             }
63043             if (!compilerOptions.experimentalDecorators) {
63044                 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);
63045             }
63046             var firstDecorator = node.decorators[0];
63047             checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
63048             if (node.kind === 156 /* Parameter */) {
63049                 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
63050             }
63051             if (compilerOptions.emitDecoratorMetadata) {
63052                 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
63053                 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
63054                 switch (node.kind) {
63055                     case 245 /* ClassDeclaration */:
63056                         var constructor = ts.getFirstConstructorWithBody(node);
63057                         if (constructor) {
63058                             for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
63059                                 var parameter = _a[_i];
63060                                 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63061                             }
63062                         }
63063                         break;
63064                     case 163 /* GetAccessor */:
63065                     case 164 /* SetAccessor */:
63066                         var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
63067                         var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
63068                         markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
63069                         break;
63070                     case 161 /* MethodDeclaration */:
63071                         for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
63072                             var parameter = _c[_b];
63073                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63074                         }
63075                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
63076                         break;
63077                     case 159 /* PropertyDeclaration */:
63078                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
63079                         break;
63080                     case 156 /* Parameter */:
63081                         markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
63082                         var containingSignature = node.parent;
63083                         for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
63084                             var parameter = _e[_d];
63085                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63086                         }
63087                         break;
63088                 }
63089             }
63090             ts.forEach(node.decorators, checkDecorator);
63091         }
63092         function checkFunctionDeclaration(node) {
63093             if (produceDiagnostics) {
63094                 checkFunctionOrMethodDeclaration(node);
63095                 checkGrammarForGenerator(node);
63096                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
63097                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
63098             }
63099         }
63100         function checkJSDocTypeAliasTag(node) {
63101             if (!node.typeExpression) {
63102                 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
63103                 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
63104             }
63105             if (node.name) {
63106                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
63107             }
63108             checkSourceElement(node.typeExpression);
63109         }
63110         function checkJSDocTemplateTag(node) {
63111             checkSourceElement(node.constraint);
63112             for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
63113                 var tp = _a[_i];
63114                 checkSourceElement(tp);
63115             }
63116         }
63117         function checkJSDocTypeTag(node) {
63118             checkSourceElement(node.typeExpression);
63119         }
63120         function checkJSDocParameterTag(node) {
63121             checkSourceElement(node.typeExpression);
63122             if (!ts.getParameterSymbolFromJSDoc(node)) {
63123                 var decl = ts.getHostSignatureFromJSDoc(node);
63124                 // don't issue an error for invalid hosts -- just functions --
63125                 // and give a better error message when the host function mentions `arguments`
63126                 // but the tag doesn't have an array type
63127                 if (decl) {
63128                     var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
63129                     if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
63130                         return;
63131                     }
63132                     if (!containsArgumentsReference(decl)) {
63133                         if (ts.isQualifiedName(node.name)) {
63134                             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));
63135                         }
63136                         else {
63137                             error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
63138                         }
63139                     }
63140                     else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
63141                         node.typeExpression && node.typeExpression.type &&
63142                         !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
63143                         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));
63144                     }
63145                 }
63146             }
63147         }
63148         function checkJSDocPropertyTag(node) {
63149             checkSourceElement(node.typeExpression);
63150         }
63151         function checkJSDocFunctionType(node) {
63152             if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
63153                 reportImplicitAny(node, anyType);
63154             }
63155             checkSignatureDeclaration(node);
63156         }
63157         function checkJSDocImplementsTag(node) {
63158             var classLike = ts.getEffectiveJSDocHost(node);
63159             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63160                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63161             }
63162         }
63163         function checkJSDocAugmentsTag(node) {
63164             var classLike = ts.getEffectiveJSDocHost(node);
63165             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63166                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63167                 return;
63168             }
63169             var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
63170             ts.Debug.assert(augmentsTags.length > 0);
63171             if (augmentsTags.length > 1) {
63172                 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
63173             }
63174             var name = getIdentifierFromEntityNameExpression(node.class.expression);
63175             var extend = ts.getClassExtendsHeritageElement(classLike);
63176             if (extend) {
63177                 var className = getIdentifierFromEntityNameExpression(extend.expression);
63178                 if (className && name.escapedText !== className.escapedText) {
63179                     error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
63180                 }
63181             }
63182         }
63183         function getIdentifierFromEntityNameExpression(node) {
63184             switch (node.kind) {
63185                 case 75 /* Identifier */:
63186                     return node;
63187                 case 194 /* PropertyAccessExpression */:
63188                     return node.name;
63189                 default:
63190                     return undefined;
63191             }
63192         }
63193         function checkFunctionOrMethodDeclaration(node) {
63194             checkDecorators(node);
63195             checkSignatureDeclaration(node);
63196             var functionFlags = ts.getFunctionFlags(node);
63197             // Do not use hasDynamicName here, because that returns false for well known symbols.
63198             // We want to perform checkComputedPropertyName for all computed properties, including
63199             // well known symbols.
63200             if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
63201                 // This check will account for methods in class/interface declarations,
63202                 // as well as accessors in classes/object literals
63203                 checkComputedPropertyName(node.name);
63204             }
63205             if (!hasNonBindableDynamicName(node)) {
63206                 // first we want to check the local symbol that contain this declaration
63207                 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
63208                 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
63209                 var symbol = getSymbolOfNode(node);
63210                 var localSymbol = node.localSymbol || symbol;
63211                 // Since the javascript won't do semantic analysis like typescript,
63212                 // if the javascript file comes before the typescript file and both contain same name functions,
63213                 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
63214                 var firstDeclaration = ts.find(localSymbol.declarations, 
63215                 // Get first non javascript function declaration
63216                 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
63217                 // Only type check the symbol once
63218                 if (node === firstDeclaration) {
63219                     checkFunctionOrConstructorSymbol(localSymbol);
63220                 }
63221                 if (symbol.parent) {
63222                     // run check once for the first declaration
63223                     if (ts.getDeclarationOfKind(symbol, node.kind) === node) {
63224                         // run check on export symbol to check that modifiers agree across all exported declarations
63225                         checkFunctionOrConstructorSymbol(symbol);
63226                     }
63227                 }
63228             }
63229             var body = node.kind === 160 /* MethodSignature */ ? undefined : node.body;
63230             checkSourceElement(body);
63231             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
63232             if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
63233                 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
63234                 // in an ambient context
63235                 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
63236                     reportImplicitAny(node, anyType);
63237                 }
63238                 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
63239                     // A generator with a body and no type annotation can still cause errors. It can error if the
63240                     // yielded values have no common supertype, or it can give an implicit any error if it has no
63241                     // yielded values. The only way to trigger these errors is to try checking its return type.
63242                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
63243                 }
63244             }
63245             // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
63246             if (ts.isInJSFile(node)) {
63247                 var typeTag = ts.getJSDocTypeTag(node);
63248                 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
63249                     error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
63250                 }
63251             }
63252         }
63253         function registerForUnusedIdentifiersCheck(node) {
63254             // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
63255             if (produceDiagnostics) {
63256                 var sourceFile = ts.getSourceFileOfNode(node);
63257                 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
63258                 if (!potentiallyUnusedIdentifiers) {
63259                     potentiallyUnusedIdentifiers = [];
63260                     allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
63261                 }
63262                 // TODO: GH#22580
63263                 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
63264                 potentiallyUnusedIdentifiers.push(node);
63265             }
63266         }
63267         function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
63268             for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
63269                 var node = potentiallyUnusedIdentifiers_1[_i];
63270                 switch (node.kind) {
63271                     case 245 /* ClassDeclaration */:
63272                     case 214 /* ClassExpression */:
63273                         checkUnusedClassMembers(node, addDiagnostic);
63274                         checkUnusedTypeParameters(node, addDiagnostic);
63275                         break;
63276                     case 290 /* SourceFile */:
63277                     case 249 /* ModuleDeclaration */:
63278                     case 223 /* Block */:
63279                     case 251 /* CaseBlock */:
63280                     case 230 /* ForStatement */:
63281                     case 231 /* ForInStatement */:
63282                     case 232 /* ForOfStatement */:
63283                         checkUnusedLocalsAndParameters(node, addDiagnostic);
63284                         break;
63285                     case 162 /* Constructor */:
63286                     case 201 /* FunctionExpression */:
63287                     case 244 /* FunctionDeclaration */:
63288                     case 202 /* ArrowFunction */:
63289                     case 161 /* MethodDeclaration */:
63290                     case 163 /* GetAccessor */:
63291                     case 164 /* SetAccessor */:
63292                         if (node.body) { // Don't report unused parameters in overloads
63293                             checkUnusedLocalsAndParameters(node, addDiagnostic);
63294                         }
63295                         checkUnusedTypeParameters(node, addDiagnostic);
63296                         break;
63297                     case 160 /* MethodSignature */:
63298                     case 165 /* CallSignature */:
63299                     case 166 /* ConstructSignature */:
63300                     case 170 /* FunctionType */:
63301                     case 171 /* ConstructorType */:
63302                     case 247 /* TypeAliasDeclaration */:
63303                     case 246 /* InterfaceDeclaration */:
63304                         checkUnusedTypeParameters(node, addDiagnostic);
63305                         break;
63306                     case 181 /* InferType */:
63307                         checkUnusedInferTypeParameter(node, addDiagnostic);
63308                         break;
63309                     default:
63310                         ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
63311                 }
63312             }
63313         }
63314         function errorUnusedLocal(declaration, name, addDiagnostic) {
63315             var node = ts.getNameOfDeclaration(declaration) || declaration;
63316             var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
63317             addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
63318         }
63319         function isIdentifierThatStartsWithUnderscore(node) {
63320             return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
63321         }
63322         function checkUnusedClassMembers(node, addDiagnostic) {
63323             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
63324                 var member = _a[_i];
63325                 switch (member.kind) {
63326                     case 161 /* MethodDeclaration */:
63327                     case 159 /* PropertyDeclaration */:
63328                     case 163 /* GetAccessor */:
63329                     case 164 /* SetAccessor */:
63330                         if (member.kind === 164 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
63331                             // Already would have reported an error on the getter.
63332                             break;
63333                         }
63334                         var symbol = getSymbolOfNode(member);
63335                         if (!symbol.isReferenced
63336                             && (ts.hasModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))
63337                             && !(member.flags & 8388608 /* Ambient */)) {
63338                             addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
63339                         }
63340                         break;
63341                     case 162 /* Constructor */:
63342                         for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
63343                             var parameter = _c[_b];
63344                             if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
63345                                 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
63346                             }
63347                         }
63348                         break;
63349                     case 167 /* IndexSignature */:
63350                     case 222 /* SemicolonClassElement */:
63351                         // Can't be private
63352                         break;
63353                     default:
63354                         ts.Debug.fail();
63355                 }
63356             }
63357         }
63358         function checkUnusedInferTypeParameter(node, addDiagnostic) {
63359             var typeParameter = node.typeParameter;
63360             if (isTypeParameterUnused(typeParameter)) {
63361                 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
63362             }
63363         }
63364         function checkUnusedTypeParameters(node, addDiagnostic) {
63365             // Only report errors on the last declaration for the type parameter container;
63366             // this ensures that all uses have been accounted for.
63367             if (ts.last(getSymbolOfNode(node).declarations) !== node)
63368                 return;
63369             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
63370             var seenParentsWithEveryUnused = new ts.NodeSet();
63371             for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
63372                 var typeParameter = typeParameters_3[_i];
63373                 if (!isTypeParameterUnused(typeParameter))
63374                     continue;
63375                 var name = ts.idText(typeParameter.name);
63376                 var parent = typeParameter.parent;
63377                 if (parent.kind !== 181 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
63378                     if (seenParentsWithEveryUnused.tryAdd(parent)) {
63379                         var range = ts.isJSDocTemplateTag(parent)
63380                             // Whole @template tag
63381                             ? ts.rangeOfNode(parent)
63382                             // Include the `<>` in the error message
63383                             : ts.rangeOfTypeParameters(parent.typeParameters);
63384                         var only = parent.typeParameters.length === 1;
63385                         var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
63386                         var arg0 = only ? name : undefined;
63387                         addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
63388                     }
63389                 }
63390                 else {
63391                     addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
63392                 }
63393             }
63394         }
63395         function isTypeParameterUnused(typeParameter) {
63396             return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
63397         }
63398         function addToGroup(map, key, value, getKey) {
63399             var keyString = String(getKey(key));
63400             var group = map.get(keyString);
63401             if (group) {
63402                 group[1].push(value);
63403             }
63404             else {
63405                 map.set(keyString, [key, [value]]);
63406             }
63407         }
63408         function tryGetRootParameterDeclaration(node) {
63409             return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
63410         }
63411         function isValidUnusedLocalDeclaration(declaration) {
63412             if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
63413                 return !!ts.findAncestor(declaration.parent, function (ancestor) {
63414                     return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false :
63415                         ts.isForOfStatement(ancestor) ? true : "quit";
63416                 });
63417             }
63418             return ts.isAmbientModule(declaration) ||
63419                 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
63420         }
63421         function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
63422             // 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.
63423             var unusedImports = ts.createMap();
63424             var unusedDestructures = ts.createMap();
63425             var unusedVariables = ts.createMap();
63426             nodeWithLocals.locals.forEach(function (local) {
63427                 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
63428                 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
63429                 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
63430                     return;
63431                 }
63432                 for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
63433                     var declaration = _a[_i];
63434                     if (isValidUnusedLocalDeclaration(declaration)) {
63435                         continue;
63436                     }
63437                     if (isImportedDeclaration(declaration)) {
63438                         addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
63439                     }
63440                     else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
63441                         // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
63442                         var lastElement = ts.last(declaration.parent.elements);
63443                         if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
63444                             addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
63445                         }
63446                     }
63447                     else if (ts.isVariableDeclaration(declaration)) {
63448                         addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
63449                     }
63450                     else {
63451                         var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
63452                         var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
63453                         if (parameter && name) {
63454                             if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
63455                                 addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
63456                             }
63457                         }
63458                         else {
63459                             errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
63460                         }
63461                     }
63462                 }
63463             });
63464             unusedImports.forEach(function (_a) {
63465                 var importClause = _a[0], unuseds = _a[1];
63466                 var importDecl = importClause.parent;
63467                 var nDeclarations = (importClause.name ? 1 : 0) +
63468                     (importClause.namedBindings ?
63469                         (importClause.namedBindings.kind === 256 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
63470                         : 0);
63471                 if (nDeclarations === unuseds.length) {
63472                     addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
63473                         ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
63474                         : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
63475                 }
63476                 else {
63477                     for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
63478                         var unused = unuseds_1[_i];
63479                         errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
63480                     }
63481                 }
63482             });
63483             unusedDestructures.forEach(function (_a) {
63484                 var bindingPattern = _a[0], bindingElements = _a[1];
63485                 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
63486                 if (bindingPattern.elements.length === bindingElements.length) {
63487                     if (bindingElements.length === 1 && bindingPattern.parent.kind === 242 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 243 /* VariableDeclarationList */) {
63488                         addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
63489                     }
63490                     else {
63491                         addDiagnostic(bindingPattern, kind, bindingElements.length === 1
63492                             ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
63493                             : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
63494                     }
63495                 }
63496                 else {
63497                     for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
63498                         var e = bindingElements_1[_i];
63499                         addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
63500                     }
63501                 }
63502             });
63503             unusedVariables.forEach(function (_a) {
63504                 var declarationList = _a[0], declarations = _a[1];
63505                 if (declarationList.declarations.length === declarations.length) {
63506                     addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
63507                         ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
63508                         : ts.createDiagnosticForNode(declarationList.parent.kind === 225 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
63509                 }
63510                 else {
63511                     for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
63512                         var decl = declarations_5[_i];
63513                         addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
63514                     }
63515                 }
63516             });
63517         }
63518         function bindingNameText(name) {
63519             switch (name.kind) {
63520                 case 75 /* Identifier */:
63521                     return ts.idText(name);
63522                 case 190 /* ArrayBindingPattern */:
63523                 case 189 /* ObjectBindingPattern */:
63524                     return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
63525                 default:
63526                     return ts.Debug.assertNever(name);
63527             }
63528         }
63529         function isImportedDeclaration(node) {
63530             return node.kind === 255 /* ImportClause */ || node.kind === 258 /* ImportSpecifier */ || node.kind === 256 /* NamespaceImport */;
63531         }
63532         function importClauseFromImported(decl) {
63533             return decl.kind === 255 /* ImportClause */ ? decl : decl.kind === 256 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
63534         }
63535         function checkBlock(node) {
63536             // Grammar checking for SyntaxKind.Block
63537             if (node.kind === 223 /* Block */) {
63538                 checkGrammarStatementInAmbientContext(node);
63539             }
63540             if (ts.isFunctionOrModuleBlock(node)) {
63541                 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
63542                 ts.forEach(node.statements, checkSourceElement);
63543                 flowAnalysisDisabled = saveFlowAnalysisDisabled;
63544             }
63545             else {
63546                 ts.forEach(node.statements, checkSourceElement);
63547             }
63548             if (node.locals) {
63549                 registerForUnusedIdentifiersCheck(node);
63550             }
63551         }
63552         function checkCollisionWithArgumentsInGeneratedCode(node) {
63553             // no rest parameters \ declaration context \ overload - no codegen impact
63554             if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
63555                 return;
63556             }
63557             ts.forEach(node.parameters, function (p) {
63558                 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
63559                     error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
63560                 }
63561             });
63562         }
63563         function needCollisionCheckForIdentifier(node, identifier, name) {
63564             if (!(identifier && identifier.escapedText === name)) {
63565                 return false;
63566             }
63567             if (node.kind === 159 /* PropertyDeclaration */ ||
63568                 node.kind === 158 /* PropertySignature */ ||
63569                 node.kind === 161 /* MethodDeclaration */ ||
63570                 node.kind === 160 /* MethodSignature */ ||
63571                 node.kind === 163 /* GetAccessor */ ||
63572                 node.kind === 164 /* SetAccessor */) {
63573                 // it is ok to have member named '_super' or '_this' - member access is always qualified
63574                 return false;
63575             }
63576             if (node.flags & 8388608 /* Ambient */) {
63577                 // ambient context - no codegen impact
63578                 return false;
63579             }
63580             var root = ts.getRootDeclaration(node);
63581             if (root.kind === 156 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
63582                 // just an overload - no codegen impact
63583                 return false;
63584             }
63585             return true;
63586         }
63587         // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
63588         function checkIfThisIsCapturedInEnclosingScope(node) {
63589             ts.findAncestor(node, function (current) {
63590                 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
63591                     var isDeclaration_1 = node.kind !== 75 /* Identifier */;
63592                     if (isDeclaration_1) {
63593                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
63594                     }
63595                     else {
63596                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
63597                     }
63598                     return true;
63599                 }
63600                 return false;
63601             });
63602         }
63603         function checkIfNewTargetIsCapturedInEnclosingScope(node) {
63604             ts.findAncestor(node, function (current) {
63605                 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
63606                     var isDeclaration_2 = node.kind !== 75 /* Identifier */;
63607                     if (isDeclaration_2) {
63608                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
63609                     }
63610                     else {
63611                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
63612                     }
63613                     return true;
63614                 }
63615                 return false;
63616             });
63617         }
63618         function checkWeakMapCollision(node) {
63619             var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
63620             if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
63621                 error(node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap");
63622             }
63623         }
63624         function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
63625             // No need to check for require or exports for ES6 modules and later
63626             if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) {
63627                 return;
63628             }
63629             if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
63630                 return;
63631             }
63632             // Uninstantiated modules shouldnt do this check
63633             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63634                 return;
63635             }
63636             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63637             var parent = getDeclarationContainer(node);
63638             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
63639                 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
63640                 error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
63641             }
63642         }
63643         function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
63644             if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) {
63645                 return;
63646             }
63647             // Uninstantiated modules shouldnt do this check
63648             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63649                 return;
63650             }
63651             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63652             var parent = getDeclarationContainer(node);
63653             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
63654                 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
63655                 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));
63656             }
63657         }
63658         function checkVarDeclaredNamesNotShadowed(node) {
63659             // - ScriptBody : StatementList
63660             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63661             // also occurs in the VarDeclaredNames of StatementList.
63662             // - Block : { StatementList }
63663             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63664             // also occurs in the VarDeclaredNames of StatementList.
63665             // Variable declarations are hoisted to the top of their function scope. They can shadow
63666             // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
63667             // by the binder as the declaration scope is different.
63668             // A non-initialized declaration is a no-op as the block declaration will resolve before the var
63669             // declaration. the problem is if the declaration has an initializer. this will act as a write to the
63670             // block declared value. this is fine for let, but not const.
63671             // Only consider declarations with initializers, uninitialized const declarations will not
63672             // step on a let/const variable.
63673             // Do not consider const and const declarations, as duplicate block-scoped declarations
63674             // are handled by the binder.
63675             // We are only looking for const declarations that step on let\const declarations from a
63676             // different scope. e.g.:
63677             //      {
63678             //          const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
63679             //          const x = 0; // symbol for this declaration will be 'symbol'
63680             //      }
63681             // skip block-scoped variables and parameters
63682             if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
63683                 return;
63684             }
63685             // skip variable declarations that don't have initializers
63686             // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
63687             // so we'll always treat binding elements as initialized
63688             if (node.kind === 242 /* VariableDeclaration */ && !node.initializer) {
63689                 return;
63690             }
63691             var symbol = getSymbolOfNode(node);
63692             if (symbol.flags & 1 /* FunctionScopedVariable */) {
63693                 if (!ts.isIdentifier(node.name))
63694                     return ts.Debug.fail();
63695                 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
63696                 if (localDeclarationSymbol &&
63697                     localDeclarationSymbol !== symbol &&
63698                     localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
63699                     if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
63700                         var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 243 /* VariableDeclarationList */);
63701                         var container = varDeclList.parent.kind === 225 /* VariableStatement */ && varDeclList.parent.parent
63702                             ? varDeclList.parent.parent
63703                             : undefined;
63704                         // names of block-scoped and function scoped variables can collide only
63705                         // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
63706                         var namesShareScope = container &&
63707                             (container.kind === 223 /* Block */ && ts.isFunctionLike(container.parent) ||
63708                                 container.kind === 250 /* ModuleBlock */ ||
63709                                 container.kind === 249 /* ModuleDeclaration */ ||
63710                                 container.kind === 290 /* SourceFile */);
63711                         // here we know that function scoped variable is shadowed by block scoped one
63712                         // if they are defined in the same scope - binder has already reported redeclaration error
63713                         // otherwise if variable has an initializer - show error that initialization will fail
63714                         // since LHS will be block scoped name instead of function scoped
63715                         if (!namesShareScope) {
63716                             var name = symbolToString(localDeclarationSymbol);
63717                             error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
63718                         }
63719                     }
63720                 }
63721             }
63722         }
63723         function convertAutoToAny(type) {
63724             return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
63725         }
63726         // Check variable, parameter, or property declaration
63727         function checkVariableLikeDeclaration(node) {
63728             checkDecorators(node);
63729             if (!ts.isBindingElement(node)) {
63730                 checkSourceElement(node.type);
63731             }
63732             // JSDoc `function(string, string): string` syntax results in parameters with no name
63733             if (!node.name) {
63734                 return;
63735             }
63736             // For a computed property, just check the initializer and exit
63737             // Do not use hasDynamicName here, because that returns false for well known symbols.
63738             // We want to perform checkComputedPropertyName for all computed properties, including
63739             // well known symbols.
63740             if (node.name.kind === 154 /* ComputedPropertyName */) {
63741                 checkComputedPropertyName(node.name);
63742                 if (node.initializer) {
63743                     checkExpressionCached(node.initializer);
63744                 }
63745             }
63746             if (node.kind === 191 /* BindingElement */) {
63747                 if (node.parent.kind === 189 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) {
63748                     checkExternalEmitHelpers(node, 4 /* Rest */);
63749                 }
63750                 // check computed properties inside property names of binding elements
63751                 if (node.propertyName && node.propertyName.kind === 154 /* ComputedPropertyName */) {
63752                     checkComputedPropertyName(node.propertyName);
63753                 }
63754                 // check private/protected variable access
63755                 var parent = node.parent.parent;
63756                 var parentType = getTypeForBindingElementParent(parent);
63757                 var name = node.propertyName || node.name;
63758                 if (parentType && !ts.isBindingPattern(name)) {
63759                     var exprType = getLiteralTypeFromPropertyName(name);
63760                     if (isTypeUsableAsPropertyName(exprType)) {
63761                         var nameText = getPropertyNameFromType(exprType);
63762                         var property = getPropertyOfType(parentType, nameText);
63763                         if (property) {
63764                             markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
63765                             checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 102 /* SuperKeyword */, parentType, property);
63766                         }
63767                     }
63768                 }
63769             }
63770             // For a binding pattern, check contained binding elements
63771             if (ts.isBindingPattern(node.name)) {
63772                 if (node.name.kind === 190 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
63773                     checkExternalEmitHelpers(node, 512 /* Read */);
63774                 }
63775                 ts.forEach(node.name.elements, checkSourceElement);
63776             }
63777             // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
63778             if (node.initializer && ts.getRootDeclaration(node).kind === 156 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
63779                 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
63780                 return;
63781             }
63782             // For a binding pattern, validate the initializer and exit
63783             if (ts.isBindingPattern(node.name)) {
63784                 var needCheckInitializer = node.initializer && node.parent.parent.kind !== 231 /* ForInStatement */;
63785                 var needCheckWidenedType = node.name.elements.length === 0;
63786                 if (needCheckInitializer || needCheckWidenedType) {
63787                     // Don't validate for-in initializer as it is already an error
63788                     var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
63789                     if (needCheckInitializer) {
63790                         var initializerType = checkExpressionCached(node.initializer);
63791                         if (strictNullChecks && needCheckWidenedType) {
63792                             checkNonNullNonVoidType(initializerType, node);
63793                         }
63794                         else {
63795                             checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
63796                         }
63797                     }
63798                     // check the binding pattern with empty elements
63799                     if (needCheckWidenedType) {
63800                         if (ts.isArrayBindingPattern(node.name)) {
63801                             checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
63802                         }
63803                         else if (strictNullChecks) {
63804                             checkNonNullNonVoidType(widenedType, node);
63805                         }
63806                     }
63807                 }
63808                 return;
63809             }
63810             var symbol = getSymbolOfNode(node);
63811             var type = convertAutoToAny(getTypeOfSymbol(symbol));
63812             if (node === symbol.valueDeclaration) {
63813                 // Node is the primary declaration of the symbol, just validate the initializer
63814                 // Don't validate for-in initializer as it is already an error
63815                 var initializer = ts.getEffectiveInitializer(node);
63816                 if (initializer) {
63817                     var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
63818                         ts.isObjectLiteralExpression(initializer) &&
63819                         (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
63820                         ts.hasEntries(symbol.exports);
63821                     if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 231 /* ForInStatement */) {
63822                         checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
63823                     }
63824                 }
63825                 if (symbol.declarations.length > 1) {
63826                     if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
63827                         error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
63828                     }
63829                 }
63830             }
63831             else {
63832                 // Node is a secondary declaration, check that type is identical to primary declaration and check that
63833                 // initializer is consistent with type associated with the node
63834                 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
63835                 if (type !== errorType && declarationType !== errorType &&
63836                     !isTypeIdenticalTo(type, declarationType) &&
63837                     !(symbol.flags & 67108864 /* Assignment */)) {
63838                     errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
63839                 }
63840                 if (node.initializer) {
63841                     checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
63842                 }
63843                 if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
63844                     error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
63845                 }
63846             }
63847             if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */) {
63848                 // We know we don't have a binding pattern or computed name here
63849                 checkExportsOnMergedDeclarations(node);
63850                 if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
63851                     checkVarDeclaredNamesNotShadowed(node);
63852                 }
63853                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
63854                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
63855                 if (!compilerOptions.noEmit && languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) {
63856                     potentialWeakMapCollisions.push(node);
63857                 }
63858             }
63859         }
63860         function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
63861             var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
63862             var message = nextDeclaration.kind === 159 /* PropertyDeclaration */ || nextDeclaration.kind === 158 /* PropertySignature */
63863                 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
63864                 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
63865             var declName = ts.declarationNameToString(nextDeclarationName);
63866             var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
63867             if (firstDeclaration) {
63868                 ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
63869             }
63870         }
63871         function areDeclarationFlagsIdentical(left, right) {
63872             if ((left.kind === 156 /* Parameter */ && right.kind === 242 /* VariableDeclaration */) ||
63873                 (left.kind === 242 /* VariableDeclaration */ && right.kind === 156 /* Parameter */)) {
63874                 // Differences in optionality between parameters and variables are allowed.
63875                 return true;
63876             }
63877             if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
63878                 return false;
63879             }
63880             var interestingFlags = 8 /* Private */ |
63881                 16 /* Protected */ |
63882                 256 /* Async */ |
63883                 128 /* Abstract */ |
63884                 64 /* Readonly */ |
63885                 32 /* Static */;
63886             return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags);
63887         }
63888         function checkVariableDeclaration(node) {
63889             checkGrammarVariableDeclaration(node);
63890             return checkVariableLikeDeclaration(node);
63891         }
63892         function checkBindingElement(node) {
63893             checkGrammarBindingElement(node);
63894             return checkVariableLikeDeclaration(node);
63895         }
63896         function checkVariableStatement(node) {
63897             // Grammar checking
63898             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
63899                 checkGrammarForDisallowedLetOrConstStatement(node);
63900             ts.forEach(node.declarationList.declarations, checkSourceElement);
63901         }
63902         function checkExpressionStatement(node) {
63903             // Grammar checking
63904             checkGrammarStatementInAmbientContext(node);
63905             checkExpression(node.expression);
63906         }
63907         function checkIfStatement(node) {
63908             // Grammar checking
63909             checkGrammarStatementInAmbientContext(node);
63910             var type = checkTruthinessExpression(node.expression);
63911             checkTestingKnownTruthyCallableType(node.expression, node.thenStatement, type);
63912             checkSourceElement(node.thenStatement);
63913             if (node.thenStatement.kind === 224 /* EmptyStatement */) {
63914                 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
63915             }
63916             checkSourceElement(node.elseStatement);
63917         }
63918         function checkTestingKnownTruthyCallableType(condExpr, body, type) {
63919             if (!strictNullChecks) {
63920                 return;
63921             }
63922             var testedNode = ts.isIdentifier(condExpr)
63923                 ? condExpr
63924                 : ts.isPropertyAccessExpression(condExpr)
63925                     ? condExpr.name
63926                     : undefined;
63927             if (!testedNode) {
63928                 return;
63929             }
63930             var possiblyFalsy = getFalsyFlags(type);
63931             if (possiblyFalsy) {
63932                 return;
63933             }
63934             // While it technically should be invalid for any known-truthy value
63935             // to be tested, we de-scope to functions unrefenced in the block as a
63936             // heuristic to identify the most common bugs. There are too many
63937             // false positives for values sourced from type definitions without
63938             // strictNullChecks otherwise.
63939             var callSignatures = getSignaturesOfType(type, 0 /* Call */);
63940             if (callSignatures.length === 0) {
63941                 return;
63942             }
63943             var testedFunctionSymbol = getSymbolAtLocation(testedNode);
63944             if (!testedFunctionSymbol) {
63945                 return;
63946             }
63947             var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) {
63948                 if (ts.isIdentifier(childNode)) {
63949                     var childSymbol = getSymbolAtLocation(childNode);
63950                     if (childSymbol && childSymbol === testedFunctionSymbol) {
63951                         // If the test was a simple identifier, the above check is sufficient
63952                         if (ts.isIdentifier(condExpr)) {
63953                             return true;
63954                         }
63955                         // Otherwise we need to ensure the symbol is called on the same target
63956                         var testedExpression = testedNode.parent;
63957                         var childExpression = childNode.parent;
63958                         while (testedExpression && childExpression) {
63959                             if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) ||
63960                                 testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) {
63961                                 return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
63962                             }
63963                             if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
63964                                 if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
63965                                     return false;
63966                                 }
63967                                 childExpression = childExpression.expression;
63968                                 testedExpression = testedExpression.expression;
63969                             }
63970                             else {
63971                                 return false;
63972                             }
63973                         }
63974                     }
63975                 }
63976                 return ts.forEachChild(childNode, check);
63977             });
63978             if (!functionIsUsedInBody) {
63979                 error(condExpr, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
63980             }
63981         }
63982         function checkDoStatement(node) {
63983             // Grammar checking
63984             checkGrammarStatementInAmbientContext(node);
63985             checkSourceElement(node.statement);
63986             checkTruthinessExpression(node.expression);
63987         }
63988         function checkWhileStatement(node) {
63989             // Grammar checking
63990             checkGrammarStatementInAmbientContext(node);
63991             checkTruthinessExpression(node.expression);
63992             checkSourceElement(node.statement);
63993         }
63994         function checkTruthinessOfType(type, node) {
63995             if (type.flags & 16384 /* Void */) {
63996                 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
63997             }
63998             return type;
63999         }
64000         function checkTruthinessExpression(node, checkMode) {
64001             return checkTruthinessOfType(checkExpression(node, checkMode), node);
64002         }
64003         function checkForStatement(node) {
64004             // Grammar checking
64005             if (!checkGrammarStatementInAmbientContext(node)) {
64006                 if (node.initializer && node.initializer.kind === 243 /* VariableDeclarationList */) {
64007                     checkGrammarVariableDeclarationList(node.initializer);
64008                 }
64009             }
64010             if (node.initializer) {
64011                 if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64012                     ts.forEach(node.initializer.declarations, checkVariableDeclaration);
64013                 }
64014                 else {
64015                     checkExpression(node.initializer);
64016                 }
64017             }
64018             if (node.condition)
64019                 checkTruthinessExpression(node.condition);
64020             if (node.incrementor)
64021                 checkExpression(node.incrementor);
64022             checkSourceElement(node.statement);
64023             if (node.locals) {
64024                 registerForUnusedIdentifiersCheck(node);
64025             }
64026         }
64027         function checkForOfStatement(node) {
64028             checkGrammarForInOrForOfStatement(node);
64029             if (node.awaitModifier) {
64030                 var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
64031                 if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
64032                     // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
64033                     checkExternalEmitHelpers(node, 32768 /* ForAwaitOfIncludes */);
64034                 }
64035             }
64036             else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
64037                 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
64038                 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
64039             }
64040             // Check the LHS and RHS
64041             // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
64042             // via checkRightHandSideOfForOf.
64043             // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
64044             // Then check that the RHS is assignable to it.
64045             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64046                 checkForInOrForOfVariableDeclaration(node);
64047             }
64048             else {
64049                 var varExpr = node.initializer;
64050                 var iteratedType = checkRightHandSideOfForOf(node);
64051                 // There may be a destructuring assignment on the left side
64052                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64053                     // iteratedType may be undefined. In this case, we still want to check the structure of
64054                     // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
64055                     // to short circuit the type relation checking as much as possible, so we pass the unknownType.
64056                     checkDestructuringAssignment(varExpr, iteratedType || errorType);
64057                 }
64058                 else {
64059                     var leftType = checkExpression(varExpr);
64060                     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);
64061                     // iteratedType will be undefined if the rightType was missing properties/signatures
64062                     // required to get its iteratedType (like [Symbol.iterator] or next). This may be
64063                     // because we accessed properties from anyType, or it may have led to an error inside
64064                     // getElementTypeOfIterable.
64065                     if (iteratedType) {
64066                         checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
64067                     }
64068                 }
64069             }
64070             checkSourceElement(node.statement);
64071             if (node.locals) {
64072                 registerForUnusedIdentifiersCheck(node);
64073             }
64074         }
64075         function checkForInStatement(node) {
64076             // Grammar checking
64077             checkGrammarForInOrForOfStatement(node);
64078             var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
64079             // TypeScript 1.0 spec (April 2014): 5.4
64080             // In a 'for-in' statement of the form
64081             // for (let VarDecl in Expr) Statement
64082             //   VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
64083             //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64084             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64085                 var variable = node.initializer.declarations[0];
64086                 if (variable && ts.isBindingPattern(variable.name)) {
64087                     error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64088                 }
64089                 checkForInOrForOfVariableDeclaration(node);
64090             }
64091             else {
64092                 // In a 'for-in' statement of the form
64093                 // for (Var in Expr) Statement
64094                 //   Var must be an expression classified as a reference of type Any or the String primitive type,
64095                 //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64096                 var varExpr = node.initializer;
64097                 var leftType = checkExpression(varExpr);
64098                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64099                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64100                 }
64101                 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
64102                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
64103                 }
64104                 else {
64105                     // run check only former check succeeded to avoid cascading errors
64106                     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);
64107                 }
64108             }
64109             // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
64110             // in this case error about missing name is already reported - do not report extra one
64111             if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
64112                 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));
64113             }
64114             checkSourceElement(node.statement);
64115             if (node.locals) {
64116                 registerForUnusedIdentifiersCheck(node);
64117             }
64118         }
64119         function checkForInOrForOfVariableDeclaration(iterationStatement) {
64120             var variableDeclarationList = iterationStatement.initializer;
64121             // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
64122             if (variableDeclarationList.declarations.length >= 1) {
64123                 var decl = variableDeclarationList.declarations[0];
64124                 checkVariableDeclaration(decl);
64125             }
64126         }
64127         function checkRightHandSideOfForOf(statement) {
64128             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
64129             return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
64130         }
64131         function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
64132             if (isTypeAny(inputType)) {
64133                 return inputType;
64134             }
64135             return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
64136         }
64137         /**
64138          * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
64139          * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
64140          * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
64141          */
64142         function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
64143             var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
64144             if (inputType === neverType) {
64145                 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
64146                 return undefined;
64147             }
64148             var uplevelIteration = languageVersion >= 2 /* ES2015 */;
64149             var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
64150             // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
64151             // or higher, when inside of an async generator or for-await-if, or when
64152             // downlevelIteration is requested.
64153             if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
64154                 // We only report errors for an invalid iterable type in ES2015 or higher.
64155                 var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
64156                 if (checkAssignability) {
64157                     if (iterationTypes) {
64158                         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 :
64159                             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 :
64160                                 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 :
64161                                     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 :
64162                                         undefined;
64163                         if (diagnostic) {
64164                             checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
64165                         }
64166                     }
64167                 }
64168                 if (iterationTypes || uplevelIteration) {
64169                     return iterationTypes && iterationTypes.yieldType;
64170                 }
64171             }
64172             var arrayType = inputType;
64173             var reportedError = false;
64174             var hasStringConstituent = false;
64175             // If strings are permitted, remove any string-like constituents from the array type.
64176             // This allows us to find other non-string element types from an array unioned with
64177             // a string.
64178             if (use & 4 /* AllowsStringInputFlag */) {
64179                 if (arrayType.flags & 1048576 /* Union */) {
64180                     // After we remove all types that are StringLike, we will know if there was a string constituent
64181                     // based on whether the result of filter is a new array.
64182                     var arrayTypes = inputType.types;
64183                     var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); });
64184                     if (filteredTypes !== arrayTypes) {
64185                         arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
64186                     }
64187                 }
64188                 else if (arrayType.flags & 132 /* StringLike */) {
64189                     arrayType = neverType;
64190                 }
64191                 hasStringConstituent = arrayType !== inputType;
64192                 if (hasStringConstituent) {
64193                     if (languageVersion < 1 /* ES5 */) {
64194                         if (errorNode) {
64195                             error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
64196                             reportedError = true;
64197                         }
64198                     }
64199                     // Now that we've removed all the StringLike types, if no constituents remain, then the entire
64200                     // arrayOrStringType was a string.
64201                     if (arrayType.flags & 131072 /* Never */) {
64202                         return stringType;
64203                     }
64204                 }
64205             }
64206             if (!isArrayLikeType(arrayType)) {
64207                 if (errorNode && !reportedError) {
64208                     // Which error we report depends on whether we allow strings or if there was a
64209                     // string constituent. For example, if the input type is number | string, we
64210                     // want to say that number is not an array type. But if the input was just
64211                     // number and string input is allowed, we want to say that number is not an
64212                     // array type or a string type.
64213                     var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
64214                     var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent
64215                         ? downlevelIteration
64216                             ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
64217                             : yieldType
64218                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64219                                 : [ts.Diagnostics.Type_0_is_not_an_array_type, true]
64220                         : downlevelIteration
64221                             ? [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]
64222                             : yieldType
64223                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64224                                 : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
64225                     errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
64226                 }
64227                 return hasStringConstituent ? stringType : undefined;
64228             }
64229             var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
64230             if (hasStringConstituent && arrayElementType) {
64231                 // This is just an optimization for the case where arrayOrStringType is string | string[]
64232                 if (arrayElementType.flags & 132 /* StringLike */) {
64233                     return stringType;
64234                 }
64235                 return getUnionType([arrayElementType, stringType], 2 /* Subtype */);
64236             }
64237             return arrayElementType;
64238         }
64239         /**
64240          * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
64241          */
64242         function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
64243             if (isTypeAny(inputType)) {
64244                 return undefined;
64245             }
64246             var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
64247             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
64248         }
64249         function createIterationTypes(yieldType, returnType, nextType) {
64250             // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
64251             // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
64252             // as it is combined via `getIntersectionType` when merging iteration types.
64253             if (yieldType === void 0) { yieldType = neverType; }
64254             if (returnType === void 0) { returnType = neverType; }
64255             if (nextType === void 0) { nextType = unknownType; }
64256             // Use the cache only for intrinsic types to keep it small as they are likely to be
64257             // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
64258             // are also cached on the type they are requested for, so we shouldn't need to maintain
64259             // the cache for less-frequently used types.
64260             if (yieldType.flags & 67359327 /* Intrinsic */ &&
64261                 returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
64262                 nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
64263                 var id = getTypeListId([yieldType, returnType, nextType]);
64264                 var iterationTypes = iterationTypesCache.get(id);
64265                 if (!iterationTypes) {
64266                     iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
64267                     iterationTypesCache.set(id, iterationTypes);
64268                 }
64269                 return iterationTypes;
64270             }
64271             return { yieldType: yieldType, returnType: returnType, nextType: nextType };
64272         }
64273         /**
64274          * Combines multiple `IterationTypes` records.
64275          *
64276          * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
64277          * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
64278          * for the combined iteration types.
64279          */
64280         function combineIterationTypes(array) {
64281             var yieldTypes;
64282             var returnTypes;
64283             var nextTypes;
64284             for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
64285                 var iterationTypes = array_10[_i];
64286                 if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
64287                     continue;
64288                 }
64289                 if (iterationTypes === anyIterationTypes) {
64290                     return anyIterationTypes;
64291                 }
64292                 yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
64293                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64294                 nextTypes = ts.append(nextTypes, iterationTypes.nextType);
64295             }
64296             if (yieldTypes || returnTypes || nextTypes) {
64297                 return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
64298             }
64299             return noIterationTypes;
64300         }
64301         function getCachedIterationTypes(type, cacheKey) {
64302             return type[cacheKey];
64303         }
64304         function setCachedIterationTypes(type, cacheKey, cachedTypes) {
64305             return type[cacheKey] = cachedTypes;
64306         }
64307         /**
64308          * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
64309          *
64310          * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
64311          *
64312          * Another thing to note is that at any step of this process, we could run into a dead end,
64313          * meaning either the property is missing, or we run into the anyType. If either of these things
64314          * happens, we return `undefined` to signal that we could not find the iteration type. If a property
64315          * is missing, and the previous step did not result in `any`, then we also give an error if the
64316          * caller requested it. Then the caller can decide what to do in the case where there is no iterated
64317          * type.
64318          *
64319          * For a **for-of** statement, `yield*` (in a normal generator), spread, array
64320          * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
64321          * method.
64322          *
64323          * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
64324          *
64325          * For a **for-await-of** statement or a `yield*` in an async generator we will look for
64326          * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
64327          */
64328         function getIterationTypesOfIterable(type, use, errorNode) {
64329             if (isTypeAny(type)) {
64330                 return anyIterationTypes;
64331             }
64332             if (!(type.flags & 1048576 /* Union */)) {
64333                 var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
64334                 if (iterationTypes_1 === noIterationTypes) {
64335                     if (errorNode) {
64336                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64337                     }
64338                     return undefined;
64339                 }
64340                 return iterationTypes_1;
64341             }
64342             var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
64343             var cachedTypes = getCachedIterationTypes(type, cacheKey);
64344             if (cachedTypes)
64345                 return cachedTypes === noIterationTypes ? undefined : cachedTypes;
64346             var allIterationTypes;
64347             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
64348                 var constituent = _a[_i];
64349                 var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
64350                 if (iterationTypes_2 === noIterationTypes) {
64351                     if (errorNode) {
64352                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64353                         errorNode = undefined;
64354                     }
64355                 }
64356                 else {
64357                     allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
64358                 }
64359             }
64360             var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
64361             setCachedIterationTypes(type, cacheKey, iterationTypes);
64362             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64363         }
64364         function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
64365             if (iterationTypes === noIterationTypes)
64366                 return noIterationTypes;
64367             if (iterationTypes === anyIterationTypes)
64368                 return anyIterationTypes;
64369             var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
64370             return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
64371         }
64372         /**
64373          * Gets the *yield*, *return*, and *next* types from a non-union type.
64374          *
64375          * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
64376          * returned to indicate to the caller that it should report an error. Otherwise, an
64377          * `IterationTypes` record is returned.
64378          *
64379          * NOTE: You probably don't want to call this directly and should be calling
64380          * `getIterationTypesOfIterable` instead.
64381          */
64382         function getIterationTypesOfIterableWorker(type, use, errorNode) {
64383             if (isTypeAny(type)) {
64384                 return anyIterationTypes;
64385             }
64386             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64387                 var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
64388                     getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
64389                 if (iterationTypes) {
64390                     return iterationTypes;
64391                 }
64392             }
64393             if (use & 1 /* AllowsSyncIterablesFlag */) {
64394                 var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
64395                     getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
64396                 if (iterationTypes) {
64397                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64398                         // for a sync iterable in an async context, only use the cached types if they are valid.
64399                         if (iterationTypes !== noIterationTypes) {
64400                             return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
64401                         }
64402                     }
64403                     else {
64404                         return iterationTypes;
64405                     }
64406                 }
64407             }
64408             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64409                 var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
64410                 if (iterationTypes !== noIterationTypes) {
64411                     return iterationTypes;
64412                 }
64413             }
64414             if (use & 1 /* AllowsSyncIterablesFlag */) {
64415                 var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
64416                 if (iterationTypes !== noIterationTypes) {
64417                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64418                         return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
64419                             ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
64420                             : noIterationTypes);
64421                     }
64422                     else {
64423                         return iterationTypes;
64424                     }
64425                 }
64426             }
64427             return noIterationTypes;
64428         }
64429         /**
64430          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
64431          * `AsyncIterable`-like type from the cache.
64432          *
64433          * NOTE: You probably don't want to call this directly and should be calling
64434          * `getIterationTypesOfIterable` instead.
64435          */
64436         function getIterationTypesOfIterableCached(type, resolver) {
64437             return getCachedIterationTypes(type, resolver.iterableCacheKey);
64438         }
64439         function getIterationTypesOfGlobalIterableType(globalType, resolver) {
64440             var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
64441                 getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
64442             return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
64443         }
64444         /**
64445          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64446          * type from from common heuristics.
64447          *
64448          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64449          * returned. If we found iteration types, an `IterationTypes` record is returned.
64450          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64451          * exhaustive analysis.
64452          *
64453          * NOTE: You probably don't want to call this directly and should be calling
64454          * `getIterationTypesOfIterable` instead.
64455          */
64456         function getIterationTypesOfIterableFast(type, resolver) {
64457             // As an optimization, if the type is an instantiation of one of the following global types, then
64458             // just grab its related type argument:
64459             // - `Iterable<T>` or `AsyncIterable<T>`
64460             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64461             var globalType;
64462             if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
64463                 isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
64464                 var yieldType = getTypeArguments(type)[0];
64465                 // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
64466                 // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
64467                 // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
64468                 // different definitions.
64469                 var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
64470                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64471             }
64472             // As an optimization, if the type is an instantiation of the following global type, then
64473             // just grab its related type arguments:
64474             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64475             if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64476                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64477                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64478             }
64479         }
64480         /**
64481          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64482          * type from its members.
64483          *
64484          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64485          * record is returned. Otherwise, `noIterationTypes` is returned.
64486          *
64487          * NOTE: You probably don't want to call this directly and should be calling
64488          * `getIterationTypesOfIterable` instead.
64489          */
64490         function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
64491             var _a;
64492             var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
64493             var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
64494             if (isTypeAny(methodType)) {
64495                 return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
64496             }
64497             var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
64498             if (!ts.some(signatures)) {
64499                 return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
64500             }
64501             var iteratorType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */);
64502             var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
64503             return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
64504         }
64505         function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
64506             var message = allowAsyncIterables
64507                 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
64508                 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
64509             errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
64510         }
64511         /**
64512          * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
64513          *
64514          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64515          * record is returned. Otherwise, `undefined` is returned.
64516          */
64517         function getIterationTypesOfIterator(type, resolver, errorNode) {
64518             if (isTypeAny(type)) {
64519                 return anyIterationTypes;
64520             }
64521             var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
64522                 getIterationTypesOfIteratorFast(type, resolver) ||
64523                 getIterationTypesOfIteratorSlow(type, resolver, errorNode);
64524             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64525         }
64526         /**
64527          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64528          * cache.
64529          *
64530          * NOTE: You probably don't want to call this directly and should be calling
64531          * `getIterationTypesOfIterator` instead.
64532          */
64533         function getIterationTypesOfIteratorCached(type, resolver) {
64534             return getCachedIterationTypes(type, resolver.iteratorCacheKey);
64535         }
64536         /**
64537          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64538          * cache or from common heuristics.
64539          *
64540          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64541          * returned. If we found iteration types, an `IterationTypes` record is returned.
64542          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64543          * exhaustive analysis.
64544          *
64545          * NOTE: You probably don't want to call this directly and should be calling
64546          * `getIterationTypesOfIterator` instead.
64547          */
64548         function getIterationTypesOfIteratorFast(type, resolver) {
64549             // As an optimization, if the type is an instantiation of one of the following global types,
64550             // then just grab its related type argument:
64551             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64552             // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
64553             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64554             var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
64555             if (isReferenceToType(type, globalType)) {
64556                 var yieldType = getTypeArguments(type)[0];
64557                 // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
64558                 // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
64559                 // and `undefined` in our libs by default, a custom lib *could* use different definitions.
64560                 var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
64561                     getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
64562                 var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
64563                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64564             }
64565             if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
64566                 isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64567                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64568                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64569             }
64570         }
64571         function isIteratorResult(type, kind) {
64572             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
64573             // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
64574             // > If the end was not reached `done` is `false` and a value is available.
64575             // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
64576             var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
64577             return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
64578         }
64579         function isYieldIteratorResult(type) {
64580             return isIteratorResult(type, 0 /* Yield */);
64581         }
64582         function isReturnIteratorResult(type) {
64583             return isIteratorResult(type, 1 /* Return */);
64584         }
64585         /**
64586          * Gets the *yield* and *return* types of an `IteratorResult`-like type.
64587          *
64588          * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
64589          * returned to indicate to the caller that it should handle the error. Otherwise, an
64590          * `IterationTypes` record is returned.
64591          */
64592         function getIterationTypesOfIteratorResult(type) {
64593             if (isTypeAny(type)) {
64594                 return anyIterationTypes;
64595             }
64596             var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
64597             if (cachedTypes) {
64598                 return cachedTypes;
64599             }
64600             // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
64601             // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
64602             if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
64603                 var yieldType_1 = getTypeArguments(type)[0];
64604                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
64605             }
64606             if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
64607                 var returnType_1 = getTypeArguments(type)[0];
64608                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
64609             }
64610             // Choose any constituents that can produce the requested iteration type.
64611             var yieldIteratorResult = filterType(type, isYieldIteratorResult);
64612             var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
64613             var returnIteratorResult = filterType(type, isReturnIteratorResult);
64614             var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
64615             if (!yieldType && !returnType) {
64616                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
64617             }
64618             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
64619             // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
64620             // > `value` property may be absent from the conforming object if it does not inherit an explicit
64621             // > `value` property.
64622             return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
64623         }
64624         /**
64625          * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
64626          * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
64627          *
64628          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64629          * record is returned. Otherwise, we return `undefined`.
64630          */
64631         function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
64632             var method = getPropertyOfType(type, methodName);
64633             // Ignore 'return' or 'throw' if they are missing.
64634             if (!method && methodName !== "next") {
64635                 return undefined;
64636             }
64637             var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
64638                 ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
64639                 : undefined;
64640             if (isTypeAny(methodType)) {
64641                 // `return()` and `throw()` don't provide a *next* type.
64642                 return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
64643             }
64644             // Both async and non-async iterators *must* have a `next` method.
64645             var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
64646             if (methodSignatures.length === 0) {
64647                 if (errorNode) {
64648                     var diagnostic = methodName === "next"
64649                         ? resolver.mustHaveANextMethodDiagnostic
64650                         : resolver.mustBeAMethodDiagnostic;
64651                     error(errorNode, diagnostic, methodName);
64652                 }
64653                 return methodName === "next" ? anyIterationTypes : undefined;
64654             }
64655             // Extract the first parameter and return type of each signature.
64656             var methodParameterTypes;
64657             var methodReturnTypes;
64658             for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
64659                 var signature = methodSignatures_1[_i];
64660                 if (methodName !== "throw" && ts.some(signature.parameters)) {
64661                     methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
64662                 }
64663                 methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
64664             }
64665             // Resolve the *next* or *return* type from the first parameter of a `next()` or
64666             // `return()` method, respectively.
64667             var returnTypes;
64668             var nextType;
64669             if (methodName !== "throw") {
64670                 var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
64671                 if (methodName === "next") {
64672                     // The value of `next(value)` is *not* awaited by async generators
64673                     nextType = methodParameterType;
64674                 }
64675                 else if (methodName === "return") {
64676                     // The value of `return(value)` *is* awaited by async generators
64677                     var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
64678                     returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
64679                 }
64680             }
64681             // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
64682             var yieldType;
64683             var methodReturnType = methodReturnTypes ? getUnionType(methodReturnTypes, 2 /* Subtype */) : neverType;
64684             var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
64685             var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
64686             if (iterationTypes === noIterationTypes) {
64687                 if (errorNode) {
64688                     error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
64689                 }
64690                 yieldType = anyType;
64691                 returnTypes = ts.append(returnTypes, anyType);
64692             }
64693             else {
64694                 yieldType = iterationTypes.yieldType;
64695                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64696             }
64697             return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
64698         }
64699         /**
64700          * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
64701          * type from its members.
64702          *
64703          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64704          * record is returned. Otherwise, `noIterationTypes` is returned.
64705          *
64706          * NOTE: You probably don't want to call this directly and should be calling
64707          * `getIterationTypesOfIterator` instead.
64708          */
64709         function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
64710             var iterationTypes = combineIterationTypes([
64711                 getIterationTypesOfMethod(type, resolver, "next", errorNode),
64712                 getIterationTypesOfMethod(type, resolver, "return", errorNode),
64713                 getIterationTypesOfMethod(type, resolver, "throw", errorNode),
64714             ]);
64715             return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
64716         }
64717         /**
64718          * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
64719          * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
64720          * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
64721          */
64722         function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
64723             if (isTypeAny(returnType)) {
64724                 return undefined;
64725             }
64726             var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
64727             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
64728         }
64729         function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
64730             if (isTypeAny(type)) {
64731                 return anyIterationTypes;
64732             }
64733             var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
64734             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
64735             return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
64736                 getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
64737         }
64738         function checkBreakOrContinueStatement(node) {
64739             // Grammar checking
64740             if (!checkGrammarStatementInAmbientContext(node))
64741                 checkGrammarBreakOrContinueStatement(node);
64742             // TODO: Check that target label is valid
64743         }
64744         function unwrapReturnType(returnType, functionFlags) {
64745             var _a, _b;
64746             var isGenerator = !!(functionFlags & 1 /* Generator */);
64747             var isAsync = !!(functionFlags & 2 /* Async */);
64748             return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType :
64749                 isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType :
64750                     returnType;
64751         }
64752         function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
64753             var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
64754             return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
64755         }
64756         function checkReturnStatement(node) {
64757             var _a;
64758             // Grammar checking
64759             if (checkGrammarStatementInAmbientContext(node)) {
64760                 return;
64761             }
64762             var func = ts.getContainingFunction(node);
64763             if (!func) {
64764                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
64765                 return;
64766             }
64767             var signature = getSignatureFromDeclaration(func);
64768             var returnType = getReturnTypeOfSignature(signature);
64769             var functionFlags = ts.getFunctionFlags(func);
64770             if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
64771                 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
64772                 if (func.kind === 164 /* SetAccessor */) {
64773                     if (node.expression) {
64774                         error(node, ts.Diagnostics.Setters_cannot_return_a_value);
64775                     }
64776                 }
64777                 else if (func.kind === 162 /* Constructor */) {
64778                     if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
64779                         error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
64780                     }
64781                 }
64782                 else if (getReturnTypeFromAnnotation(func)) {
64783                     var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType;
64784                     var unwrappedExprType = functionFlags & 2 /* Async */
64785                         ? 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)
64786                         : exprType;
64787                     if (unwrappedReturnType) {
64788                         // If the function has a return type, but promisedType is
64789                         // undefined, an error will be reported in checkAsyncFunctionReturnType
64790                         // so we don't need to report one here.
64791                         checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
64792                     }
64793                 }
64794             }
64795             else if (func.kind !== 162 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
64796                 // The function has a return type, but the return statement doesn't have an expression.
64797                 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
64798             }
64799         }
64800         function checkWithStatement(node) {
64801             // Grammar checking for withStatement
64802             if (!checkGrammarStatementInAmbientContext(node)) {
64803                 if (node.flags & 32768 /* AwaitContext */) {
64804                     grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
64805                 }
64806             }
64807             checkExpression(node.expression);
64808             var sourceFile = ts.getSourceFileOfNode(node);
64809             if (!hasParseDiagnostics(sourceFile)) {
64810                 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
64811                 var end = node.statement.pos;
64812                 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
64813             }
64814         }
64815         function checkSwitchStatement(node) {
64816             // Grammar checking
64817             checkGrammarStatementInAmbientContext(node);
64818             var firstDefaultClause;
64819             var hasDuplicateDefaultClause = false;
64820             var expressionType = checkExpression(node.expression);
64821             var expressionIsLiteral = isLiteralType(expressionType);
64822             ts.forEach(node.caseBlock.clauses, function (clause) {
64823                 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
64824                 if (clause.kind === 278 /* DefaultClause */ && !hasDuplicateDefaultClause) {
64825                     if (firstDefaultClause === undefined) {
64826                         firstDefaultClause = clause;
64827                     }
64828                     else {
64829                         grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
64830                         hasDuplicateDefaultClause = true;
64831                     }
64832                 }
64833                 if (produceDiagnostics && clause.kind === 277 /* CaseClause */) {
64834                     // TypeScript 1.0 spec (April 2014): 5.9
64835                     // In a 'switch' statement, each 'case' expression must be of a type that is comparable
64836                     // to or from the type of the 'switch' expression.
64837                     var caseType = checkExpression(clause.expression);
64838                     var caseIsLiteral = isLiteralType(caseType);
64839                     var comparedExpressionType = expressionType;
64840                     if (!caseIsLiteral || !expressionIsLiteral) {
64841                         caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
64842                         comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
64843                     }
64844                     if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
64845                         // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
64846                         checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
64847                     }
64848                 }
64849                 ts.forEach(clause.statements, checkSourceElement);
64850                 if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
64851                     error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
64852                 }
64853             });
64854             if (node.caseBlock.locals) {
64855                 registerForUnusedIdentifiersCheck(node.caseBlock);
64856             }
64857         }
64858         function checkLabeledStatement(node) {
64859             // Grammar checking
64860             if (!checkGrammarStatementInAmbientContext(node)) {
64861                 ts.findAncestor(node.parent, function (current) {
64862                     if (ts.isFunctionLike(current)) {
64863                         return "quit";
64864                     }
64865                     if (current.kind === 238 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
64866                         grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
64867                         return true;
64868                     }
64869                     return false;
64870                 });
64871             }
64872             // ensure that label is unique
64873             checkSourceElement(node.statement);
64874         }
64875         function checkThrowStatement(node) {
64876             // Grammar checking
64877             if (!checkGrammarStatementInAmbientContext(node)) {
64878                 if (node.expression === undefined) {
64879                     grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
64880                 }
64881             }
64882             if (node.expression) {
64883                 checkExpression(node.expression);
64884             }
64885         }
64886         function checkTryStatement(node) {
64887             // Grammar checking
64888             checkGrammarStatementInAmbientContext(node);
64889             checkBlock(node.tryBlock);
64890             var catchClause = node.catchClause;
64891             if (catchClause) {
64892                 // Grammar checking
64893                 if (catchClause.variableDeclaration) {
64894                     if (catchClause.variableDeclaration.type) {
64895                         grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation);
64896                     }
64897                     else if (catchClause.variableDeclaration.initializer) {
64898                         grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
64899                     }
64900                     else {
64901                         var blockLocals_1 = catchClause.block.locals;
64902                         if (blockLocals_1) {
64903                             ts.forEachKey(catchClause.locals, function (caughtName) {
64904                                 var blockLocal = blockLocals_1.get(caughtName);
64905                                 if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
64906                                     grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
64907                                 }
64908                             });
64909                         }
64910                     }
64911                 }
64912                 checkBlock(catchClause.block);
64913             }
64914             if (node.finallyBlock) {
64915                 checkBlock(node.finallyBlock);
64916             }
64917         }
64918         function checkIndexConstraints(type) {
64919             var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
64920             var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
64921             var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
64922             var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
64923             if (stringIndexType || numberIndexType) {
64924                 ts.forEach(getPropertiesOfObjectType(type), function (prop) {
64925                     var propType = getTypeOfSymbol(prop);
64926                     checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
64927                     checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
64928                 });
64929                 var classDeclaration = type.symbol.valueDeclaration;
64930                 if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
64931                     for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
64932                         var member = _a[_i];
64933                         // Only process instance properties with computed names here.
64934                         // Static properties cannot be in conflict with indexers,
64935                         // and properties with literal names were already checked.
64936                         if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
64937                             var symbol = getSymbolOfNode(member);
64938                             var propType = getTypeOfSymbol(symbol);
64939                             checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
64940                             checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
64941                         }
64942                     }
64943                 }
64944             }
64945             var errorNode;
64946             if (stringIndexType && numberIndexType) {
64947                 errorNode = declaredNumberIndexer || declaredStringIndexer;
64948                 // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
64949                 if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
64950                     var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
64951                     errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
64952                 }
64953             }
64954             if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
64955                 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
64956             }
64957             function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
64958                 // ESSymbol properties apply to neither string nor numeric indexers.
64959                 if (!indexType || ts.isKnownSymbol(prop)) {
64960                     return;
64961                 }
64962                 var propDeclaration = prop.valueDeclaration;
64963                 var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
64964                 if (name && ts.isPrivateIdentifier(name)) {
64965                     return;
64966                 }
64967                 // index is numeric and property name is not valid numeric literal
64968                 if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
64969                     return;
64970                 }
64971                 // perform property check if property or indexer is declared in 'type'
64972                 // this allows us to rule out cases when both property and indexer are inherited from the base class
64973                 var errorNode;
64974                 if (propDeclaration && name &&
64975                     (propDeclaration.kind === 209 /* BinaryExpression */ ||
64976                         name.kind === 154 /* ComputedPropertyName */ ||
64977                         prop.parent === containingType.symbol)) {
64978                     errorNode = propDeclaration;
64979                 }
64980                 else if (indexDeclaration) {
64981                     errorNode = indexDeclaration;
64982                 }
64983                 else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
64984                     // for interfaces property and indexer might be inherited from different bases
64985                     // check if any base class already has both property and indexer.
64986                     // check should be performed only if 'type' is the first type that brings property\indexer together
64987                     var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
64988                     errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
64989                 }
64990                 if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
64991                     var errorMessage = indexKind === 0 /* String */
64992                         ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
64993                         : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
64994                     error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
64995                 }
64996             }
64997         }
64998         function checkTypeNameIsReserved(name, message) {
64999             // TS 1.0 spec (April 2014): 3.6.1
65000             // The predefined type keywords are reserved and cannot be used as names of user defined types.
65001             switch (name.escapedText) {
65002                 case "any":
65003                 case "unknown":
65004                 case "number":
65005                 case "bigint":
65006                 case "boolean":
65007                 case "string":
65008                 case "symbol":
65009                 case "void":
65010                 case "object":
65011                     error(name, message, name.escapedText);
65012             }
65013         }
65014         /**
65015          * The name cannot be used as 'Object' of user defined types with special target.
65016          */
65017         function checkClassNameCollisionWithObject(name) {
65018             if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
65019                 && moduleKind < ts.ModuleKind.ES2015) {
65020                 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
65021             }
65022         }
65023         /**
65024          * Check each type parameter and check that type parameters have no duplicate type parameter declarations
65025          */
65026         function checkTypeParameters(typeParameterDeclarations) {
65027             if (typeParameterDeclarations) {
65028                 var seenDefault = false;
65029                 for (var i = 0; i < typeParameterDeclarations.length; i++) {
65030                     var node = typeParameterDeclarations[i];
65031                     checkTypeParameter(node);
65032                     if (produceDiagnostics) {
65033                         if (node.default) {
65034                             seenDefault = true;
65035                             checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
65036                         }
65037                         else if (seenDefault) {
65038                             error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
65039                         }
65040                         for (var j = 0; j < i; j++) {
65041                             if (typeParameterDeclarations[j].symbol === node.symbol) {
65042                                 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
65043                             }
65044                         }
65045                     }
65046                 }
65047             }
65048         }
65049         /** Check that type parameter defaults only reference previously declared type parameters */
65050         function checkTypeParametersNotReferenced(root, typeParameters, index) {
65051             visit(root);
65052             function visit(node) {
65053                 if (node.kind === 169 /* TypeReference */) {
65054                     var type = getTypeFromTypeReference(node);
65055                     if (type.flags & 262144 /* TypeParameter */) {
65056                         for (var i = index; i < typeParameters.length; i++) {
65057                             if (type.symbol === getSymbolOfNode(typeParameters[i])) {
65058                                 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
65059                             }
65060                         }
65061                     }
65062                 }
65063                 ts.forEachChild(node, visit);
65064             }
65065         }
65066         /** Check that type parameter lists are identical across multiple declarations */
65067         function checkTypeParameterListsIdentical(symbol) {
65068             if (symbol.declarations.length === 1) {
65069                 return;
65070             }
65071             var links = getSymbolLinks(symbol);
65072             if (!links.typeParametersChecked) {
65073                 links.typeParametersChecked = true;
65074                 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
65075                 if (declarations.length <= 1) {
65076                     return;
65077                 }
65078                 var type = getDeclaredTypeOfSymbol(symbol);
65079                 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
65080                     // Report an error on every conflicting declaration.
65081                     var name = symbolToString(symbol);
65082                     for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
65083                         var declaration = declarations_6[_i];
65084                         error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
65085                     }
65086                 }
65087             }
65088         }
65089         function areTypeParametersIdentical(declarations, targetParameters) {
65090             var maxTypeArgumentCount = ts.length(targetParameters);
65091             var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
65092             for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
65093                 var declaration = declarations_7[_i];
65094                 // If this declaration has too few or too many type parameters, we report an error
65095                 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
65096                 var numTypeParameters = sourceParameters.length;
65097                 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
65098                     return false;
65099                 }
65100                 for (var i = 0; i < numTypeParameters; i++) {
65101                     var source = sourceParameters[i];
65102                     var target = targetParameters[i];
65103                     // If the type parameter node does not have the same as the resolved type
65104                     // parameter at this position, we report an error.
65105                     if (source.name.escapedText !== target.symbol.escapedName) {
65106                         return false;
65107                     }
65108                     // If the type parameter node does not have an identical constraint as the resolved
65109                     // type parameter at this position, we report an error.
65110                     var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
65111                     var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
65112                     var targetConstraint = getConstraintOfTypeParameter(target);
65113                     // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
65114                     // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
65115                     if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
65116                         return false;
65117                     }
65118                     // If the type parameter node has a default and it is not identical to the default
65119                     // for the type parameter at this position, we report an error.
65120                     var sourceDefault = source.default && getTypeFromTypeNode(source.default);
65121                     var targetDefault = getDefaultFromTypeParameter(target);
65122                     if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
65123                         return false;
65124                     }
65125                 }
65126             }
65127             return true;
65128         }
65129         function checkClassExpression(node) {
65130             checkClassLikeDeclaration(node);
65131             checkNodeDeferred(node);
65132             return getTypeOfSymbol(getSymbolOfNode(node));
65133         }
65134         function checkClassExpressionDeferred(node) {
65135             ts.forEach(node.members, checkSourceElement);
65136             registerForUnusedIdentifiersCheck(node);
65137         }
65138         function checkClassDeclaration(node) {
65139             if (!node.name && !ts.hasModifier(node, 512 /* Default */)) {
65140                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
65141             }
65142             checkClassLikeDeclaration(node);
65143             ts.forEach(node.members, checkSourceElement);
65144             registerForUnusedIdentifiersCheck(node);
65145         }
65146         function checkClassLikeDeclaration(node) {
65147             checkGrammarClassLikeDeclaration(node);
65148             checkDecorators(node);
65149             if (node.name) {
65150                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
65151                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65152                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65153                 if (!(node.flags & 8388608 /* Ambient */)) {
65154                     checkClassNameCollisionWithObject(node.name);
65155                 }
65156             }
65157             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
65158             checkExportsOnMergedDeclarations(node);
65159             var symbol = getSymbolOfNode(node);
65160             var type = getDeclaredTypeOfSymbol(symbol);
65161             var typeWithThis = getTypeWithThisArgument(type);
65162             var staticType = getTypeOfSymbol(symbol);
65163             checkTypeParameterListsIdentical(symbol);
65164             checkClassForDuplicateDeclarations(node);
65165             // Only check for reserved static identifiers on non-ambient context.
65166             if (!(node.flags & 8388608 /* Ambient */)) {
65167                 checkClassForStaticPropertyNameConflicts(node);
65168             }
65169             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
65170             if (baseTypeNode) {
65171                 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65172                 if (languageVersion < 2 /* ES2015 */) {
65173                     checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
65174                 }
65175                 // check both @extends and extends if both are specified.
65176                 var extendsNode = ts.getClassExtendsHeritageElement(node);
65177                 if (extendsNode && extendsNode !== baseTypeNode) {
65178                     checkExpression(extendsNode.expression);
65179                 }
65180                 var baseTypes = getBaseTypes(type);
65181                 if (baseTypes.length && produceDiagnostics) {
65182                     var baseType_1 = baseTypes[0];
65183                     var baseConstructorType = getBaseConstructorTypeOfClass(type);
65184                     var staticBaseType = getApparentType(baseConstructorType);
65185                     checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
65186                     checkSourceElement(baseTypeNode.expression);
65187                     if (ts.some(baseTypeNode.typeArguments)) {
65188                         ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65189                         for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
65190                             var constructor = _a[_i];
65191                             if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
65192                                 break;
65193                             }
65194                         }
65195                     }
65196                     var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
65197                     if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65198                         issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
65199                     }
65200                     else {
65201                         // Report static side error only when instance type is assignable
65202                         checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
65203                     }
65204                     if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
65205                         error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
65206                     }
65207                     if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
65208                         // When the static base type is a "class-like" constructor function (but not actually a class), we verify
65209                         // that all instantiated base constructor signatures return the same type.
65210                         var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
65211                         if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
65212                             error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
65213                         }
65214                     }
65215                     checkKindsOfPropertyMemberOverrides(type, baseType_1);
65216                 }
65217             }
65218             var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node);
65219             if (implementedTypeNodes) {
65220                 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
65221                     var typeRefNode = implementedTypeNodes_1[_b];
65222                     if (!ts.isEntityNameExpression(typeRefNode.expression)) {
65223                         error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
65224                     }
65225                     checkTypeReferenceNode(typeRefNode);
65226                     if (produceDiagnostics) {
65227                         var t = getReducedType(getTypeFromTypeNode(typeRefNode));
65228                         if (t !== errorType) {
65229                             if (isValidBaseType(t)) {
65230                                 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
65231                                     ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
65232                                     ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
65233                                 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
65234                                 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65235                                     issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
65236                                 }
65237                             }
65238                             else {
65239                                 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
65240                             }
65241                         }
65242                     }
65243                 }
65244             }
65245             if (produceDiagnostics) {
65246                 checkIndexConstraints(type);
65247                 checkTypeForDuplicateIndexSignatures(node);
65248                 checkPropertyInitialization(node);
65249             }
65250         }
65251         function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
65252             // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
65253             var issuedMemberError = false;
65254             var _loop_19 = function (member) {
65255                 if (ts.hasStaticModifier(member)) {
65256                     return "continue";
65257                 }
65258                 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
65259                 if (declaredProp) {
65260                     var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
65261                     var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
65262                     if (prop && baseProp) {
65263                         var rootChain = function () { return ts.chainDiagnosticMessages(
65264                         /*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)); };
65265                         if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
65266                             issuedMemberError = true;
65267                         }
65268                     }
65269                 }
65270             };
65271             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65272                 var member = _a[_i];
65273                 _loop_19(member);
65274             }
65275             if (!issuedMemberError) {
65276                 // check again with diagnostics to generate a less-specific error
65277                 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
65278             }
65279         }
65280         function checkBaseTypeAccessibility(type, node) {
65281             var signatures = getSignaturesOfType(type, 1 /* Construct */);
65282             if (signatures.length) {
65283                 var declaration = signatures[0].declaration;
65284                 if (declaration && ts.hasModifier(declaration, 8 /* Private */)) {
65285                     var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65286                     if (!isNodeWithinClass(node, typeClassDeclaration)) {
65287                         error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
65288                     }
65289                 }
65290             }
65291         }
65292         function getTargetSymbol(s) {
65293             // if symbol is instantiated its flags are not copied from the 'target'
65294             // so we'll need to get back original 'target' symbol to work with correct set of flags
65295             return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
65296         }
65297         function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
65298             return ts.filter(symbol.declarations, function (d) {
65299                 return d.kind === 245 /* ClassDeclaration */ || d.kind === 246 /* InterfaceDeclaration */;
65300             });
65301         }
65302         function checkKindsOfPropertyMemberOverrides(type, baseType) {
65303             // TypeScript 1.0 spec (April 2014): 8.2.3
65304             // A derived class inherits all members from its base class it doesn't override.
65305             // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
65306             // Both public and private property members are inherited, but only public property members can be overridden.
65307             // A property member in a derived class is said to override a property member in a base class
65308             // when the derived class property member has the same name and kind(instance or static)
65309             // as the base class property member.
65310             // The type of an overriding property member must be assignable(section 3.8.4)
65311             // to the type of the overridden property member, or otherwise a compile - time error occurs.
65312             // Base class instance member functions can be overridden by derived class instance member functions,
65313             // but not by other kinds of members.
65314             // Base class instance member variables and accessors can be overridden by
65315             // derived class instance member variables and accessors, but not by other kinds of members.
65316             // NOTE: assignability is checked in checkClassDeclaration
65317             var baseProperties = getPropertiesOfType(baseType);
65318             basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
65319                 var baseProperty = baseProperties_1[_i];
65320                 var base = getTargetSymbol(baseProperty);
65321                 if (base.flags & 4194304 /* Prototype */) {
65322                     continue;
65323                 }
65324                 var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
65325                 if (!baseSymbol) {
65326                     continue;
65327                 }
65328                 var derived = getTargetSymbol(baseSymbol);
65329                 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
65330                 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
65331                 // In order to resolve whether the inherited method was overridden in the base class or not,
65332                 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
65333                 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
65334                 if (derived === base) {
65335                     // derived class inherits base without override/redeclaration
65336                     var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65337                     // It is an error to inherit an abstract member without implementing it or being declared abstract.
65338                     // If there is no declaration for the derived class (as in the case of class expressions),
65339                     // then the class cannot be declared abstract.
65340                     if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) {
65341                         // Searches other base types for a declaration that would satisfy the inherited abstract member.
65342                         // (The class may have more than one base type via declaration merging with an interface with the
65343                         // same name.)
65344                         for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) {
65345                             var otherBaseType = _b[_a];
65346                             if (otherBaseType === baseType)
65347                                 continue;
65348                             var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
65349                             var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
65350                             if (derivedElsewhere && derivedElsewhere !== base) {
65351                                 continue basePropertyCheck;
65352                             }
65353                         }
65354                         if (derivedClassDecl.kind === 214 /* ClassExpression */) {
65355                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
65356                         }
65357                         else {
65358                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
65359                         }
65360                     }
65361                 }
65362                 else {
65363                     // derived overrides base.
65364                     var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
65365                     if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
65366                         // either base or derived property is private - not override, skip it
65367                         continue;
65368                     }
65369                     var errorMessage = void 0;
65370                     var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
65371                     var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
65372                     if (basePropertyFlags && derivedPropertyFlags) {
65373                         // property/accessor is overridden with property/accessor
65374                         if (!compilerOptions.useDefineForClassFields
65375                             || baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
65376                             || base.valueDeclaration && base.valueDeclaration.parent.kind === 246 /* InterfaceDeclaration */
65377                             || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
65378                             // when the base property is abstract or from an interface, base/derived flags don't need to match
65379                             // same when the derived property is from an assignment
65380                             continue;
65381                         }
65382                         var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
65383                         var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
65384                         if (overriddenInstanceProperty || overriddenInstanceAccessor) {
65385                             var errorMessage_1 = overriddenInstanceProperty ?
65386                                 ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
65387                                 ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
65388                             error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
65389                         }
65390                         else {
65391                             var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 159 /* PropertyDeclaration */ && !d.initializer; });
65392                             if (uninitialized
65393                                 && !(derived.flags & 33554432 /* Transient */)
65394                                 && !(baseDeclarationFlags & 128 /* Abstract */)
65395                                 && !(derivedDeclarationFlags & 128 /* Abstract */)
65396                                 && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) {
65397                                 var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
65398                                 var propName = uninitialized.name;
65399                                 if (uninitialized.exclamationToken
65400                                     || !constructor
65401                                     || !ts.isIdentifier(propName)
65402                                     || !strictNullChecks
65403                                     || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65404                                     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;
65405                                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
65406                                 }
65407                             }
65408                         }
65409                         // correct case
65410                         continue;
65411                     }
65412                     else if (isPrototypeProperty(base)) {
65413                         if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
65414                             // method is overridden with method or property -- correct case
65415                             continue;
65416                         }
65417                         else {
65418                             ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
65419                             errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
65420                         }
65421                     }
65422                     else if (base.flags & 98304 /* Accessor */) {
65423                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
65424                     }
65425                     else {
65426                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
65427                     }
65428                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
65429                 }
65430             }
65431         }
65432         function getNonInterhitedProperties(type, baseTypes, properties) {
65433             if (!ts.length(baseTypes)) {
65434                 return properties;
65435             }
65436             var seen = ts.createUnderscoreEscapedMap();
65437             ts.forEach(properties, function (p) { seen.set(p.escapedName, p); });
65438             for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
65439                 var base = baseTypes_2[_i];
65440                 var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65441                 for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) {
65442                     var prop = properties_4[_a];
65443                     var existing = seen.get(prop.escapedName);
65444                     if (existing && !isPropertyIdenticalTo(existing, prop)) {
65445                         seen.delete(prop.escapedName);
65446                     }
65447                 }
65448             }
65449             return ts.arrayFrom(seen.values());
65450         }
65451         function checkInheritedPropertiesAreIdentical(type, typeNode) {
65452             var baseTypes = getBaseTypes(type);
65453             if (baseTypes.length < 2) {
65454                 return true;
65455             }
65456             var seen = ts.createUnderscoreEscapedMap();
65457             ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
65458             var ok = true;
65459             for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) {
65460                 var base = baseTypes_3[_i];
65461                 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65462                 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
65463                     var prop = properties_6[_a];
65464                     var existing = seen.get(prop.escapedName);
65465                     if (!existing) {
65466                         seen.set(prop.escapedName, { prop: prop, containingType: base });
65467                     }
65468                     else {
65469                         var isInheritedProperty = existing.containingType !== type;
65470                         if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
65471                             ok = false;
65472                             var typeName1 = typeToString(existing.containingType);
65473                             var typeName2 = typeToString(base);
65474                             var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
65475                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
65476                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
65477                         }
65478                     }
65479                 }
65480             }
65481             return ok;
65482         }
65483         function checkPropertyInitialization(node) {
65484             if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
65485                 return;
65486             }
65487             var constructor = findConstructorDeclaration(node);
65488             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65489                 var member = _a[_i];
65490                 if (ts.getModifierFlags(member) & 2 /* Ambient */) {
65491                     continue;
65492                 }
65493                 if (isInstancePropertyWithoutInitializer(member)) {
65494                     var propName = member.name;
65495                     if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
65496                         var type = getTypeOfSymbol(getSymbolOfNode(member));
65497                         if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
65498                             if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65499                                 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
65500                             }
65501                         }
65502                     }
65503                 }
65504             }
65505         }
65506         function isInstancePropertyWithoutInitializer(node) {
65507             return node.kind === 159 /* PropertyDeclaration */ &&
65508                 !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
65509                 !node.exclamationToken &&
65510                 !node.initializer;
65511         }
65512         function isPropertyInitializedInConstructor(propName, propType, constructor) {
65513             var reference = ts.createPropertyAccess(ts.createThis(), propName);
65514             reference.expression.parent = reference;
65515             reference.parent = constructor;
65516             reference.flowNode = constructor.returnFlowNode;
65517             var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
65518             return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
65519         }
65520         function checkInterfaceDeclaration(node) {
65521             // Grammar checking
65522             if (!checkGrammarDecoratorsAndModifiers(node))
65523                 checkGrammarInterfaceDeclaration(node);
65524             checkTypeParameters(node.typeParameters);
65525             if (produceDiagnostics) {
65526                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
65527                 checkExportsOnMergedDeclarations(node);
65528                 var symbol = getSymbolOfNode(node);
65529                 checkTypeParameterListsIdentical(symbol);
65530                 // Only check this symbol once
65531                 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
65532                 if (node === firstInterfaceDecl) {
65533                     var type = getDeclaredTypeOfSymbol(symbol);
65534                     var typeWithThis = getTypeWithThisArgument(type);
65535                     // run subsequent checks only if first set succeeded
65536                     if (checkInheritedPropertiesAreIdentical(type, node.name)) {
65537                         for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
65538                             var baseType = _a[_i];
65539                             checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
65540                         }
65541                         checkIndexConstraints(type);
65542                     }
65543                 }
65544                 checkObjectTypeForDuplicateDeclarations(node);
65545             }
65546             ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
65547                 if (!ts.isEntityNameExpression(heritageElement.expression)) {
65548                     error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
65549                 }
65550                 checkTypeReferenceNode(heritageElement);
65551             });
65552             ts.forEach(node.members, checkSourceElement);
65553             if (produceDiagnostics) {
65554                 checkTypeForDuplicateIndexSignatures(node);
65555                 registerForUnusedIdentifiersCheck(node);
65556             }
65557         }
65558         function checkTypeAliasDeclaration(node) {
65559             // Grammar checking
65560             checkGrammarDecoratorsAndModifiers(node);
65561             checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
65562             checkExportsOnMergedDeclarations(node);
65563             checkTypeParameters(node.typeParameters);
65564             checkSourceElement(node.type);
65565             registerForUnusedIdentifiersCheck(node);
65566         }
65567         function computeEnumMemberValues(node) {
65568             var nodeLinks = getNodeLinks(node);
65569             if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
65570                 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
65571                 var autoValue = 0;
65572                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65573                     var member = _a[_i];
65574                     var value = computeMemberValue(member, autoValue);
65575                     getNodeLinks(member).enumMemberValue = value;
65576                     autoValue = typeof value === "number" ? value + 1 : undefined;
65577                 }
65578             }
65579         }
65580         function computeMemberValue(member, autoValue) {
65581             if (ts.isComputedNonLiteralName(member.name)) {
65582                 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
65583             }
65584             else {
65585                 var text = ts.getTextOfPropertyName(member.name);
65586                 if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
65587                     error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
65588                 }
65589             }
65590             if (member.initializer) {
65591                 return computeConstantValue(member);
65592             }
65593             // In ambient non-const numeric enum declarations, enum members without initializers are
65594             // considered computed members (as opposed to having auto-incremented values).
65595             if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
65596                 return undefined;
65597             }
65598             // If the member declaration specifies no value, the member is considered a constant enum member.
65599             // If the member is the first member in the enum declaration, it is assigned the value zero.
65600             // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
65601             // occurs if the immediately preceding member is not a constant enum member.
65602             if (autoValue !== undefined) {
65603                 return autoValue;
65604             }
65605             error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
65606             return undefined;
65607         }
65608         function computeConstantValue(member) {
65609             var enumKind = getEnumKind(getSymbolOfNode(member.parent));
65610             var isConstEnum = ts.isEnumConst(member.parent);
65611             var initializer = member.initializer;
65612             var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
65613             if (value !== undefined) {
65614                 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
65615                     error(initializer, isNaN(value) ?
65616                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
65617                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
65618                 }
65619             }
65620             else if (enumKind === 1 /* Literal */) {
65621                 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
65622                 return 0;
65623             }
65624             else if (isConstEnum) {
65625                 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
65626             }
65627             else if (member.parent.flags & 8388608 /* Ambient */) {
65628                 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
65629             }
65630             else {
65631                 // Only here do we need to check that the initializer is assignable to the enum type.
65632                 var source = checkExpression(initializer);
65633                 if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) {
65634                     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));
65635                 }
65636                 else {
65637                     checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
65638                 }
65639             }
65640             return value;
65641             function evaluate(expr) {
65642                 switch (expr.kind) {
65643                     case 207 /* PrefixUnaryExpression */:
65644                         var value_2 = evaluate(expr.operand);
65645                         if (typeof value_2 === "number") {
65646                             switch (expr.operator) {
65647                                 case 39 /* PlusToken */: return value_2;
65648                                 case 40 /* MinusToken */: return -value_2;
65649                                 case 54 /* TildeToken */: return ~value_2;
65650                             }
65651                         }
65652                         break;
65653                     case 209 /* BinaryExpression */:
65654                         var left = evaluate(expr.left);
65655                         var right = evaluate(expr.right);
65656                         if (typeof left === "number" && typeof right === "number") {
65657                             switch (expr.operatorToken.kind) {
65658                                 case 51 /* BarToken */: return left | right;
65659                                 case 50 /* AmpersandToken */: return left & right;
65660                                 case 48 /* GreaterThanGreaterThanToken */: return left >> right;
65661                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
65662                                 case 47 /* LessThanLessThanToken */: return left << right;
65663                                 case 52 /* CaretToken */: return left ^ right;
65664                                 case 41 /* AsteriskToken */: return left * right;
65665                                 case 43 /* SlashToken */: return left / right;
65666                                 case 39 /* PlusToken */: return left + right;
65667                                 case 40 /* MinusToken */: return left - right;
65668                                 case 44 /* PercentToken */: return left % right;
65669                                 case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
65670                             }
65671                         }
65672                         else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
65673                             return left + right;
65674                         }
65675                         break;
65676                     case 10 /* StringLiteral */:
65677                     case 14 /* NoSubstitutionTemplateLiteral */:
65678                         return expr.text;
65679                     case 8 /* NumericLiteral */:
65680                         checkGrammarNumericLiteral(expr);
65681                         return +expr.text;
65682                     case 200 /* ParenthesizedExpression */:
65683                         return evaluate(expr.expression);
65684                     case 75 /* Identifier */:
65685                         var identifier = expr;
65686                         if (isInfinityOrNaNString(identifier.escapedText)) {
65687                             return +(identifier.escapedText);
65688                         }
65689                         return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
65690                     case 195 /* ElementAccessExpression */:
65691                     case 194 /* PropertyAccessExpression */:
65692                         var ex = expr;
65693                         if (isConstantMemberAccess(ex)) {
65694                             var type = getTypeOfExpression(ex.expression);
65695                             if (type.symbol && type.symbol.flags & 384 /* Enum */) {
65696                                 var name = void 0;
65697                                 if (ex.kind === 194 /* PropertyAccessExpression */) {
65698                                     name = ex.name.escapedText;
65699                                 }
65700                                 else {
65701                                     name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
65702                                 }
65703                                 return evaluateEnumMember(expr, type.symbol, name);
65704                             }
65705                         }
65706                         break;
65707                 }
65708                 return undefined;
65709             }
65710             function evaluateEnumMember(expr, enumSymbol, name) {
65711                 var memberSymbol = enumSymbol.exports.get(name);
65712                 if (memberSymbol) {
65713                     var declaration = memberSymbol.valueDeclaration;
65714                     if (declaration !== member) {
65715                         if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
65716                             return getEnumMemberValue(declaration);
65717                         }
65718                         error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
65719                         return 0;
65720                     }
65721                     else {
65722                         error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol));
65723                     }
65724                 }
65725                 return undefined;
65726             }
65727         }
65728         function isConstantMemberAccess(node) {
65729             return node.kind === 75 /* Identifier */ ||
65730                 node.kind === 194 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
65731                 node.kind === 195 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
65732                     ts.isStringLiteralLike(node.argumentExpression);
65733         }
65734         function checkEnumDeclaration(node) {
65735             if (!produceDiagnostics) {
65736                 return;
65737             }
65738             // Grammar checking
65739             checkGrammarDecoratorsAndModifiers(node);
65740             checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
65741             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65742             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65743             checkExportsOnMergedDeclarations(node);
65744             node.members.forEach(checkEnumMember);
65745             computeEnumMemberValues(node);
65746             // Spec 2014 - Section 9.3:
65747             // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
65748             // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
65749             // for the first member.
65750             //
65751             // Only perform this check once per symbol
65752             var enumSymbol = getSymbolOfNode(node);
65753             var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
65754             if (node === firstDeclaration) {
65755                 if (enumSymbol.declarations.length > 1) {
65756                     var enumIsConst_1 = ts.isEnumConst(node);
65757                     // check that const is placed\omitted on all enum declarations
65758                     ts.forEach(enumSymbol.declarations, function (decl) {
65759                         if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
65760                             error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
65761                         }
65762                     });
65763                 }
65764                 var seenEnumMissingInitialInitializer_1 = false;
65765                 ts.forEach(enumSymbol.declarations, function (declaration) {
65766                     // return true if we hit a violation of the rule, false otherwise
65767                     if (declaration.kind !== 248 /* EnumDeclaration */) {
65768                         return false;
65769                     }
65770                     var enumDeclaration = declaration;
65771                     if (!enumDeclaration.members.length) {
65772                         return false;
65773                     }
65774                     var firstEnumMember = enumDeclaration.members[0];
65775                     if (!firstEnumMember.initializer) {
65776                         if (seenEnumMissingInitialInitializer_1) {
65777                             error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
65778                         }
65779                         else {
65780                             seenEnumMissingInitialInitializer_1 = true;
65781                         }
65782                     }
65783                 });
65784             }
65785         }
65786         function checkEnumMember(node) {
65787             if (ts.isPrivateIdentifier(node.name)) {
65788                 error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
65789             }
65790         }
65791         function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
65792             var declarations = symbol.declarations;
65793             for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
65794                 var declaration = declarations_8[_i];
65795                 if ((declaration.kind === 245 /* ClassDeclaration */ ||
65796                     (declaration.kind === 244 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
65797                     !(declaration.flags & 8388608 /* Ambient */)) {
65798                     return declaration;
65799                 }
65800             }
65801             return undefined;
65802         }
65803         function inSameLexicalScope(node1, node2) {
65804             var container1 = ts.getEnclosingBlockScopeContainer(node1);
65805             var container2 = ts.getEnclosingBlockScopeContainer(node2);
65806             if (isGlobalSourceFile(container1)) {
65807                 return isGlobalSourceFile(container2);
65808             }
65809             else if (isGlobalSourceFile(container2)) {
65810                 return false;
65811             }
65812             else {
65813                 return container1 === container2;
65814             }
65815         }
65816         function checkModuleDeclaration(node) {
65817             if (produceDiagnostics) {
65818                 // Grammar checking
65819                 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
65820                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
65821                 if (isGlobalAugmentation && !inAmbientContext) {
65822                     error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
65823                 }
65824                 var isAmbientExternalModule = ts.isAmbientModule(node);
65825                 var contextErrorMessage = isAmbientExternalModule
65826                     ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
65827                     : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
65828                 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
65829                     // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
65830                     return;
65831                 }
65832                 if (!checkGrammarDecoratorsAndModifiers(node)) {
65833                     if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
65834                         grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
65835                     }
65836                 }
65837                 if (ts.isIdentifier(node.name)) {
65838                     checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65839                     checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65840                 }
65841                 checkExportsOnMergedDeclarations(node);
65842                 var symbol = getSymbolOfNode(node);
65843                 // The following checks only apply on a non-ambient instantiated module declaration.
65844                 if (symbol.flags & 512 /* ValueModule */
65845                     && !inAmbientContext
65846                     && symbol.declarations.length > 1
65847                     && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
65848                     var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
65849                     if (firstNonAmbientClassOrFunc) {
65850                         if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
65851                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
65852                         }
65853                         else if (node.pos < firstNonAmbientClassOrFunc.pos) {
65854                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
65855                         }
65856                     }
65857                     // if the module merges with a class declaration in the same lexical scope,
65858                     // we need to track this to ensure the correct emit.
65859                     var mergedClass = ts.getDeclarationOfKind(symbol, 245 /* ClassDeclaration */);
65860                     if (mergedClass &&
65861                         inSameLexicalScope(node, mergedClass)) {
65862                         getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
65863                     }
65864                 }
65865                 if (isAmbientExternalModule) {
65866                     if (ts.isExternalModuleAugmentation(node)) {
65867                         // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
65868                         // otherwise we'll be swamped in cascading errors.
65869                         // We can detect if augmentation was applied using following rules:
65870                         // - augmentation for a global scope is always applied
65871                         // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
65872                         var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
65873                         if (checkBody && node.body) {
65874                             for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
65875                                 var statement = _a[_i];
65876                                 checkModuleAugmentationElement(statement, isGlobalAugmentation);
65877                             }
65878                         }
65879                     }
65880                     else if (isGlobalSourceFile(node.parent)) {
65881                         if (isGlobalAugmentation) {
65882                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
65883                         }
65884                         else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
65885                             error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
65886                         }
65887                     }
65888                     else {
65889                         if (isGlobalAugmentation) {
65890                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
65891                         }
65892                         else {
65893                             // Node is not an augmentation and is not located on the script level.
65894                             // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
65895                             error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
65896                         }
65897                     }
65898                 }
65899             }
65900             if (node.body) {
65901                 checkSourceElement(node.body);
65902                 if (!ts.isGlobalScopeAugmentation(node)) {
65903                     registerForUnusedIdentifiersCheck(node);
65904                 }
65905             }
65906         }
65907         function checkModuleAugmentationElement(node, isGlobalAugmentation) {
65908             switch (node.kind) {
65909                 case 225 /* VariableStatement */:
65910                     // error each individual name in variable statement instead of marking the entire variable statement
65911                     for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
65912                         var decl = _a[_i];
65913                         checkModuleAugmentationElement(decl, isGlobalAugmentation);
65914                     }
65915                     break;
65916                 case 259 /* ExportAssignment */:
65917                 case 260 /* ExportDeclaration */:
65918                     grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
65919                     break;
65920                 case 253 /* ImportEqualsDeclaration */:
65921                 case 254 /* ImportDeclaration */:
65922                     grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
65923                     break;
65924                 case 191 /* BindingElement */:
65925                 case 242 /* VariableDeclaration */:
65926                     var name = node.name;
65927                     if (ts.isBindingPattern(name)) {
65928                         for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
65929                             var el = _c[_b];
65930                             // mark individual names in binding pattern
65931                             checkModuleAugmentationElement(el, isGlobalAugmentation);
65932                         }
65933                         break;
65934                     }
65935                 // falls through
65936                 case 245 /* ClassDeclaration */:
65937                 case 248 /* EnumDeclaration */:
65938                 case 244 /* FunctionDeclaration */:
65939                 case 246 /* InterfaceDeclaration */:
65940                 case 249 /* ModuleDeclaration */:
65941                 case 247 /* TypeAliasDeclaration */:
65942                     if (isGlobalAugmentation) {
65943                         return;
65944                     }
65945                     var symbol = getSymbolOfNode(node);
65946                     if (symbol) {
65947                         // module augmentations cannot introduce new names on the top level scope of the module
65948                         // this is done it two steps
65949                         // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
65950                         // 2. main check - report error if value declaration of the parent symbol is module augmentation)
65951                         var reportError = !(symbol.flags & 33554432 /* Transient */);
65952                         if (!reportError) {
65953                             // symbol should not originate in augmentation
65954                             reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
65955                         }
65956                     }
65957                     break;
65958             }
65959         }
65960         function getFirstNonModuleExportsIdentifier(node) {
65961             switch (node.kind) {
65962                 case 75 /* Identifier */:
65963                     return node;
65964                 case 153 /* QualifiedName */:
65965                     do {
65966                         node = node.left;
65967                     } while (node.kind !== 75 /* Identifier */);
65968                     return node;
65969                 case 194 /* PropertyAccessExpression */:
65970                     do {
65971                         if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
65972                             return node.name;
65973                         }
65974                         node = node.expression;
65975                     } while (node.kind !== 75 /* Identifier */);
65976                     return node;
65977             }
65978         }
65979         function checkExternalImportOrExportDeclaration(node) {
65980             var moduleName = ts.getExternalModuleName(node);
65981             if (!moduleName || ts.nodeIsMissing(moduleName)) {
65982                 // Should be a parse error.
65983                 return false;
65984             }
65985             if (!ts.isStringLiteral(moduleName)) {
65986                 error(moduleName, ts.Diagnostics.String_literal_expected);
65987                 return false;
65988             }
65989             var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
65990             if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule) {
65991                 error(moduleName, node.kind === 260 /* ExportDeclaration */ ?
65992                     ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
65993                     ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
65994                 return false;
65995             }
65996             if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
65997                 // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration
65998                 // no need to do this again.
65999                 if (!isTopLevelInExternalModuleAugmentation(node)) {
66000                     // TypeScript 1.0 spec (April 2013): 12.1.6
66001                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
66002                     // other external modules only through top - level external module names.
66003                     // Relative external module names are not permitted.
66004                     error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
66005                     return false;
66006                 }
66007             }
66008             return true;
66009         }
66010         function checkAliasSymbol(node) {
66011             var symbol = getSymbolOfNode(node);
66012             var target = resolveAlias(symbol);
66013             var shouldSkipWithJSExpandoTargets = symbol.flags & 67108864 /* Assignment */;
66014             if (!shouldSkipWithJSExpandoTargets && target !== unknownSymbol) {
66015                 // For external modules symbol represents local symbol for an alias.
66016                 // This local symbol will merge any other local declarations (excluding other aliases)
66017                 // and symbol.flags will contains combined representation for all merged declaration.
66018                 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
66019                 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
66020                 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
66021                 symbol = getMergedSymbol(symbol.exportSymbol || symbol);
66022                 var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
66023                     (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
66024                     (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
66025                 if (target.flags & excludedMeanings) {
66026                     var message = node.kind === 263 /* ExportSpecifier */ ?
66027                         ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
66028                         ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
66029                     error(node, message, symbolToString(symbol));
66030                 }
66031                 // Don't allow to re-export something with no value side when `--isolatedModules` is set.
66032                 if (compilerOptions.isolatedModules
66033                     && node.kind === 263 /* ExportSpecifier */
66034                     && !node.parent.parent.isTypeOnly
66035                     && !(target.flags & 111551 /* Value */)
66036                     && !(node.flags & 8388608 /* Ambient */)) {
66037                     error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
66038                 }
66039             }
66040         }
66041         function checkImportBinding(node) {
66042             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
66043             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
66044             checkAliasSymbol(node);
66045         }
66046         function checkImportDeclaration(node) {
66047             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66048                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66049                 return;
66050             }
66051             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66052                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
66053             }
66054             if (checkExternalImportOrExportDeclaration(node)) {
66055                 var importClause = node.importClause;
66056                 if (importClause && !checkGrammarImportClause(importClause)) {
66057                     if (importClause.name) {
66058                         checkImportBinding(importClause);
66059                     }
66060                     if (importClause.namedBindings) {
66061                         if (importClause.namedBindings.kind === 256 /* NamespaceImport */) {
66062                             checkImportBinding(importClause.namedBindings);
66063                         }
66064                         else {
66065                             var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
66066                             if (moduleExisted) {
66067                                 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
66068                             }
66069                         }
66070                     }
66071                 }
66072             }
66073         }
66074         function checkImportEqualsDeclaration(node) {
66075             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66076                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66077                 return;
66078             }
66079             checkGrammarDecoratorsAndModifiers(node);
66080             if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
66081                 checkImportBinding(node);
66082                 if (ts.hasModifier(node, 1 /* Export */)) {
66083                     markExportAsReferenced(node);
66084                 }
66085                 if (node.moduleReference.kind !== 265 /* ExternalModuleReference */) {
66086                     var target = resolveAlias(getSymbolOfNode(node));
66087                     if (target !== unknownSymbol) {
66088                         if (target.flags & 111551 /* Value */) {
66089                             // Target is a value symbol, check that it is not hidden by a local declaration with the same name
66090                             var moduleName = ts.getFirstIdentifier(node.moduleReference);
66091                             if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
66092                                 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
66093                             }
66094                         }
66095                         if (target.flags & 788968 /* Type */) {
66096                             checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
66097                         }
66098                     }
66099                 }
66100                 else {
66101                     if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 8388608 /* Ambient */)) {
66102                         // Import equals declaration is deprecated in es6 or above
66103                         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);
66104                     }
66105                 }
66106             }
66107         }
66108         function checkExportDeclaration(node) {
66109             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
66110                 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
66111                 return;
66112             }
66113             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66114                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
66115             }
66116             if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
66117                 checkExternalEmitHelpers(node, 1048576 /* CreateBinding */);
66118             }
66119             checkGrammarExportDeclaration(node);
66120             if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
66121                 if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) {
66122                     // export { x, y }
66123                     // export { x, y } from "foo"
66124                     ts.forEach(node.exportClause.elements, checkExportSpecifier);
66125                     var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
66126                     var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ &&
66127                         !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
66128                     if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
66129                         error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
66130                     }
66131                 }
66132                 else {
66133                     // export * from "foo"
66134                     var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
66135                     if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
66136                         error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
66137                     }
66138                     else if (node.exportClause) {
66139                         checkAliasSymbol(node.exportClause);
66140                     }
66141                     if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
66142                         checkExternalEmitHelpers(node, 65536 /* ExportStar */);
66143                     }
66144                 }
66145             }
66146         }
66147         function checkGrammarExportDeclaration(node) {
66148             var _a;
66149             var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 261 /* NamedExports */;
66150             if (isTypeOnlyExportStar) {
66151                 grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
66152             }
66153             return !isTypeOnlyExportStar;
66154         }
66155         function checkGrammarModuleElementContext(node, errorMessage) {
66156             var isInAppropriateContext = node.parent.kind === 290 /* SourceFile */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 249 /* ModuleDeclaration */;
66157             if (!isInAppropriateContext) {
66158                 grammarErrorOnFirstToken(node, errorMessage);
66159             }
66160             return !isInAppropriateContext;
66161         }
66162         function importClauseContainsReferencedImport(importClause) {
66163             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66164                 return !!getSymbolOfNode(declaration).isReferenced;
66165             });
66166         }
66167         function importClauseContainsConstEnumUsedAsValue(importClause) {
66168             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66169                 return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
66170             });
66171         }
66172         function checkImportsForTypeOnlyConversion(sourceFile) {
66173             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
66174                 var statement = _a[_i];
66175                 if (ts.isImportDeclaration(statement) &&
66176                     statement.importClause &&
66177                     !statement.importClause.isTypeOnly &&
66178                     importClauseContainsReferencedImport(statement.importClause) &&
66179                     !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
66180                     !importClauseContainsConstEnumUsedAsValue(statement.importClause)) {
66181                     error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error);
66182                 }
66183             }
66184         }
66185         function checkExportSpecifier(node) {
66186             checkAliasSymbol(node);
66187             if (ts.getEmitDeclarations(compilerOptions)) {
66188                 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
66189             }
66190             if (!node.parent.parent.moduleSpecifier) {
66191                 var exportedName = node.propertyName || node.name;
66192                 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
66193                 var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, 
66194                 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
66195                 if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
66196                     error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
66197                 }
66198                 else {
66199                     markExportAsReferenced(node);
66200                     var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
66201                     if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
66202                         checkExpressionCached(node.propertyName || node.name);
66203                     }
66204                 }
66205             }
66206         }
66207         function checkExportAssignment(node) {
66208             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
66209                 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
66210                 return;
66211             }
66212             var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
66213             if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
66214                 if (node.isExportEquals) {
66215                     error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
66216                 }
66217                 else {
66218                     error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
66219                 }
66220                 return;
66221             }
66222             // Grammar checking
66223             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66224                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
66225             }
66226             if (node.expression.kind === 75 /* Identifier */) {
66227                 var id = node.expression;
66228                 var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
66229                 if (sym) {
66230                     markAliasReferenced(sym, id);
66231                     // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
66232                     var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
66233                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
66234                         // However if it is a value, we need to check it's being used correctly
66235                         checkExpressionCached(node.expression);
66236                     }
66237                 }
66238                 if (ts.getEmitDeclarations(compilerOptions)) {
66239                     collectLinkedAliases(node.expression, /*setVisibility*/ true);
66240                 }
66241             }
66242             else {
66243                 checkExpressionCached(node.expression);
66244             }
66245             checkExternalModuleExports(container);
66246             if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
66247                 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
66248             }
66249             if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
66250                 if (moduleKind >= ts.ModuleKind.ES2015) {
66251                     // export assignment is not supported in es6 modules
66252                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
66253                 }
66254                 else if (moduleKind === ts.ModuleKind.System) {
66255                     // system modules does not support export assignment
66256                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
66257                 }
66258             }
66259         }
66260         function hasExportedMembers(moduleSymbol) {
66261             return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
66262         }
66263         function checkExternalModuleExports(node) {
66264             var moduleSymbol = getSymbolOfNode(node);
66265             var links = getSymbolLinks(moduleSymbol);
66266             if (!links.exportsChecked) {
66267                 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
66268                 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
66269                     var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
66270                     if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
66271                         error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
66272                     }
66273                 }
66274                 // Checks for export * conflicts
66275                 var exports_2 = getExportsOfModule(moduleSymbol);
66276                 if (exports_2) {
66277                     exports_2.forEach(function (_a, id) {
66278                         var declarations = _a.declarations, flags = _a.flags;
66279                         if (id === "__export") {
66280                             return;
66281                         }
66282                         // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
66283                         // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
66284                         if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
66285                             return;
66286                         }
66287                         var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
66288                         if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
66289                             // it is legal to merge type alias with other values
66290                             // so count should be either 1 (just type alias) or 2 (type alias + merged value)
66291                             return;
66292                         }
66293                         if (exportedDeclarationsCount > 1) {
66294                             for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
66295                                 var declaration = declarations_9[_i];
66296                                 if (isNotOverload(declaration)) {
66297                                     diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
66298                                 }
66299                             }
66300                         }
66301                     });
66302                 }
66303                 links.exportsChecked = true;
66304             }
66305         }
66306         function checkSourceElement(node) {
66307             if (node) {
66308                 var saveCurrentNode = currentNode;
66309                 currentNode = node;
66310                 instantiationCount = 0;
66311                 checkSourceElementWorker(node);
66312                 currentNode = saveCurrentNode;
66313             }
66314         }
66315         function checkSourceElementWorker(node) {
66316             if (ts.isInJSFile(node)) {
66317                 ts.forEach(node.jsDoc, function (_a) {
66318                     var tags = _a.tags;
66319                     return ts.forEach(tags, checkSourceElement);
66320                 });
66321             }
66322             var kind = node.kind;
66323             if (cancellationToken) {
66324                 // Only bother checking on a few construct kinds.  We don't want to be excessively
66325                 // hitting the cancellation token on every node we check.
66326                 switch (kind) {
66327                     case 249 /* ModuleDeclaration */:
66328                     case 245 /* ClassDeclaration */:
66329                     case 246 /* InterfaceDeclaration */:
66330                     case 244 /* FunctionDeclaration */:
66331                         cancellationToken.throwIfCancellationRequested();
66332                 }
66333             }
66334             if (kind >= 225 /* FirstStatement */ && kind <= 241 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
66335                 errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
66336             }
66337             switch (kind) {
66338                 case 155 /* TypeParameter */:
66339                     return checkTypeParameter(node);
66340                 case 156 /* Parameter */:
66341                     return checkParameter(node);
66342                 case 159 /* PropertyDeclaration */:
66343                     return checkPropertyDeclaration(node);
66344                 case 158 /* PropertySignature */:
66345                     return checkPropertySignature(node);
66346                 case 170 /* FunctionType */:
66347                 case 171 /* ConstructorType */:
66348                 case 165 /* CallSignature */:
66349                 case 166 /* ConstructSignature */:
66350                 case 167 /* IndexSignature */:
66351                     return checkSignatureDeclaration(node);
66352                 case 161 /* MethodDeclaration */:
66353                 case 160 /* MethodSignature */:
66354                     return checkMethodDeclaration(node);
66355                 case 162 /* Constructor */:
66356                     return checkConstructorDeclaration(node);
66357                 case 163 /* GetAccessor */:
66358                 case 164 /* SetAccessor */:
66359                     return checkAccessorDeclaration(node);
66360                 case 169 /* TypeReference */:
66361                     return checkTypeReferenceNode(node);
66362                 case 168 /* TypePredicate */:
66363                     return checkTypePredicate(node);
66364                 case 172 /* TypeQuery */:
66365                     return checkTypeQuery(node);
66366                 case 173 /* TypeLiteral */:
66367                     return checkTypeLiteral(node);
66368                 case 174 /* ArrayType */:
66369                     return checkArrayType(node);
66370                 case 175 /* TupleType */:
66371                     return checkTupleType(node);
66372                 case 178 /* UnionType */:
66373                 case 179 /* IntersectionType */:
66374                     return checkUnionOrIntersectionType(node);
66375                 case 182 /* ParenthesizedType */:
66376                 case 176 /* OptionalType */:
66377                 case 177 /* RestType */:
66378                     return checkSourceElement(node.type);
66379                 case 183 /* ThisType */:
66380                     return checkThisType(node);
66381                 case 184 /* TypeOperator */:
66382                     return checkTypeOperator(node);
66383                 case 180 /* ConditionalType */:
66384                     return checkConditionalType(node);
66385                 case 181 /* InferType */:
66386                     return checkInferType(node);
66387                 case 188 /* ImportType */:
66388                     return checkImportType(node);
66389                 case 307 /* JSDocAugmentsTag */:
66390                     return checkJSDocAugmentsTag(node);
66391                 case 308 /* JSDocImplementsTag */:
66392                     return checkJSDocImplementsTag(node);
66393                 case 322 /* JSDocTypedefTag */:
66394                 case 315 /* JSDocCallbackTag */:
66395                 case 316 /* JSDocEnumTag */:
66396                     return checkJSDocTypeAliasTag(node);
66397                 case 321 /* JSDocTemplateTag */:
66398                     return checkJSDocTemplateTag(node);
66399                 case 320 /* JSDocTypeTag */:
66400                     return checkJSDocTypeTag(node);
66401                 case 317 /* JSDocParameterTag */:
66402                     return checkJSDocParameterTag(node);
66403                 case 323 /* JSDocPropertyTag */:
66404                     return checkJSDocPropertyTag(node);
66405                 case 300 /* JSDocFunctionType */:
66406                     checkJSDocFunctionType(node);
66407                 // falls through
66408                 case 298 /* JSDocNonNullableType */:
66409                 case 297 /* JSDocNullableType */:
66410                 case 295 /* JSDocAllType */:
66411                 case 296 /* JSDocUnknownType */:
66412                 case 304 /* JSDocTypeLiteral */:
66413                     checkJSDocTypeIsInJsFile(node);
66414                     ts.forEachChild(node, checkSourceElement);
66415                     return;
66416                 case 301 /* JSDocVariadicType */:
66417                     checkJSDocVariadicType(node);
66418                     return;
66419                 case 294 /* JSDocTypeExpression */:
66420                     return checkSourceElement(node.type);
66421                 case 185 /* IndexedAccessType */:
66422                     return checkIndexedAccessType(node);
66423                 case 186 /* MappedType */:
66424                     return checkMappedType(node);
66425                 case 244 /* FunctionDeclaration */:
66426                     return checkFunctionDeclaration(node);
66427                 case 223 /* Block */:
66428                 case 250 /* ModuleBlock */:
66429                     return checkBlock(node);
66430                 case 225 /* VariableStatement */:
66431                     return checkVariableStatement(node);
66432                 case 226 /* ExpressionStatement */:
66433                     return checkExpressionStatement(node);
66434                 case 227 /* IfStatement */:
66435                     return checkIfStatement(node);
66436                 case 228 /* DoStatement */:
66437                     return checkDoStatement(node);
66438                 case 229 /* WhileStatement */:
66439                     return checkWhileStatement(node);
66440                 case 230 /* ForStatement */:
66441                     return checkForStatement(node);
66442                 case 231 /* ForInStatement */:
66443                     return checkForInStatement(node);
66444                 case 232 /* ForOfStatement */:
66445                     return checkForOfStatement(node);
66446                 case 233 /* ContinueStatement */:
66447                 case 234 /* BreakStatement */:
66448                     return checkBreakOrContinueStatement(node);
66449                 case 235 /* ReturnStatement */:
66450                     return checkReturnStatement(node);
66451                 case 236 /* WithStatement */:
66452                     return checkWithStatement(node);
66453                 case 237 /* SwitchStatement */:
66454                     return checkSwitchStatement(node);
66455                 case 238 /* LabeledStatement */:
66456                     return checkLabeledStatement(node);
66457                 case 239 /* ThrowStatement */:
66458                     return checkThrowStatement(node);
66459                 case 240 /* TryStatement */:
66460                     return checkTryStatement(node);
66461                 case 242 /* VariableDeclaration */:
66462                     return checkVariableDeclaration(node);
66463                 case 191 /* BindingElement */:
66464                     return checkBindingElement(node);
66465                 case 245 /* ClassDeclaration */:
66466                     return checkClassDeclaration(node);
66467                 case 246 /* InterfaceDeclaration */:
66468                     return checkInterfaceDeclaration(node);
66469                 case 247 /* TypeAliasDeclaration */:
66470                     return checkTypeAliasDeclaration(node);
66471                 case 248 /* EnumDeclaration */:
66472                     return checkEnumDeclaration(node);
66473                 case 249 /* ModuleDeclaration */:
66474                     return checkModuleDeclaration(node);
66475                 case 254 /* ImportDeclaration */:
66476                     return checkImportDeclaration(node);
66477                 case 253 /* ImportEqualsDeclaration */:
66478                     return checkImportEqualsDeclaration(node);
66479                 case 260 /* ExportDeclaration */:
66480                     return checkExportDeclaration(node);
66481                 case 259 /* ExportAssignment */:
66482                     return checkExportAssignment(node);
66483                 case 224 /* EmptyStatement */:
66484                 case 241 /* DebuggerStatement */:
66485                     checkGrammarStatementInAmbientContext(node);
66486                     return;
66487                 case 264 /* MissingDeclaration */:
66488                     return checkMissingDeclaration(node);
66489             }
66490         }
66491         function checkJSDocTypeIsInJsFile(node) {
66492             if (!ts.isInJSFile(node)) {
66493                 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
66494             }
66495         }
66496         function checkJSDocVariadicType(node) {
66497             checkJSDocTypeIsInJsFile(node);
66498             checkSourceElement(node.type);
66499             // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
66500             var parent = node.parent;
66501             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66502                 if (ts.last(parent.parent.parameters) !== parent) {
66503                     error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66504                 }
66505                 return;
66506             }
66507             if (!ts.isJSDocTypeExpression(parent)) {
66508                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66509             }
66510             var paramTag = node.parent.parent;
66511             if (!ts.isJSDocParameterTag(paramTag)) {
66512                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66513                 return;
66514             }
66515             var param = ts.getParameterSymbolFromJSDoc(paramTag);
66516             if (!param) {
66517                 // We will error in `checkJSDocParameterTag`.
66518                 return;
66519             }
66520             var host = ts.getHostSignatureFromJSDoc(paramTag);
66521             if (!host || ts.last(host.parameters).symbol !== param) {
66522                 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66523             }
66524         }
66525         function getTypeFromJSDocVariadicType(node) {
66526             var type = getTypeFromTypeNode(node.type);
66527             var parent = node.parent;
66528             var paramTag = node.parent.parent;
66529             if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
66530                 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
66531                 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
66532                 if (host_1) {
66533                     /*
66534                     Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
66535                     So in the following situation we will not create an array type:
66536                         /** @param {...number} a * /
66537                         function f(a) {}
66538                     Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
66539                     */
66540                     var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
66541                     var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
66542                     if (!lastParamDeclaration ||
66543                         symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
66544                         return createArrayType(type);
66545                     }
66546                 }
66547             }
66548             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66549                 return createArrayType(type);
66550             }
66551             return addOptionality(type);
66552         }
66553         // Function and class expression bodies are checked after all statements in the enclosing body. This is
66554         // to ensure constructs like the following are permitted:
66555         //     const foo = function () {
66556         //        const s = foo();
66557         //        return "hello";
66558         //     }
66559         // Here, performing a full type check of the body of the function expression whilst in the process of
66560         // determining the type of foo would cause foo to be given type any because of the recursive reference.
66561         // Delaying the type check of the body ensures foo has been assigned a type.
66562         function checkNodeDeferred(node) {
66563             var enclosingFile = ts.getSourceFileOfNode(node);
66564             var links = getNodeLinks(enclosingFile);
66565             if (!(links.flags & 1 /* TypeChecked */)) {
66566                 links.deferredNodes = links.deferredNodes || ts.createMap();
66567                 var id = "" + getNodeId(node);
66568                 links.deferredNodes.set(id, node);
66569             }
66570         }
66571         function checkDeferredNodes(context) {
66572             var links = getNodeLinks(context);
66573             if (links.deferredNodes) {
66574                 links.deferredNodes.forEach(checkDeferredNode);
66575             }
66576         }
66577         function checkDeferredNode(node) {
66578             var saveCurrentNode = currentNode;
66579             currentNode = node;
66580             instantiationCount = 0;
66581             switch (node.kind) {
66582                 case 196 /* CallExpression */:
66583                 case 197 /* NewExpression */:
66584                 case 198 /* TaggedTemplateExpression */:
66585                 case 157 /* Decorator */:
66586                 case 268 /* JsxOpeningElement */:
66587                     // These node kinds are deferred checked when overload resolution fails
66588                     // To save on work, we ensure the arguments are checked just once, in
66589                     // a deferred way
66590                     resolveUntypedCall(node);
66591                     break;
66592                 case 201 /* FunctionExpression */:
66593                 case 202 /* ArrowFunction */:
66594                 case 161 /* MethodDeclaration */:
66595                 case 160 /* MethodSignature */:
66596                     checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
66597                     break;
66598                 case 163 /* GetAccessor */:
66599                 case 164 /* SetAccessor */:
66600                     checkAccessorDeclaration(node);
66601                     break;
66602                 case 214 /* ClassExpression */:
66603                     checkClassExpressionDeferred(node);
66604                     break;
66605                 case 267 /* JsxSelfClosingElement */:
66606                     checkJsxSelfClosingElementDeferred(node);
66607                     break;
66608                 case 266 /* JsxElement */:
66609                     checkJsxElementDeferred(node);
66610                     break;
66611             }
66612             currentNode = saveCurrentNode;
66613         }
66614         function checkSourceFile(node) {
66615             ts.performance.mark("beforeCheck");
66616             checkSourceFileWorker(node);
66617             ts.performance.mark("afterCheck");
66618             ts.performance.measure("Check", "beforeCheck", "afterCheck");
66619         }
66620         function unusedIsError(kind, isAmbient) {
66621             if (isAmbient) {
66622                 return false;
66623             }
66624             switch (kind) {
66625                 case 0 /* Local */:
66626                     return !!compilerOptions.noUnusedLocals;
66627                 case 1 /* Parameter */:
66628                     return !!compilerOptions.noUnusedParameters;
66629                 default:
66630                     return ts.Debug.assertNever(kind);
66631             }
66632         }
66633         function getPotentiallyUnusedIdentifiers(sourceFile) {
66634             return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
66635         }
66636         // Fully type check a source file and collect the relevant diagnostics.
66637         function checkSourceFileWorker(node) {
66638             var links = getNodeLinks(node);
66639             if (!(links.flags & 1 /* TypeChecked */)) {
66640                 if (ts.skipTypeChecking(node, compilerOptions, host)) {
66641                     return;
66642                 }
66643                 // Grammar checking
66644                 checkGrammarSourceFile(node);
66645                 ts.clear(potentialThisCollisions);
66646                 ts.clear(potentialNewTargetCollisions);
66647                 ts.clear(potentialWeakMapCollisions);
66648                 ts.forEach(node.statements, checkSourceElement);
66649                 checkSourceElement(node.endOfFileToken);
66650                 checkDeferredNodes(node);
66651                 if (ts.isExternalOrCommonJsModule(node)) {
66652                     registerForUnusedIdentifiersCheck(node);
66653                 }
66654                 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
66655                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
66656                         if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
66657                             diagnostics.add(diag);
66658                         }
66659                     });
66660                 }
66661                 if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
66662                     !node.isDeclarationFile &&
66663                     ts.isExternalModule(node)) {
66664                     checkImportsForTypeOnlyConversion(node);
66665                 }
66666                 if (ts.isExternalOrCommonJsModule(node)) {
66667                     checkExternalModuleExports(node);
66668                 }
66669                 if (potentialThisCollisions.length) {
66670                     ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
66671                     ts.clear(potentialThisCollisions);
66672                 }
66673                 if (potentialNewTargetCollisions.length) {
66674                     ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
66675                     ts.clear(potentialNewTargetCollisions);
66676                 }
66677                 if (potentialWeakMapCollisions.length) {
66678                     ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision);
66679                     ts.clear(potentialWeakMapCollisions);
66680                 }
66681                 links.flags |= 1 /* TypeChecked */;
66682             }
66683         }
66684         function getDiagnostics(sourceFile, ct) {
66685             try {
66686                 // Record the cancellation token so it can be checked later on during checkSourceElement.
66687                 // Do this in a finally block so we can ensure that it gets reset back to nothing after
66688                 // this call is done.
66689                 cancellationToken = ct;
66690                 return getDiagnosticsWorker(sourceFile);
66691             }
66692             finally {
66693                 cancellationToken = undefined;
66694             }
66695         }
66696         function getDiagnosticsWorker(sourceFile) {
66697             throwIfNonDiagnosticsProducing();
66698             if (sourceFile) {
66699                 // Some global diagnostics are deferred until they are needed and
66700                 // may not be reported in the first call to getGlobalDiagnostics.
66701                 // We should catch these changes and report them.
66702                 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66703                 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
66704                 checkSourceFile(sourceFile);
66705                 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
66706                 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66707                 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
66708                     // If the arrays are not the same reference, new diagnostics were added.
66709                     var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
66710                     return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
66711                 }
66712                 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
66713                     // If the arrays are the same reference, but the length has changed, a single
66714                     // new diagnostic was added as DiagnosticCollection attempts to reuse the
66715                     // same array.
66716                     return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
66717                 }
66718                 return semanticDiagnostics;
66719             }
66720             // Global diagnostics are always added when a file is not provided to
66721             // getDiagnostics
66722             ts.forEach(host.getSourceFiles(), checkSourceFile);
66723             return diagnostics.getDiagnostics();
66724         }
66725         function getGlobalDiagnostics() {
66726             throwIfNonDiagnosticsProducing();
66727             return diagnostics.getGlobalDiagnostics();
66728         }
66729         function throwIfNonDiagnosticsProducing() {
66730             if (!produceDiagnostics) {
66731                 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
66732             }
66733         }
66734         // Language service support
66735         function getSymbolsInScope(location, meaning) {
66736             if (location.flags & 16777216 /* InWithStatement */) {
66737                 // We cannot answer semantic questions within a with block, do not proceed any further
66738                 return [];
66739             }
66740             var symbols = ts.createSymbolTable();
66741             var isStatic = false;
66742             populateSymbols();
66743             symbols.delete("this" /* This */); // Not a symbol, a keyword
66744             return symbolsToArray(symbols);
66745             function populateSymbols() {
66746                 while (location) {
66747                     if (location.locals && !isGlobalSourceFile(location)) {
66748                         copySymbols(location.locals, meaning);
66749                     }
66750                     switch (location.kind) {
66751                         case 290 /* SourceFile */:
66752                             if (!ts.isExternalOrCommonJsModule(location))
66753                                 break;
66754                         // falls through
66755                         case 249 /* ModuleDeclaration */:
66756                             copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
66757                             break;
66758                         case 248 /* EnumDeclaration */:
66759                             copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
66760                             break;
66761                         case 214 /* ClassExpression */:
66762                             var className = location.name;
66763                             if (className) {
66764                                 copySymbol(location.symbol, meaning);
66765                             }
66766                         // this fall-through is necessary because we would like to handle
66767                         // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
66768                         // falls through
66769                         case 245 /* ClassDeclaration */:
66770                         case 246 /* InterfaceDeclaration */:
66771                             // If we didn't come from static member of class or interface,
66772                             // add the type parameters into the symbol table
66773                             // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
66774                             // Note: that the memberFlags come from previous iteration.
66775                             if (!isStatic) {
66776                                 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
66777                             }
66778                             break;
66779                         case 201 /* FunctionExpression */:
66780                             var funcName = location.name;
66781                             if (funcName) {
66782                                 copySymbol(location.symbol, meaning);
66783                             }
66784                             break;
66785                     }
66786                     if (ts.introducesArgumentsExoticObject(location)) {
66787                         copySymbol(argumentsSymbol, meaning);
66788                     }
66789                     isStatic = ts.hasModifier(location, 32 /* Static */);
66790                     location = location.parent;
66791                 }
66792                 copySymbols(globals, meaning);
66793             }
66794             /**
66795              * Copy the given symbol into symbol tables if the symbol has the given meaning
66796              * and it doesn't already existed in the symbol table
66797              * @param key a key for storing in symbol table; if undefined, use symbol.name
66798              * @param symbol the symbol to be added into symbol table
66799              * @param meaning meaning of symbol to filter by before adding to symbol table
66800              */
66801             function copySymbol(symbol, meaning) {
66802                 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
66803                     var id = symbol.escapedName;
66804                     // We will copy all symbol regardless of its reserved name because
66805                     // symbolsToArray will check whether the key is a reserved name and
66806                     // it will not copy symbol with reserved name to the array
66807                     if (!symbols.has(id)) {
66808                         symbols.set(id, symbol);
66809                     }
66810                 }
66811             }
66812             function copySymbols(source, meaning) {
66813                 if (meaning) {
66814                     source.forEach(function (symbol) {
66815                         copySymbol(symbol, meaning);
66816                     });
66817                 }
66818             }
66819         }
66820         function isTypeDeclarationName(name) {
66821             return name.kind === 75 /* Identifier */ &&
66822                 isTypeDeclaration(name.parent) &&
66823                 name.parent.name === name;
66824         }
66825         function isTypeDeclaration(node) {
66826             switch (node.kind) {
66827                 case 155 /* TypeParameter */:
66828                 case 245 /* ClassDeclaration */:
66829                 case 246 /* InterfaceDeclaration */:
66830                 case 247 /* TypeAliasDeclaration */:
66831                 case 248 /* EnumDeclaration */:
66832                     return true;
66833                 case 255 /* ImportClause */:
66834                     return node.isTypeOnly;
66835                 case 258 /* ImportSpecifier */:
66836                 case 263 /* ExportSpecifier */:
66837                     return node.parent.parent.isTypeOnly;
66838                 default:
66839                     return false;
66840             }
66841         }
66842         // True if the given identifier is part of a type reference
66843         function isTypeReferenceIdentifier(node) {
66844             while (node.parent.kind === 153 /* QualifiedName */) {
66845                 node = node.parent;
66846             }
66847             return node.parent.kind === 169 /* TypeReference */;
66848         }
66849         function isHeritageClauseElementIdentifier(node) {
66850             while (node.parent.kind === 194 /* PropertyAccessExpression */) {
66851                 node = node.parent;
66852             }
66853             return node.parent.kind === 216 /* ExpressionWithTypeArguments */;
66854         }
66855         function forEachEnclosingClass(node, callback) {
66856             var result;
66857             while (true) {
66858                 node = ts.getContainingClass(node);
66859                 if (!node)
66860                     break;
66861                 if (result = callback(node))
66862                     break;
66863             }
66864             return result;
66865         }
66866         function isNodeUsedDuringClassInitialization(node) {
66867             return !!ts.findAncestor(node, function (element) {
66868                 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
66869                     return true;
66870                 }
66871                 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
66872                     return "quit";
66873                 }
66874                 return false;
66875             });
66876         }
66877         function isNodeWithinClass(node, classDeclaration) {
66878             return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
66879         }
66880         function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
66881             while (nodeOnRightSide.parent.kind === 153 /* QualifiedName */) {
66882                 nodeOnRightSide = nodeOnRightSide.parent;
66883             }
66884             if (nodeOnRightSide.parent.kind === 253 /* ImportEqualsDeclaration */) {
66885                 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
66886             }
66887             if (nodeOnRightSide.parent.kind === 259 /* ExportAssignment */) {
66888                 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
66889             }
66890             return undefined;
66891         }
66892         function isInRightSideOfImportOrExportAssignment(node) {
66893             return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
66894         }
66895         function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
66896             var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
66897             switch (specialPropertyAssignmentKind) {
66898                 case 1 /* ExportsProperty */:
66899                 case 3 /* PrototypeProperty */:
66900                     return getSymbolOfNode(entityName.parent);
66901                 case 4 /* ThisProperty */:
66902                 case 2 /* ModuleExports */:
66903                 case 5 /* Property */:
66904                     return getSymbolOfNode(entityName.parent.parent);
66905             }
66906         }
66907         function isImportTypeQualifierPart(node) {
66908             var parent = node.parent;
66909             while (ts.isQualifiedName(parent)) {
66910                 node = parent;
66911                 parent = parent.parent;
66912             }
66913             if (parent && parent.kind === 188 /* ImportType */ && parent.qualifier === node) {
66914                 return parent;
66915             }
66916             return undefined;
66917         }
66918         function getSymbolOfNameOrPropertyAccessExpression(name) {
66919             if (ts.isDeclarationName(name)) {
66920                 return getSymbolOfNode(name.parent);
66921             }
66922             if (ts.isInJSFile(name) &&
66923                 name.parent.kind === 194 /* PropertyAccessExpression */ &&
66924                 name.parent === name.parent.parent.left) {
66925                 // Check if this is a special property assignment
66926                 if (!ts.isPrivateIdentifier(name)) {
66927                     var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
66928                     if (specialPropertyAssignmentSymbol) {
66929                         return specialPropertyAssignmentSymbol;
66930                     }
66931                 }
66932             }
66933             if (name.parent.kind === 259 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
66934                 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
66935                 var success = resolveEntityName(name, 
66936                 /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
66937                 if (success && success !== unknownSymbol) {
66938                     return success;
66939                 }
66940             }
66941             else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) {
66942                 // Since we already checked for ExportAssignment, this really could only be an Import
66943                 var importEqualsDeclaration = ts.getAncestor(name, 253 /* ImportEqualsDeclaration */);
66944                 ts.Debug.assert(importEqualsDeclaration !== undefined);
66945                 return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
66946             }
66947             if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name)) {
66948                 var possibleImportNode = isImportTypeQualifierPart(name);
66949                 if (possibleImportNode) {
66950                     getTypeFromTypeNode(possibleImportNode);
66951                     var sym = getNodeLinks(name).resolvedSymbol;
66952                     return sym === unknownSymbol ? undefined : sym;
66953                 }
66954             }
66955             while (ts.isRightSideOfQualifiedNameOrPropertyAccess(name)) {
66956                 name = name.parent;
66957             }
66958             if (isHeritageClauseElementIdentifier(name)) {
66959                 var meaning = 0 /* None */;
66960                 // In an interface or class, we're definitely interested in a type.
66961                 if (name.parent.kind === 216 /* ExpressionWithTypeArguments */) {
66962                     meaning = 788968 /* Type */;
66963                     // In a class 'extends' clause we are also looking for a value.
66964                     if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
66965                         meaning |= 111551 /* Value */;
66966                     }
66967                 }
66968                 else {
66969                     meaning = 1920 /* Namespace */;
66970                 }
66971                 meaning |= 2097152 /* Alias */;
66972                 var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
66973                 if (entityNameSymbol) {
66974                     return entityNameSymbol;
66975                 }
66976             }
66977             if (name.parent.kind === 317 /* JSDocParameterTag */) {
66978                 return ts.getParameterSymbolFromJSDoc(name.parent);
66979             }
66980             if (name.parent.kind === 155 /* TypeParameter */ && name.parent.parent.kind === 321 /* JSDocTemplateTag */) {
66981                 ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
66982                 var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
66983                 return typeParameter && typeParameter.symbol;
66984             }
66985             if (ts.isExpressionNode(name)) {
66986                 if (ts.nodeIsMissing(name)) {
66987                     // Missing entity name.
66988                     return undefined;
66989                 }
66990                 if (name.kind === 75 /* Identifier */) {
66991                     if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
66992                         var symbol = getIntrinsicTagSymbol(name.parent);
66993                         return symbol === unknownSymbol ? undefined : symbol;
66994                     }
66995                     return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
66996                 }
66997                 else if (name.kind === 194 /* PropertyAccessExpression */ || name.kind === 153 /* QualifiedName */) {
66998                     var links = getNodeLinks(name);
66999                     if (links.resolvedSymbol) {
67000                         return links.resolvedSymbol;
67001                     }
67002                     if (name.kind === 194 /* PropertyAccessExpression */) {
67003                         checkPropertyAccessExpression(name);
67004                     }
67005                     else {
67006                         checkQualifiedName(name);
67007                     }
67008                     return links.resolvedSymbol;
67009                 }
67010             }
67011             else if (isTypeReferenceIdentifier(name)) {
67012                 var meaning = name.parent.kind === 169 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
67013                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
67014             }
67015             if (name.parent.kind === 168 /* TypePredicate */) {
67016                 return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
67017             }
67018             // Do we want to return undefined here?
67019             return undefined;
67020         }
67021         function getSymbolAtLocation(node, ignoreErrors) {
67022             if (node.kind === 290 /* SourceFile */) {
67023                 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
67024             }
67025             var parent = node.parent;
67026             var grandParent = parent.parent;
67027             if (node.flags & 16777216 /* InWithStatement */) {
67028                 // We cannot answer semantic questions within a with block, do not proceed any further
67029                 return undefined;
67030             }
67031             if (isDeclarationNameOrImportPropertyName(node)) {
67032                 // This is a declaration, call getSymbolOfNode
67033                 var parentSymbol = getSymbolOfNode(parent);
67034                 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
67035                     ? getImmediateAliasedSymbol(parentSymbol)
67036                     : parentSymbol;
67037             }
67038             else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
67039                 return getSymbolOfNode(parent.parent);
67040             }
67041             if (node.kind === 75 /* Identifier */) {
67042                 if (isInRightSideOfImportOrExportAssignment(node)) {
67043                     return getSymbolOfNameOrPropertyAccessExpression(node);
67044                 }
67045                 else if (parent.kind === 191 /* BindingElement */ &&
67046                     grandParent.kind === 189 /* ObjectBindingPattern */ &&
67047                     node === parent.propertyName) {
67048                     var typeOfPattern = getTypeOfNode(grandParent);
67049                     var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
67050                     if (propertyDeclaration) {
67051                         return propertyDeclaration;
67052                     }
67053                 }
67054             }
67055             switch (node.kind) {
67056                 case 75 /* Identifier */:
67057                 case 76 /* PrivateIdentifier */:
67058                 case 194 /* PropertyAccessExpression */:
67059                 case 153 /* QualifiedName */:
67060                     return getSymbolOfNameOrPropertyAccessExpression(node);
67061                 case 104 /* ThisKeyword */:
67062                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
67063                     if (ts.isFunctionLike(container)) {
67064                         var sig = getSignatureFromDeclaration(container);
67065                         if (sig.thisParameter) {
67066                             return sig.thisParameter;
67067                         }
67068                     }
67069                     if (ts.isInExpressionContext(node)) {
67070                         return checkExpression(node).symbol;
67071                     }
67072                 // falls through
67073                 case 183 /* ThisType */:
67074                     return getTypeFromThisTypeNode(node).symbol;
67075                 case 102 /* SuperKeyword */:
67076                     return checkExpression(node).symbol;
67077                 case 129 /* ConstructorKeyword */:
67078                     // constructor keyword for an overload, should take us to the definition if it exist
67079                     var constructorDeclaration = node.parent;
67080                     if (constructorDeclaration && constructorDeclaration.kind === 162 /* Constructor */) {
67081                         return constructorDeclaration.parent.symbol;
67082                     }
67083                     return undefined;
67084                 case 10 /* StringLiteral */:
67085                 case 14 /* NoSubstitutionTemplateLiteral */:
67086                     // 1). import x = require("./mo/*gotToDefinitionHere*/d")
67087                     // 2). External module name in an import declaration
67088                     // 3). Dynamic import call or require in javascript
67089                     // 4). type A = import("./f/*gotToDefinitionHere*/oo")
67090                     if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
67091                         ((node.parent.kind === 254 /* ImportDeclaration */ || node.parent.kind === 260 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
67092                         ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
67093                         (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
67094                         return resolveExternalModuleName(node, node, ignoreErrors);
67095                     }
67096                     if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
67097                         return getSymbolOfNode(parent);
67098                     }
67099                 // falls through
67100                 case 8 /* NumericLiteral */:
67101                     // index access
67102                     var objectType = ts.isElementAccessExpression(parent)
67103                         ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
67104                         : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
67105                             ? getTypeFromTypeNode(grandParent.objectType)
67106                             : undefined;
67107                     return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
67108                 case 84 /* DefaultKeyword */:
67109                 case 94 /* FunctionKeyword */:
67110                 case 38 /* EqualsGreaterThanToken */:
67111                 case 80 /* ClassKeyword */:
67112                     return getSymbolOfNode(node.parent);
67113                 case 188 /* ImportType */:
67114                     return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
67115                 case 89 /* ExportKeyword */:
67116                     return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined;
67117                 default:
67118                     return undefined;
67119             }
67120         }
67121         function getShorthandAssignmentValueSymbol(location) {
67122             if (location && location.kind === 282 /* ShorthandPropertyAssignment */) {
67123                 return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
67124             }
67125             return undefined;
67126         }
67127         /** Returns the target of an export specifier without following aliases */
67128         function getExportSpecifierLocalTargetSymbol(node) {
67129             return node.parent.parent.moduleSpecifier ?
67130                 getExternalModuleMember(node.parent.parent, node) :
67131                 resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
67132         }
67133         function getTypeOfNode(node) {
67134             if (node.flags & 16777216 /* InWithStatement */) {
67135                 // We cannot answer semantic questions within a with block, do not proceed any further
67136                 return errorType;
67137             }
67138             var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
67139             var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
67140             if (ts.isPartOfTypeNode(node)) {
67141                 var typeFromTypeNode = getTypeFromTypeNode(node);
67142                 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
67143             }
67144             if (ts.isExpressionNode(node)) {
67145                 return getRegularTypeOfExpression(node);
67146             }
67147             if (classType && !classDecl.isImplements) {
67148                 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
67149                 // extends clause of a class. We handle that case here.
67150                 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
67151                 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
67152             }
67153             if (isTypeDeclaration(node)) {
67154                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67155                 var symbol = getSymbolOfNode(node);
67156                 return getDeclaredTypeOfSymbol(symbol);
67157             }
67158             if (isTypeDeclarationName(node)) {
67159                 var symbol = getSymbolAtLocation(node);
67160                 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
67161             }
67162             if (ts.isDeclaration(node)) {
67163                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67164                 var symbol = getSymbolOfNode(node);
67165                 return getTypeOfSymbol(symbol);
67166             }
67167             if (isDeclarationNameOrImportPropertyName(node)) {
67168                 var symbol = getSymbolAtLocation(node);
67169                 if (symbol) {
67170                     return getTypeOfSymbol(symbol);
67171                 }
67172                 return errorType;
67173             }
67174             if (ts.isBindingPattern(node)) {
67175                 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
67176             }
67177             if (isInRightSideOfImportOrExportAssignment(node)) {
67178                 var symbol = getSymbolAtLocation(node);
67179                 if (symbol) {
67180                     var declaredType = getDeclaredTypeOfSymbol(symbol);
67181                     return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
67182                 }
67183             }
67184             return errorType;
67185         }
67186         // Gets the type of object literal or array literal of destructuring assignment.
67187         // { a } from
67188         //     for ( { a } of elems) {
67189         //     }
67190         // [ a ] from
67191         //     [a] = [ some array ...]
67192         function getTypeOfAssignmentPattern(expr) {
67193             ts.Debug.assert(expr.kind === 193 /* ObjectLiteralExpression */ || expr.kind === 192 /* ArrayLiteralExpression */);
67194             // If this is from "for of"
67195             //     for ( { a } of elems) {
67196             //     }
67197             if (expr.parent.kind === 232 /* ForOfStatement */) {
67198                 var iteratedType = checkRightHandSideOfForOf(expr.parent);
67199                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67200             }
67201             // If this is from "for" initializer
67202             //     for ({a } = elems[0];.....) { }
67203             if (expr.parent.kind === 209 /* BinaryExpression */) {
67204                 var iteratedType = getTypeOfExpression(expr.parent.right);
67205                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67206             }
67207             // If this is from nested object binding pattern
67208             //     for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
67209             if (expr.parent.kind === 281 /* PropertyAssignment */) {
67210                 var node_4 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
67211                 var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_4) || errorType;
67212                 var propertyIndex = ts.indexOfNode(node_4.properties, expr.parent);
67213                 return checkObjectLiteralDestructuringPropertyAssignment(node_4, typeOfParentObjectLiteral, propertyIndex);
67214             }
67215             // Array literal assignment - array destructuring pattern
67216             var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
67217             //    [{ property1: p1, property2 }] = elems;
67218             var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
67219             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
67220             return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
67221         }
67222         // Gets the property symbol corresponding to the property in destructuring assignment
67223         // 'property1' from
67224         //     for ( { property1: a } of elems) {
67225         //     }
67226         // 'property1' at location 'a' from:
67227         //     [a] = [ property1, property2 ]
67228         function getPropertySymbolOfDestructuringAssignment(location) {
67229             // Get the type of the object or array literal and then look for property of given name in the type
67230             var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
67231             return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
67232         }
67233         function getRegularTypeOfExpression(expr) {
67234             if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
67235                 expr = expr.parent;
67236             }
67237             return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
67238         }
67239         /**
67240          * Gets either the static or instance type of a class element, based on
67241          * whether the element is declared as "static".
67242          */
67243         function getParentTypeOfClassElement(node) {
67244             var classSymbol = getSymbolOfNode(node.parent);
67245             return ts.hasModifier(node, 32 /* Static */)
67246                 ? getTypeOfSymbol(classSymbol)
67247                 : getDeclaredTypeOfSymbol(classSymbol);
67248         }
67249         function getClassElementPropertyKeyType(element) {
67250             var name = element.name;
67251             switch (name.kind) {
67252                 case 75 /* Identifier */:
67253                     return getLiteralType(ts.idText(name));
67254                 case 8 /* NumericLiteral */:
67255                 case 10 /* StringLiteral */:
67256                     return getLiteralType(name.text);
67257                 case 154 /* ComputedPropertyName */:
67258                     var nameType = checkComputedPropertyName(name);
67259                     return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
67260                 default:
67261                     return ts.Debug.fail("Unsupported property name.");
67262             }
67263         }
67264         // Return the list of properties of the given type, augmented with properties from Function
67265         // if the type has call or construct signatures
67266         function getAugmentedPropertiesOfType(type) {
67267             type = getApparentType(type);
67268             var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
67269             var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
67270                 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
67271                     undefined;
67272             if (functionType) {
67273                 ts.forEach(getPropertiesOfType(functionType), function (p) {
67274                     if (!propsByName.has(p.escapedName)) {
67275                         propsByName.set(p.escapedName, p);
67276                     }
67277                 });
67278             }
67279             return getNamedMembers(propsByName);
67280         }
67281         function typeHasCallOrConstructSignatures(type) {
67282             return ts.typeHasCallOrConstructSignatures(type, checker);
67283         }
67284         function getRootSymbols(symbol) {
67285             var roots = getImmediateRootSymbols(symbol);
67286             return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
67287         }
67288         function getImmediateRootSymbols(symbol) {
67289             if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
67290                 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
67291             }
67292             else if (symbol.flags & 33554432 /* Transient */) {
67293                 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
67294                 return leftSpread ? [leftSpread, rightSpread]
67295                     : syntheticOrigin ? [syntheticOrigin]
67296                         : ts.singleElementArray(tryGetAliasTarget(symbol));
67297             }
67298             return undefined;
67299         }
67300         function tryGetAliasTarget(symbol) {
67301             var target;
67302             var next = symbol;
67303             while (next = getSymbolLinks(next).target) {
67304                 target = next;
67305             }
67306             return target;
67307         }
67308         // Emitter support
67309         function isArgumentsLocalBinding(nodeIn) {
67310             if (!ts.isGeneratedIdentifier(nodeIn)) {
67311                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67312                 if (node) {
67313                     var isPropertyName_1 = node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node;
67314                     return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol;
67315                 }
67316             }
67317             return false;
67318         }
67319         function moduleExportsSomeValue(moduleReferenceExpression) {
67320             var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
67321             if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
67322                 // If the module is not found or is shorthand, assume that it may export a value.
67323                 return true;
67324             }
67325             var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
67326             // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
67327             // otherwise it will return moduleSymbol itself
67328             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
67329             var symbolLinks = getSymbolLinks(moduleSymbol);
67330             if (symbolLinks.exportsSomeValue === undefined) {
67331                 // for export assignments - check if resolved symbol for RHS is itself a value
67332                 // otherwise - check if at least one export is value
67333                 symbolLinks.exportsSomeValue = hasExportAssignment
67334                     ? !!(moduleSymbol.flags & 111551 /* Value */)
67335                     : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
67336             }
67337             return symbolLinks.exportsSomeValue;
67338             function isValue(s) {
67339                 s = resolveSymbol(s);
67340                 return s && !!(s.flags & 111551 /* Value */);
67341             }
67342         }
67343         function isNameOfModuleOrEnumDeclaration(node) {
67344             return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
67345         }
67346         // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
67347         // node of the exported entity's container. Otherwise, return undefined.
67348         function getReferencedExportContainer(nodeIn, prefixLocals) {
67349             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67350             if (node) {
67351                 // When resolving the export container for the name of a module or enum
67352                 // declaration, we need to start resolution at the declaration's container.
67353                 // Otherwise, we could incorrectly resolve the export container as the
67354                 // declaration if it contains an exported member with the same name.
67355                 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
67356                 if (symbol) {
67357                     if (symbol.flags & 1048576 /* ExportValue */) {
67358                         // If we reference an exported entity within the same module declaration, then whether
67359                         // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
67360                         // kinds that we do NOT prefix.
67361                         var exportSymbol = getMergedSymbol(symbol.exportSymbol);
67362                         if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
67363                             return undefined;
67364                         }
67365                         symbol = exportSymbol;
67366                     }
67367                     var parentSymbol_1 = getParentOfSymbol(symbol);
67368                     if (parentSymbol_1) {
67369                         if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 290 /* SourceFile */) {
67370                             var symbolFile = parentSymbol_1.valueDeclaration;
67371                             var referenceFile = ts.getSourceFileOfNode(node);
67372                             // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
67373                             var symbolIsUmdExport = symbolFile !== referenceFile;
67374                             return symbolIsUmdExport ? undefined : symbolFile;
67375                         }
67376                         return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
67377                     }
67378                 }
67379             }
67380         }
67381         // When resolved as an expression identifier, if the given node references an import, return the declaration of
67382         // that import. Otherwise, return undefined.
67383         function getReferencedImportDeclaration(nodeIn) {
67384             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67385             if (node) {
67386                 var symbol = getReferencedValueSymbol(node);
67387                 // We should only get the declaration of an alias if there isn't a local value
67388                 // declaration for the symbol
67389                 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
67390                     return getDeclarationOfAliasSymbol(symbol);
67391                 }
67392             }
67393             return undefined;
67394         }
67395         function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
67396             return ts.isBindingElement(symbol.valueDeclaration)
67397                 && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 280 /* CatchClause */;
67398         }
67399         function isSymbolOfDeclarationWithCollidingName(symbol) {
67400             if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
67401                 var links = getSymbolLinks(symbol);
67402                 if (links.isDeclarationWithCollidingName === undefined) {
67403                     var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
67404                     if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
67405                         var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
67406                         if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
67407                             // redeclaration - always should be renamed
67408                             links.isDeclarationWithCollidingName = true;
67409                         }
67410                         else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
67411                             // binding is captured in the function
67412                             // should be renamed if:
67413                             // - binding is not top level - top level bindings never collide with anything
67414                             // AND
67415                             //   - binding is not declared in loop, should be renamed to avoid name reuse across siblings
67416                             //     let a, b
67417                             //     { let x = 1; a = () => x; }
67418                             //     { let x = 100; b = () => x; }
67419                             //     console.log(a()); // should print '1'
67420                             //     console.log(b()); // should print '100'
67421                             //     OR
67422                             //   - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
67423                             //     * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
67424                             //     * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
67425                             //       they will not collide with anything
67426                             var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
67427                             var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
67428                             var inLoopBodyBlock = container.kind === 223 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
67429                             links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
67430                         }
67431                         else {
67432                             links.isDeclarationWithCollidingName = false;
67433                         }
67434                     }
67435                 }
67436                 return links.isDeclarationWithCollidingName;
67437             }
67438             return false;
67439         }
67440         // When resolved as an expression identifier, if the given node references a nested block scoped entity with
67441         // a name that either hides an existing name or might hide it when compiled downlevel,
67442         // return the declaration of that entity. Otherwise, return undefined.
67443         function getReferencedDeclarationWithCollidingName(nodeIn) {
67444             if (!ts.isGeneratedIdentifier(nodeIn)) {
67445                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67446                 if (node) {
67447                     var symbol = getReferencedValueSymbol(node);
67448                     if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
67449                         return symbol.valueDeclaration;
67450                     }
67451                 }
67452             }
67453             return undefined;
67454         }
67455         // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
67456         // existing name or might hide a name when compiled downlevel
67457         function isDeclarationWithCollidingName(nodeIn) {
67458             var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67459             if (node) {
67460                 var symbol = getSymbolOfNode(node);
67461                 if (symbol) {
67462                     return isSymbolOfDeclarationWithCollidingName(symbol);
67463                 }
67464             }
67465             return false;
67466         }
67467         function isValueAliasDeclaration(node) {
67468             switch (node.kind) {
67469                 case 253 /* ImportEqualsDeclaration */:
67470                     return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
67471                 case 255 /* ImportClause */:
67472                 case 256 /* NamespaceImport */:
67473                 case 258 /* ImportSpecifier */:
67474                 case 263 /* ExportSpecifier */:
67475                     var symbol = getSymbolOfNode(node) || unknownSymbol;
67476                     return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
67477                 case 260 /* ExportDeclaration */:
67478                     var exportClause = node.exportClause;
67479                     return !!exportClause && (ts.isNamespaceExport(exportClause) ||
67480                         ts.some(exportClause.elements, isValueAliasDeclaration));
67481                 case 259 /* ExportAssignment */:
67482                     return node.expression && node.expression.kind === 75 /* Identifier */ ?
67483                         isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) :
67484                         true;
67485             }
67486             return false;
67487         }
67488         function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
67489             var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
67490             if (node === undefined || node.parent.kind !== 290 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
67491                 // parent is not source file or it is not reference to internal module
67492                 return false;
67493             }
67494             var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
67495             return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
67496         }
67497         function isAliasResolvedToValue(symbol) {
67498             var target = resolveAlias(symbol);
67499             if (target === unknownSymbol) {
67500                 return true;
67501             }
67502             // const enums and modules that contain only const enums are not considered values from the emit perspective
67503             // unless 'preserveConstEnums' option is set to true
67504             return !!(target.flags & 111551 /* Value */) &&
67505                 (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
67506         }
67507         function isConstEnumOrConstEnumOnlyModule(s) {
67508             return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
67509         }
67510         function isReferencedAliasDeclaration(node, checkChildren) {
67511             if (isAliasSymbolDeclaration(node)) {
67512                 var symbol = getSymbolOfNode(node);
67513                 if (symbol && getSymbolLinks(symbol).referenced) {
67514                     return true;
67515                 }
67516                 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
67517                 if (target && ts.getModifierFlags(node) & 1 /* Export */ &&
67518                     target.flags & 111551 /* Value */ &&
67519                     (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
67520                     // An `export import ... =` of a value symbol is always considered referenced
67521                     return true;
67522                 }
67523             }
67524             if (checkChildren) {
67525                 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
67526             }
67527             return false;
67528         }
67529         function isImplementationOfOverload(node) {
67530             if (ts.nodeIsPresent(node.body)) {
67531                 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
67532                     return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
67533                 var symbol = getSymbolOfNode(node);
67534                 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
67535                 // If this function body corresponds to function with multiple signature, it is implementation of overload
67536                 // e.g.: function foo(a: string): string;
67537                 //       function foo(a: number): number;
67538                 //       function foo(a: any) { // This is implementation of the overloads
67539                 //           return a;
67540                 //       }
67541                 return signaturesOfSymbol.length > 1 ||
67542                     // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
67543                     // e.g.: function foo(a: string): string;
67544                     //       function foo(a: any) { // This is implementation of the overloads
67545                     //           return a;
67546                     //       }
67547                     (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
67548             }
67549             return false;
67550         }
67551         function isRequiredInitializedParameter(parameter) {
67552             return !!strictNullChecks &&
67553                 !isOptionalParameter(parameter) &&
67554                 !ts.isJSDocParameterTag(parameter) &&
67555                 !!parameter.initializer &&
67556                 !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67557         }
67558         function isOptionalUninitializedParameterProperty(parameter) {
67559             return strictNullChecks &&
67560                 isOptionalParameter(parameter) &&
67561                 !parameter.initializer &&
67562                 ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67563         }
67564         function isExpandoFunctionDeclaration(node) {
67565             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67566             if (!declaration) {
67567                 return false;
67568             }
67569             var symbol = getSymbolOfNode(declaration);
67570             if (!symbol || !(symbol.flags & 16 /* Function */)) {
67571                 return false;
67572             }
67573             return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
67574         }
67575         function getPropertiesOfContainerFunction(node) {
67576             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67577             if (!declaration) {
67578                 return ts.emptyArray;
67579             }
67580             var symbol = getSymbolOfNode(declaration);
67581             return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
67582         }
67583         function getNodeCheckFlags(node) {
67584             return getNodeLinks(node).flags || 0;
67585         }
67586         function getEnumMemberValue(node) {
67587             computeEnumMemberValues(node.parent);
67588             return getNodeLinks(node).enumMemberValue;
67589         }
67590         function canHaveConstantValue(node) {
67591             switch (node.kind) {
67592                 case 284 /* EnumMember */:
67593                 case 194 /* PropertyAccessExpression */:
67594                 case 195 /* ElementAccessExpression */:
67595                     return true;
67596             }
67597             return false;
67598         }
67599         function getConstantValue(node) {
67600             if (node.kind === 284 /* EnumMember */) {
67601                 return getEnumMemberValue(node);
67602             }
67603             var symbol = getNodeLinks(node).resolvedSymbol;
67604             if (symbol && (symbol.flags & 8 /* EnumMember */)) {
67605                 // inline property\index accesses only for const enums
67606                 var member = symbol.valueDeclaration;
67607                 if (ts.isEnumConst(member.parent)) {
67608                     return getEnumMemberValue(member);
67609                 }
67610             }
67611             return undefined;
67612         }
67613         function isFunctionType(type) {
67614             return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
67615         }
67616         function getTypeReferenceSerializationKind(typeNameIn, location) {
67617             // ensure both `typeName` and `location` are parse tree nodes.
67618             var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
67619             if (!typeName)
67620                 return ts.TypeReferenceSerializationKind.Unknown;
67621             if (location) {
67622                 location = ts.getParseTreeNode(location);
67623                 if (!location)
67624                     return ts.TypeReferenceSerializationKind.Unknown;
67625             }
67626             // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
67627             var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67628             // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
67629             var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67630             if (valueSymbol && valueSymbol === typeSymbol) {
67631                 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
67632                 if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
67633                     return ts.TypeReferenceSerializationKind.Promise;
67634                 }
67635                 var constructorType = getTypeOfSymbol(valueSymbol);
67636                 if (constructorType && isConstructorType(constructorType)) {
67637                     return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
67638                 }
67639             }
67640             // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
67641             if (!typeSymbol) {
67642                 return ts.TypeReferenceSerializationKind.Unknown;
67643             }
67644             var type = getDeclaredTypeOfSymbol(typeSymbol);
67645             if (type === errorType) {
67646                 return ts.TypeReferenceSerializationKind.Unknown;
67647             }
67648             else if (type.flags & 3 /* AnyOrUnknown */) {
67649                 return ts.TypeReferenceSerializationKind.ObjectType;
67650             }
67651             else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
67652                 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
67653             }
67654             else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
67655                 return ts.TypeReferenceSerializationKind.BooleanType;
67656             }
67657             else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
67658                 return ts.TypeReferenceSerializationKind.NumberLikeType;
67659             }
67660             else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
67661                 return ts.TypeReferenceSerializationKind.BigIntLikeType;
67662             }
67663             else if (isTypeAssignableToKind(type, 132 /* StringLike */)) {
67664                 return ts.TypeReferenceSerializationKind.StringLikeType;
67665             }
67666             else if (isTupleType(type)) {
67667                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67668             }
67669             else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
67670                 return ts.TypeReferenceSerializationKind.ESSymbolType;
67671             }
67672             else if (isFunctionType(type)) {
67673                 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
67674             }
67675             else if (isArrayType(type)) {
67676                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67677             }
67678             else {
67679                 return ts.TypeReferenceSerializationKind.ObjectType;
67680             }
67681         }
67682         function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
67683             var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
67684             if (!declaration) {
67685                 return ts.createToken(125 /* AnyKeyword */);
67686             }
67687             // Get type of the symbol if this is the valid symbol otherwise get type at location
67688             var symbol = getSymbolOfNode(declaration);
67689             var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
67690                 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
67691                 : errorType;
67692             if (type.flags & 8192 /* UniqueESSymbol */ &&
67693                 type.symbol === symbol) {
67694                 flags |= 1048576 /* AllowUniqueESSymbolType */;
67695             }
67696             if (addUndefined) {
67697                 type = getOptionalType(type);
67698             }
67699             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67700         }
67701         function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
67702             var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
67703             if (!signatureDeclaration) {
67704                 return ts.createToken(125 /* AnyKeyword */);
67705             }
67706             var signature = getSignatureFromDeclaration(signatureDeclaration);
67707             return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67708         }
67709         function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
67710             var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
67711             if (!expr) {
67712                 return ts.createToken(125 /* AnyKeyword */);
67713             }
67714             var type = getWidenedType(getRegularTypeOfExpression(expr));
67715             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67716         }
67717         function hasGlobalName(name) {
67718             return globals.has(ts.escapeLeadingUnderscores(name));
67719         }
67720         function getReferencedValueSymbol(reference, startInDeclarationContainer) {
67721             var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
67722             if (resolvedSymbol) {
67723                 return resolvedSymbol;
67724             }
67725             var location = reference;
67726             if (startInDeclarationContainer) {
67727                 // When resolving the name of a declaration as a value, we need to start resolution
67728                 // at a point outside of the declaration.
67729                 var parent = reference.parent;
67730                 if (ts.isDeclaration(parent) && reference === parent.name) {
67731                     location = getDeclarationContainer(parent);
67732                 }
67733             }
67734             return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
67735         }
67736         function getReferencedValueDeclaration(referenceIn) {
67737             if (!ts.isGeneratedIdentifier(referenceIn)) {
67738                 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
67739                 if (reference) {
67740                     var symbol = getReferencedValueSymbol(reference);
67741                     if (symbol) {
67742                         return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
67743                     }
67744                 }
67745             }
67746             return undefined;
67747         }
67748         function isLiteralConstDeclaration(node) {
67749             if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
67750                 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
67751             }
67752             return false;
67753         }
67754         function literalTypeToNode(type, enclosing, tracker) {
67755             var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
67756                 : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse();
67757             return enumResult || ts.createLiteral(type.value);
67758         }
67759         function createLiteralConstValue(node, tracker) {
67760             var type = getTypeOfSymbol(getSymbolOfNode(node));
67761             return literalTypeToNode(type, node, tracker);
67762         }
67763         function getJsxFactoryEntity(location) {
67764             return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity;
67765         }
67766         function createResolver() {
67767             // this variable and functions that use it are deliberately moved here from the outer scope
67768             // to avoid scope pollution
67769             var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
67770             var fileToDirective;
67771             if (resolvedTypeReferenceDirectives) {
67772                 // populate reverse mapping: file path -> type reference directive that was resolved to this file
67773                 fileToDirective = ts.createMap();
67774                 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
67775                     if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
67776                         return;
67777                     }
67778                     var file = host.getSourceFile(resolvedDirective.resolvedFileName);
67779                     if (file) {
67780                         // Add the transitive closure of path references loaded by this file (as long as they are not)
67781                         // part of an existing type reference.
67782                         addReferencedFilesToTypeDirective(file, key);
67783                     }
67784                 });
67785             }
67786             return {
67787                 getReferencedExportContainer: getReferencedExportContainer,
67788                 getReferencedImportDeclaration: getReferencedImportDeclaration,
67789                 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
67790                 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
67791                 isValueAliasDeclaration: function (node) {
67792                     node = ts.getParseTreeNode(node);
67793                     // Synthesized nodes are always treated like values.
67794                     return node ? isValueAliasDeclaration(node) : true;
67795                 },
67796                 hasGlobalName: hasGlobalName,
67797                 isReferencedAliasDeclaration: function (node, checkChildren) {
67798                     node = ts.getParseTreeNode(node);
67799                     // Synthesized nodes are always treated as referenced.
67800                     return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
67801                 },
67802                 getNodeCheckFlags: function (node) {
67803                     node = ts.getParseTreeNode(node);
67804                     return node ? getNodeCheckFlags(node) : 0;
67805                 },
67806                 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
67807                 isDeclarationVisible: isDeclarationVisible,
67808                 isImplementationOfOverload: isImplementationOfOverload,
67809                 isRequiredInitializedParameter: isRequiredInitializedParameter,
67810                 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
67811                 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
67812                 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
67813                 createTypeOfDeclaration: createTypeOfDeclaration,
67814                 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
67815                 createTypeOfExpression: createTypeOfExpression,
67816                 createLiteralConstValue: createLiteralConstValue,
67817                 isSymbolAccessible: isSymbolAccessible,
67818                 isEntityNameVisible: isEntityNameVisible,
67819                 getConstantValue: function (nodeIn) {
67820                     var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
67821                     return node ? getConstantValue(node) : undefined;
67822                 },
67823                 collectLinkedAliases: collectLinkedAliases,
67824                 getReferencedValueDeclaration: getReferencedValueDeclaration,
67825                 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
67826                 isOptionalParameter: isOptionalParameter,
67827                 moduleExportsSomeValue: moduleExportsSomeValue,
67828                 isArgumentsLocalBinding: isArgumentsLocalBinding,
67829                 getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
67830                 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
67831                 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
67832                 isLiteralConstDeclaration: isLiteralConstDeclaration,
67833                 isLateBound: function (nodeIn) {
67834                     var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67835                     var symbol = node && getSymbolOfNode(node);
67836                     return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
67837                 },
67838                 getJsxFactoryEntity: getJsxFactoryEntity,
67839                 getAllAccessorDeclarations: function (accessor) {
67840                     accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
67841                     var otherKind = accessor.kind === 164 /* SetAccessor */ ? 163 /* GetAccessor */ : 164 /* SetAccessor */;
67842                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
67843                     var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
67844                     var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
67845                     var setAccessor = accessor.kind === 164 /* SetAccessor */ ? accessor : otherAccessor;
67846                     var getAccessor = accessor.kind === 163 /* GetAccessor */ ? accessor : otherAccessor;
67847                     return {
67848                         firstAccessor: firstAccessor,
67849                         secondAccessor: secondAccessor,
67850                         setAccessor: setAccessor,
67851                         getAccessor: getAccessor
67852                     };
67853                 },
67854                 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
67855                 isBindingCapturedByNode: function (node, decl) {
67856                     var parseNode = ts.getParseTreeNode(node);
67857                     var parseDecl = ts.getParseTreeNode(decl);
67858                     return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
67859                 },
67860                 getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
67861                     var n = ts.getParseTreeNode(node);
67862                     ts.Debug.assert(n && n.kind === 290 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
67863                     var sym = getSymbolOfNode(node);
67864                     if (!sym) {
67865                         return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
67866                     }
67867                     return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
67868                 },
67869                 isImportRequiredByAugmentation: isImportRequiredByAugmentation,
67870             };
67871             function isImportRequiredByAugmentation(node) {
67872                 var file = ts.getSourceFileOfNode(node);
67873                 if (!file.symbol)
67874                     return false;
67875                 var importTarget = getExternalModuleFileFromDeclaration(node);
67876                 if (!importTarget)
67877                     return false;
67878                 if (importTarget === file)
67879                     return false;
67880                 var exports = getExportsOfModule(file.symbol);
67881                 for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) {
67882                     var s = _a[_i];
67883                     if (s.mergeId) {
67884                         var merged = getMergedSymbol(s);
67885                         for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) {
67886                             var d = _c[_b];
67887                             var declFile = ts.getSourceFileOfNode(d);
67888                             if (declFile === importTarget) {
67889                                 return true;
67890                             }
67891                         }
67892                     }
67893                 }
67894                 return false;
67895             }
67896             function isInHeritageClause(node) {
67897                 return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */;
67898             }
67899             // defined here to avoid outer scope pollution
67900             function getTypeReferenceDirectivesForEntityName(node) {
67901                 // program does not have any files with type reference directives - bail out
67902                 if (!fileToDirective) {
67903                     return undefined;
67904                 }
67905                 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
67906                 // qualified names can only be used as types\namespaces
67907                 // identifiers are treated as values only if they appear in type queries
67908                 var meaning = 788968 /* Type */ | 1920 /* Namespace */;
67909                 if ((node.kind === 75 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 194 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
67910                     meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
67911                 }
67912                 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
67913                 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
67914             }
67915             // defined here to avoid outer scope pollution
67916             function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
67917                 // program does not have any files with type reference directives - bail out
67918                 if (!fileToDirective) {
67919                     return undefined;
67920                 }
67921                 if (!isSymbolFromTypeDeclarationFile(symbol)) {
67922                     return undefined;
67923                 }
67924                 // check what declarations in the symbol can contribute to the target meaning
67925                 var typeReferenceDirectives;
67926                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
67927                     var decl = _a[_i];
67928                     // check meaning of the local symbol to see if declaration needs to be analyzed further
67929                     if (decl.symbol && decl.symbol.flags & meaning) {
67930                         var file = ts.getSourceFileOfNode(decl);
67931                         var typeReferenceDirective = fileToDirective.get(file.path);
67932                         if (typeReferenceDirective) {
67933                             (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
67934                         }
67935                         else {
67936                             // found at least one entry that does not originate from type reference directive
67937                             return undefined;
67938                         }
67939                     }
67940                 }
67941                 return typeReferenceDirectives;
67942             }
67943             function isSymbolFromTypeDeclarationFile(symbol) {
67944                 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
67945                 if (!symbol.declarations) {
67946                     return false;
67947                 }
67948                 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
67949                 // external modules cannot define or contribute to type declaration files
67950                 var current = symbol;
67951                 while (true) {
67952                     var parent = getParentOfSymbol(current);
67953                     if (parent) {
67954                         current = parent;
67955                     }
67956                     else {
67957                         break;
67958                     }
67959                 }
67960                 if (current.valueDeclaration && current.valueDeclaration.kind === 290 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
67961                     return false;
67962                 }
67963                 // check that at least one declaration of top level symbol originates from type declaration file
67964                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
67965                     var decl = _a[_i];
67966                     var file = ts.getSourceFileOfNode(decl);
67967                     if (fileToDirective.has(file.path)) {
67968                         return true;
67969                     }
67970                 }
67971                 return false;
67972             }
67973             function addReferencedFilesToTypeDirective(file, key) {
67974                 if (fileToDirective.has(file.path))
67975                     return;
67976                 fileToDirective.set(file.path, key);
67977                 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
67978                     var fileName = _a[_i].fileName;
67979                     var resolvedFile = ts.resolveTripleslashReference(fileName, file.originalFileName);
67980                     var referencedFile = host.getSourceFile(resolvedFile);
67981                     if (referencedFile) {
67982                         addReferencedFilesToTypeDirective(referencedFile, key);
67983                     }
67984                 }
67985             }
67986         }
67987         function getExternalModuleFileFromDeclaration(declaration) {
67988             var specifier = declaration.kind === 249 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
67989             var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
67990             if (!moduleSymbol) {
67991                 return undefined;
67992             }
67993             return ts.getDeclarationOfKind(moduleSymbol, 290 /* SourceFile */);
67994         }
67995         function initializeTypeChecker() {
67996             // Bind all source files and propagate errors
67997             for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
67998                 var file = _a[_i];
67999                 ts.bindSourceFile(file, compilerOptions);
68000             }
68001             amalgamatedDuplicates = ts.createMap();
68002             // Initialize global symbol table
68003             var augmentations;
68004             for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
68005                 var file = _c[_b];
68006                 if (file.redirectInfo) {
68007                     continue;
68008                 }
68009                 if (!ts.isExternalOrCommonJsModule(file)) {
68010                     // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
68011                     // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
68012                     var fileGlobalThisSymbol = file.locals.get("globalThis");
68013                     if (fileGlobalThisSymbol) {
68014                         for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
68015                             var declaration = _e[_d];
68016                             diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
68017                         }
68018                     }
68019                     mergeSymbolTable(globals, file.locals);
68020                 }
68021                 if (file.jsGlobalAugmentations) {
68022                     mergeSymbolTable(globals, file.jsGlobalAugmentations);
68023                 }
68024                 if (file.patternAmbientModules && file.patternAmbientModules.length) {
68025                     patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
68026                 }
68027                 if (file.moduleAugmentations.length) {
68028                     (augmentations || (augmentations = [])).push(file.moduleAugmentations);
68029                 }
68030                 if (file.symbol && file.symbol.globalExports) {
68031                     // Merge in UMD exports with first-in-wins semantics (see #9771)
68032                     var source = file.symbol.globalExports;
68033                     source.forEach(function (sourceSymbol, id) {
68034                         if (!globals.has(id)) {
68035                             globals.set(id, sourceSymbol);
68036                         }
68037                     });
68038                 }
68039             }
68040             // We do global augmentations separately from module augmentations (and before creating global types) because they
68041             //  1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
68042             //  2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
68043             //       checking for an export or property on the module (if export=) which, in turn, can fall back to the
68044             //       apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
68045             //       did module augmentations prior to finalizing the global types.
68046             if (augmentations) {
68047                 // merge _global_ module augmentations.
68048                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68049                 for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
68050                     var list = augmentations_1[_f];
68051                     for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
68052                         var augmentation = list_1[_g];
68053                         if (!ts.isGlobalScopeAugmentation(augmentation.parent))
68054                             continue;
68055                         mergeModuleAugmentation(augmentation);
68056                     }
68057                 }
68058             }
68059             // Setup global builtins
68060             addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
68061             getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
68062             getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
68063             getSymbolLinks(unknownSymbol).type = errorType;
68064             getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
68065             // Initialize special types
68066             globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
68067             globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
68068             globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
68069             globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68070             globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68071             globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
68072             globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
68073             globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
68074             globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
68075             anyArrayType = createArrayType(anyType);
68076             autoArrayType = createArrayType(autoType);
68077             if (autoArrayType === emptyObjectType) {
68078                 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
68079                 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
68080             }
68081             globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
68082             anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
68083             globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
68084             if (augmentations) {
68085                 // merge _nonglobal_ module augmentations.
68086                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68087                 for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
68088                     var list = augmentations_2[_h];
68089                     for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
68090                         var augmentation = list_2[_j];
68091                         if (ts.isGlobalScopeAugmentation(augmentation.parent))
68092                             continue;
68093                         mergeModuleAugmentation(augmentation);
68094                     }
68095                 }
68096             }
68097             amalgamatedDuplicates.forEach(function (_a) {
68098                 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
68099                 // If not many things conflict, issue individual errors
68100                 if (conflictingSymbols.size < 8) {
68101                     conflictingSymbols.forEach(function (_a, symbolName) {
68102                         var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
68103                         var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
68104                         for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
68105                             var node = firstFileLocations_1[_i];
68106                             addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
68107                         }
68108                         for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
68109                             var node = secondFileLocations_1[_b];
68110                             addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
68111                         }
68112                     });
68113                 }
68114                 else {
68115                     // Otherwise issue top-level error since the files appear very identical in terms of what they contain
68116                     var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
68117                     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)));
68118                     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)));
68119                 }
68120             });
68121             amalgamatedDuplicates = undefined;
68122         }
68123         function checkExternalEmitHelpers(location, helpers) {
68124             if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
68125                 var sourceFile = ts.getSourceFileOfNode(location);
68126                 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
68127                     var helpersModule = resolveHelpersModule(sourceFile, location);
68128                     if (helpersModule !== unknownSymbol) {
68129                         var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
68130                         for (var helper = 1 /* FirstEmitHelper */; helper <= 1048576 /* LastEmitHelper */; helper <<= 1) {
68131                             if (uncheckedHelpers & helper) {
68132                                 var name = getHelperName(helper);
68133                                 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
68134                                 if (!symbol) {
68135                                     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);
68136                                 }
68137                             }
68138                         }
68139                     }
68140                     requestedExternalEmitHelpers |= helpers;
68141                 }
68142             }
68143         }
68144         function getHelperName(helper) {
68145             switch (helper) {
68146                 case 1 /* Extends */: return "__extends";
68147                 case 2 /* Assign */: return "__assign";
68148                 case 4 /* Rest */: return "__rest";
68149                 case 8 /* Decorate */: return "__decorate";
68150                 case 16 /* Metadata */: return "__metadata";
68151                 case 32 /* Param */: return "__param";
68152                 case 64 /* Awaiter */: return "__awaiter";
68153                 case 128 /* Generator */: return "__generator";
68154                 case 256 /* Values */: return "__values";
68155                 case 512 /* Read */: return "__read";
68156                 case 1024 /* Spread */: return "__spread";
68157                 case 2048 /* SpreadArrays */: return "__spreadArrays";
68158                 case 4096 /* Await */: return "__await";
68159                 case 8192 /* AsyncGenerator */: return "__asyncGenerator";
68160                 case 16384 /* AsyncDelegator */: return "__asyncDelegator";
68161                 case 32768 /* AsyncValues */: return "__asyncValues";
68162                 case 65536 /* ExportStar */: return "__exportStar";
68163                 case 131072 /* MakeTemplateObject */: return "__makeTemplateObject";
68164                 case 262144 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
68165                 case 524288 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
68166                 case 1048576 /* CreateBinding */: return "__createBinding";
68167                 default: return ts.Debug.fail("Unrecognized helper");
68168             }
68169         }
68170         function resolveHelpersModule(node, errorNode) {
68171             if (!externalHelpersModule) {
68172                 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
68173             }
68174             return externalHelpersModule;
68175         }
68176         // GRAMMAR CHECKING
68177         function checkGrammarDecoratorsAndModifiers(node) {
68178             return checkGrammarDecorators(node) || checkGrammarModifiers(node);
68179         }
68180         function checkGrammarDecorators(node) {
68181             if (!node.decorators) {
68182                 return false;
68183             }
68184             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
68185                 if (node.kind === 161 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
68186                     return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
68187                 }
68188                 else {
68189                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
68190                 }
68191             }
68192             else if (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */) {
68193                 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
68194                 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
68195                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
68196                 }
68197             }
68198             return false;
68199         }
68200         function checkGrammarModifiers(node) {
68201             var quickResult = reportObviousModifierErrors(node);
68202             if (quickResult !== undefined) {
68203                 return quickResult;
68204             }
68205             var lastStatic, lastDeclare, lastAsync, lastReadonly;
68206             var flags = 0 /* None */;
68207             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
68208                 var modifier = _a[_i];
68209                 if (modifier.kind !== 138 /* ReadonlyKeyword */) {
68210                     if (node.kind === 158 /* PropertySignature */ || node.kind === 160 /* MethodSignature */) {
68211                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
68212                     }
68213                     if (node.kind === 167 /* IndexSignature */) {
68214                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
68215                     }
68216                 }
68217                 switch (modifier.kind) {
68218                     case 81 /* ConstKeyword */:
68219                         if (node.kind !== 248 /* EnumDeclaration */) {
68220                             return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(81 /* ConstKeyword */));
68221                         }
68222                         break;
68223                     case 119 /* PublicKeyword */:
68224                     case 118 /* ProtectedKeyword */:
68225                     case 117 /* PrivateKeyword */:
68226                         var text = visibilityToString(ts.modifierToFlag(modifier.kind));
68227                         if (flags & 28 /* AccessibilityModifier */) {
68228                             return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
68229                         }
68230                         else if (flags & 32 /* Static */) {
68231                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
68232                         }
68233                         else if (flags & 64 /* Readonly */) {
68234                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
68235                         }
68236                         else if (flags & 256 /* Async */) {
68237                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
68238                         }
68239                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68240                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
68241                         }
68242                         else if (flags & 128 /* Abstract */) {
68243                             if (modifier.kind === 117 /* PrivateKeyword */) {
68244                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
68245                             }
68246                             else {
68247                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
68248                             }
68249                         }
68250                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68251                             return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
68252                         }
68253                         flags |= ts.modifierToFlag(modifier.kind);
68254                         break;
68255                     case 120 /* StaticKeyword */:
68256                         if (flags & 32 /* Static */) {
68257                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
68258                         }
68259                         else if (flags & 64 /* Readonly */) {
68260                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
68261                         }
68262                         else if (flags & 256 /* Async */) {
68263                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
68264                         }
68265                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68266                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
68267                         }
68268                         else if (node.kind === 156 /* Parameter */) {
68269                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
68270                         }
68271                         else if (flags & 128 /* Abstract */) {
68272                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68273                         }
68274                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68275                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static");
68276                         }
68277                         flags |= 32 /* Static */;
68278                         lastStatic = modifier;
68279                         break;
68280                     case 138 /* ReadonlyKeyword */:
68281                         if (flags & 64 /* Readonly */) {
68282                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
68283                         }
68284                         else if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */ && node.kind !== 167 /* IndexSignature */ && node.kind !== 156 /* Parameter */) {
68285                             // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
68286                             return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
68287                         }
68288                         flags |= 64 /* Readonly */;
68289                         lastReadonly = modifier;
68290                         break;
68291                     case 89 /* ExportKeyword */:
68292                         if (flags & 1 /* Export */) {
68293                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
68294                         }
68295                         else if (flags & 2 /* Ambient */) {
68296                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
68297                         }
68298                         else if (flags & 128 /* Abstract */) {
68299                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
68300                         }
68301                         else if (flags & 256 /* Async */) {
68302                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
68303                         }
68304                         else if (ts.isClassLike(node.parent)) {
68305                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export");
68306                         }
68307                         else if (node.kind === 156 /* Parameter */) {
68308                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
68309                         }
68310                         flags |= 1 /* Export */;
68311                         break;
68312                     case 84 /* DefaultKeyword */:
68313                         var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
68314                         if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
68315                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
68316                         }
68317                         flags |= 512 /* Default */;
68318                         break;
68319                     case 130 /* DeclareKeyword */:
68320                         if (flags & 2 /* Ambient */) {
68321                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
68322                         }
68323                         else if (flags & 256 /* Async */) {
68324                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68325                         }
68326                         else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
68327                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
68328                         }
68329                         else if (node.kind === 156 /* Parameter */) {
68330                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
68331                         }
68332                         else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 250 /* ModuleBlock */) {
68333                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
68334                         }
68335                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68336                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
68337                         }
68338                         flags |= 2 /* Ambient */;
68339                         lastDeclare = modifier;
68340                         break;
68341                     case 122 /* AbstractKeyword */:
68342                         if (flags & 128 /* Abstract */) {
68343                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
68344                         }
68345                         if (node.kind !== 245 /* ClassDeclaration */) {
68346                             if (node.kind !== 161 /* MethodDeclaration */ &&
68347                                 node.kind !== 159 /* PropertyDeclaration */ &&
68348                                 node.kind !== 163 /* GetAccessor */ &&
68349                                 node.kind !== 164 /* SetAccessor */) {
68350                                 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
68351                             }
68352                             if (!(node.parent.kind === 245 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) {
68353                                 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
68354                             }
68355                             if (flags & 32 /* Static */) {
68356                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68357                             }
68358                             if (flags & 8 /* Private */) {
68359                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
68360                             }
68361                         }
68362                         if (ts.isNamedDeclaration(node) && node.name.kind === 76 /* PrivateIdentifier */) {
68363                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
68364                         }
68365                         flags |= 128 /* Abstract */;
68366                         break;
68367                     case 126 /* AsyncKeyword */:
68368                         if (flags & 256 /* Async */) {
68369                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
68370                         }
68371                         else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
68372                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68373                         }
68374                         else if (node.kind === 156 /* Parameter */) {
68375                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
68376                         }
68377                         flags |= 256 /* Async */;
68378                         lastAsync = modifier;
68379                         break;
68380                 }
68381             }
68382             if (node.kind === 162 /* Constructor */) {
68383                 if (flags & 32 /* Static */) {
68384                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
68385                 }
68386                 if (flags & 128 /* Abstract */) {
68387                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
68388                 }
68389                 else if (flags & 256 /* Async */) {
68390                     return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
68391                 }
68392                 else if (flags & 64 /* Readonly */) {
68393                     return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
68394                 }
68395                 return false;
68396             }
68397             else if ((node.kind === 254 /* ImportDeclaration */ || node.kind === 253 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
68398                 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
68399             }
68400             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
68401                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
68402             }
68403             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
68404                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
68405             }
68406             if (flags & 256 /* Async */) {
68407                 return checkGrammarAsyncModifier(node, lastAsync);
68408             }
68409             return false;
68410         }
68411         /**
68412          * true | false: Early return this value from checkGrammarModifiers.
68413          * undefined: Need to do full checking on the modifiers.
68414          */
68415         function reportObviousModifierErrors(node) {
68416             return !node.modifiers
68417                 ? false
68418                 : shouldReportBadModifier(node)
68419                     ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
68420                     : undefined;
68421         }
68422         function shouldReportBadModifier(node) {
68423             switch (node.kind) {
68424                 case 163 /* GetAccessor */:
68425                 case 164 /* SetAccessor */:
68426                 case 162 /* Constructor */:
68427                 case 159 /* PropertyDeclaration */:
68428                 case 158 /* PropertySignature */:
68429                 case 161 /* MethodDeclaration */:
68430                 case 160 /* MethodSignature */:
68431                 case 167 /* IndexSignature */:
68432                 case 249 /* ModuleDeclaration */:
68433                 case 254 /* ImportDeclaration */:
68434                 case 253 /* ImportEqualsDeclaration */:
68435                 case 260 /* ExportDeclaration */:
68436                 case 259 /* ExportAssignment */:
68437                 case 201 /* FunctionExpression */:
68438                 case 202 /* ArrowFunction */:
68439                 case 156 /* Parameter */:
68440                     return false;
68441                 default:
68442                     if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68443                         return false;
68444                     }
68445                     switch (node.kind) {
68446                         case 244 /* FunctionDeclaration */:
68447                             return nodeHasAnyModifiersExcept(node, 126 /* AsyncKeyword */);
68448                         case 245 /* ClassDeclaration */:
68449                             return nodeHasAnyModifiersExcept(node, 122 /* AbstractKeyword */);
68450                         case 246 /* InterfaceDeclaration */:
68451                         case 225 /* VariableStatement */:
68452                         case 247 /* TypeAliasDeclaration */:
68453                             return true;
68454                         case 248 /* EnumDeclaration */:
68455                             return nodeHasAnyModifiersExcept(node, 81 /* ConstKeyword */);
68456                         default:
68457                             ts.Debug.fail();
68458                             return false;
68459                     }
68460             }
68461         }
68462         function nodeHasAnyModifiersExcept(node, allowedModifier) {
68463             return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
68464         }
68465         function checkGrammarAsyncModifier(node, asyncModifier) {
68466             switch (node.kind) {
68467                 case 161 /* MethodDeclaration */:
68468                 case 244 /* FunctionDeclaration */:
68469                 case 201 /* FunctionExpression */:
68470                 case 202 /* ArrowFunction */:
68471                     return false;
68472             }
68473             return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
68474         }
68475         function checkGrammarForDisallowedTrailingComma(list, diag) {
68476             if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
68477             if (list && list.hasTrailingComma) {
68478                 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
68479             }
68480             return false;
68481         }
68482         function checkGrammarTypeParameterList(typeParameters, file) {
68483             if (typeParameters && typeParameters.length === 0) {
68484                 var start = typeParameters.pos - "<".length;
68485                 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
68486                 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
68487             }
68488             return false;
68489         }
68490         function checkGrammarParameterList(parameters) {
68491             var seenOptionalParameter = false;
68492             var parameterCount = parameters.length;
68493             for (var i = 0; i < parameterCount; i++) {
68494                 var parameter = parameters[i];
68495                 if (parameter.dotDotDotToken) {
68496                     if (i !== (parameterCount - 1)) {
68497                         return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
68498                     }
68499                     if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
68500                         checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
68501                     }
68502                     if (parameter.questionToken) {
68503                         return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
68504                     }
68505                     if (parameter.initializer) {
68506                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
68507                     }
68508                 }
68509                 else if (parameter.questionToken) {
68510                     seenOptionalParameter = true;
68511                     if (parameter.initializer) {
68512                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
68513                     }
68514                 }
68515                 else if (seenOptionalParameter && !parameter.initializer) {
68516                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
68517                 }
68518             }
68519         }
68520         function getNonSimpleParameters(parameters) {
68521             return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
68522         }
68523         function checkGrammarForUseStrictSimpleParameterList(node) {
68524             if (languageVersion >= 3 /* ES2016 */) {
68525                 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
68526                 if (useStrictDirective_1) {
68527                     var nonSimpleParameters = getNonSimpleParameters(node.parameters);
68528                     if (ts.length(nonSimpleParameters)) {
68529                         ts.forEach(nonSimpleParameters, function (parameter) {
68530                             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));
68531                         });
68532                         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)); });
68533                         ts.addRelatedInfo.apply(void 0, __spreadArrays([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_1));
68534                         return true;
68535                     }
68536                 }
68537             }
68538             return false;
68539         }
68540         function checkGrammarFunctionLikeDeclaration(node) {
68541             // Prevent cascading error by short-circuit
68542             var file = ts.getSourceFileOfNode(node);
68543             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
68544                 checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) ||
68545                 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
68546         }
68547         function checkGrammarClassLikeDeclaration(node) {
68548             var file = ts.getSourceFileOfNode(node);
68549             return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
68550         }
68551         function checkGrammarArrowFunction(node, file) {
68552             if (!ts.isArrowFunction(node)) {
68553                 return false;
68554             }
68555             var equalsGreaterThanToken = node.equalsGreaterThanToken;
68556             var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
68557             var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
68558             return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
68559         }
68560         function checkGrammarIndexSignatureParameters(node) {
68561             var parameter = node.parameters[0];
68562             if (node.parameters.length !== 1) {
68563                 if (parameter) {
68564                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68565                 }
68566                 else {
68567                     return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68568                 }
68569             }
68570             checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
68571             if (parameter.dotDotDotToken) {
68572                 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
68573             }
68574             if (ts.hasModifiers(parameter)) {
68575                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
68576             }
68577             if (parameter.questionToken) {
68578                 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
68579             }
68580             if (parameter.initializer) {
68581                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
68582             }
68583             if (!parameter.type) {
68584                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
68585             }
68586             if (parameter.type.kind !== 143 /* StringKeyword */ && parameter.type.kind !== 140 /* NumberKeyword */) {
68587                 var type = getTypeFromTypeNode(parameter.type);
68588                 if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
68589                     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));
68590                 }
68591                 if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) {
68592                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
68593                 }
68594                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number);
68595             }
68596             if (!node.type) {
68597                 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
68598             }
68599             return false;
68600         }
68601         function checkGrammarIndexSignature(node) {
68602             // Prevent cascading error by short-circuit
68603             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
68604         }
68605         function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
68606             if (typeArguments && typeArguments.length === 0) {
68607                 var sourceFile = ts.getSourceFileOfNode(node);
68608                 var start = typeArguments.pos - "<".length;
68609                 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
68610                 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
68611             }
68612             return false;
68613         }
68614         function checkGrammarTypeArguments(node, typeArguments) {
68615             return checkGrammarForDisallowedTrailingComma(typeArguments) ||
68616                 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
68617         }
68618         function checkGrammarTaggedTemplateChain(node) {
68619             if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
68620                 return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
68621             }
68622             return false;
68623         }
68624         function checkGrammarForOmittedArgument(args) {
68625             if (args) {
68626                 for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
68627                     var arg = args_4[_i];
68628                     if (arg.kind === 215 /* OmittedExpression */) {
68629                         return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
68630                     }
68631                 }
68632             }
68633             return false;
68634         }
68635         function checkGrammarArguments(args) {
68636             return checkGrammarForOmittedArgument(args);
68637         }
68638         function checkGrammarHeritageClause(node) {
68639             var types = node.types;
68640             if (checkGrammarForDisallowedTrailingComma(types)) {
68641                 return true;
68642             }
68643             if (types && types.length === 0) {
68644                 var listType = ts.tokenToString(node.token);
68645                 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
68646             }
68647             return ts.some(types, checkGrammarExpressionWithTypeArguments);
68648         }
68649         function checkGrammarExpressionWithTypeArguments(node) {
68650             return checkGrammarTypeArguments(node, node.typeArguments);
68651         }
68652         function checkGrammarClassDeclarationHeritageClauses(node) {
68653             var seenExtendsClause = false;
68654             var seenImplementsClause = false;
68655             if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
68656                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68657                     var heritageClause = _a[_i];
68658                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68659                         if (seenExtendsClause) {
68660                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68661                         }
68662                         if (seenImplementsClause) {
68663                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
68664                         }
68665                         if (heritageClause.types.length > 1) {
68666                             return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
68667                         }
68668                         seenExtendsClause = true;
68669                     }
68670                     else {
68671                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68672                         if (seenImplementsClause) {
68673                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
68674                         }
68675                         seenImplementsClause = true;
68676                     }
68677                     // Grammar checking heritageClause inside class declaration
68678                     checkGrammarHeritageClause(heritageClause);
68679                 }
68680             }
68681         }
68682         function checkGrammarInterfaceDeclaration(node) {
68683             var seenExtendsClause = false;
68684             if (node.heritageClauses) {
68685                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68686                     var heritageClause = _a[_i];
68687                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68688                         if (seenExtendsClause) {
68689                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68690                         }
68691                         seenExtendsClause = true;
68692                     }
68693                     else {
68694                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68695                         return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
68696                     }
68697                     // Grammar checking heritageClause inside class declaration
68698                     checkGrammarHeritageClause(heritageClause);
68699                 }
68700             }
68701             return false;
68702         }
68703         function checkGrammarComputedPropertyName(node) {
68704             // If node is not a computedPropertyName, just skip the grammar checking
68705             if (node.kind !== 154 /* ComputedPropertyName */) {
68706                 return false;
68707             }
68708             var computedPropertyName = node;
68709             if (computedPropertyName.expression.kind === 209 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
68710                 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
68711             }
68712             return false;
68713         }
68714         function checkGrammarForGenerator(node) {
68715             if (node.asteriskToken) {
68716                 ts.Debug.assert(node.kind === 244 /* FunctionDeclaration */ ||
68717                     node.kind === 201 /* FunctionExpression */ ||
68718                     node.kind === 161 /* MethodDeclaration */);
68719                 if (node.flags & 8388608 /* Ambient */) {
68720                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
68721                 }
68722                 if (!node.body) {
68723                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
68724                 }
68725             }
68726         }
68727         function checkGrammarForInvalidQuestionMark(questionToken, message) {
68728             return !!questionToken && grammarErrorOnNode(questionToken, message);
68729         }
68730         function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
68731             return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
68732         }
68733         function checkGrammarObjectLiteralExpression(node, inDestructuring) {
68734             var seen = ts.createUnderscoreEscapedMap();
68735             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
68736                 var prop = _a[_i];
68737                 if (prop.kind === 283 /* SpreadAssignment */) {
68738                     if (inDestructuring) {
68739                         // a rest property cannot be destructured any further
68740                         var expression = ts.skipParentheses(prop.expression);
68741                         if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
68742                             return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
68743                         }
68744                     }
68745                     continue;
68746                 }
68747                 var name = prop.name;
68748                 if (name.kind === 154 /* ComputedPropertyName */) {
68749                     // If the name is not a ComputedPropertyName, the grammar checking will skip it
68750                     checkGrammarComputedPropertyName(name);
68751                 }
68752                 if (prop.kind === 282 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
68753                     // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
68754                     // outside of destructuring it is a syntax error
68755                     return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
68756                 }
68757                 if (name.kind === 76 /* PrivateIdentifier */) {
68758                     return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
68759                 }
68760                 // Modifiers are never allowed on properties except for 'async' on a method declaration
68761                 if (prop.modifiers) {
68762                     // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
68763                     for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
68764                         var mod = _c[_b];
68765                         if (mod.kind !== 126 /* AsyncKeyword */ || prop.kind !== 161 /* MethodDeclaration */) {
68766                             grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
68767                         }
68768                     }
68769                 }
68770                 // ECMA-262 11.1.5 Object Initializer
68771                 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
68772                 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
68773                 // IsDataDescriptor(propId.descriptor) is true.
68774                 //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
68775                 //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
68776                 //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
68777                 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
68778                 var currentKind = void 0;
68779                 switch (prop.kind) {
68780                     case 282 /* ShorthandPropertyAssignment */:
68781                         checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
68782                     // falls through
68783                     case 281 /* PropertyAssignment */:
68784                         // Grammar checking for computedPropertyName and shorthandPropertyAssignment
68785                         checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
68786                         if (name.kind === 8 /* NumericLiteral */) {
68787                             checkGrammarNumericLiteral(name);
68788                         }
68789                         currentKind = 4 /* PropertyAssignment */;
68790                         break;
68791                     case 161 /* MethodDeclaration */:
68792                         currentKind = 8 /* Method */;
68793                         break;
68794                     case 163 /* GetAccessor */:
68795                         currentKind = 1 /* GetAccessor */;
68796                         break;
68797                     case 164 /* SetAccessor */:
68798                         currentKind = 2 /* SetAccessor */;
68799                         break;
68800                     default:
68801                         throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
68802                 }
68803                 if (!inDestructuring) {
68804                     var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
68805                     if (effectiveName === undefined) {
68806                         continue;
68807                     }
68808                     var existingKind = seen.get(effectiveName);
68809                     if (!existingKind) {
68810                         seen.set(effectiveName, currentKind);
68811                     }
68812                     else {
68813                         if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
68814                             grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
68815                         }
68816                         else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
68817                             if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
68818                                 seen.set(effectiveName, currentKind | existingKind);
68819                             }
68820                             else {
68821                                 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
68822                             }
68823                         }
68824                         else {
68825                             return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
68826                         }
68827                     }
68828                 }
68829             }
68830         }
68831         function checkGrammarJsxElement(node) {
68832             checkGrammarTypeArguments(node, node.typeArguments);
68833             var seen = ts.createUnderscoreEscapedMap();
68834             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
68835                 var attr = _a[_i];
68836                 if (attr.kind === 275 /* JsxSpreadAttribute */) {
68837                     continue;
68838                 }
68839                 var name = attr.name, initializer = attr.initializer;
68840                 if (!seen.get(name.escapedText)) {
68841                     seen.set(name.escapedText, true);
68842                 }
68843                 else {
68844                     return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
68845                 }
68846                 if (initializer && initializer.kind === 276 /* JsxExpression */ && !initializer.expression) {
68847                     return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
68848                 }
68849             }
68850         }
68851         function checkGrammarJsxExpression(node) {
68852             if (node.expression && ts.isCommaSequence(node.expression)) {
68853                 return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
68854             }
68855         }
68856         function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
68857             if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
68858                 return true;
68859             }
68860             if (forInOrOfStatement.kind === 232 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
68861                 if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) {
68862                     // use of 'for-await-of' in non-async function
68863                     var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
68864                     if (!hasParseDiagnostics(sourceFile)) {
68865                         var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
68866                         var func = ts.getContainingFunction(forInOrOfStatement);
68867                         if (func && func.kind !== 162 /* Constructor */) {
68868                             ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
68869                             var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
68870                             ts.addRelatedInfo(diagnostic, relatedInfo);
68871                         }
68872                         diagnostics.add(diagnostic);
68873                         return true;
68874                     }
68875                     return false;
68876                 }
68877             }
68878             if (forInOrOfStatement.initializer.kind === 243 /* VariableDeclarationList */) {
68879                 var variableList = forInOrOfStatement.initializer;
68880                 if (!checkGrammarVariableDeclarationList(variableList)) {
68881                     var declarations = variableList.declarations;
68882                     // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
68883                     // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
68884                     // For example:
68885                     //      var let = 10;
68886                     //      for (let of [1,2,3]) {} // this is invalid ES6 syntax
68887                     //      for (let in [1,2,3]) {} // this is invalid ES6 syntax
68888                     // We will then want to skip on grammar checking on variableList declaration
68889                     if (!declarations.length) {
68890                         return false;
68891                     }
68892                     if (declarations.length > 1) {
68893                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68894                             ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
68895                             : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
68896                         return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
68897                     }
68898                     var firstDeclaration = declarations[0];
68899                     if (firstDeclaration.initializer) {
68900                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68901                             ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
68902                             : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
68903                         return grammarErrorOnNode(firstDeclaration.name, diagnostic);
68904                     }
68905                     if (firstDeclaration.type) {
68906                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68907                             ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
68908                             : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
68909                         return grammarErrorOnNode(firstDeclaration, diagnostic);
68910                     }
68911                 }
68912             }
68913             return false;
68914         }
68915         function checkGrammarAccessor(accessor) {
68916             if (!(accessor.flags & 8388608 /* Ambient */)) {
68917                 if (languageVersion < 1 /* ES5 */) {
68918                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
68919                 }
68920                 if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) {
68921                     return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
68922                 }
68923             }
68924             if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) {
68925                 return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
68926             }
68927             if (accessor.typeParameters) {
68928                 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
68929             }
68930             if (!doesAccessorHaveCorrectParameterCount(accessor)) {
68931                 return grammarErrorOnNode(accessor.name, accessor.kind === 163 /* GetAccessor */ ?
68932                     ts.Diagnostics.A_get_accessor_cannot_have_parameters :
68933                     ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
68934             }
68935             if (accessor.kind === 164 /* SetAccessor */) {
68936                 if (accessor.type) {
68937                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
68938                 }
68939                 var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
68940                 if (parameter.dotDotDotToken) {
68941                     return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
68942                 }
68943                 if (parameter.questionToken) {
68944                     return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
68945                 }
68946                 if (parameter.initializer) {
68947                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
68948                 }
68949             }
68950             return false;
68951         }
68952         /** Does the accessor have the right number of parameters?
68953          * A get accessor has no parameters or a single `this` parameter.
68954          * A set accessor has one parameter or a `this` parameter and one more parameter.
68955          */
68956         function doesAccessorHaveCorrectParameterCount(accessor) {
68957             return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 0 : 1);
68958         }
68959         function getAccessorThisParameter(accessor) {
68960             if (accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 1 : 2)) {
68961                 return ts.getThisParameter(accessor);
68962             }
68963         }
68964         function checkGrammarTypeOperatorNode(node) {
68965             if (node.operator === 147 /* UniqueKeyword */) {
68966                 if (node.type.kind !== 144 /* SymbolKeyword */) {
68967                     return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(144 /* SymbolKeyword */));
68968                 }
68969                 var parent = ts.walkUpParenthesizedTypes(node.parent);
68970                 switch (parent.kind) {
68971                     case 242 /* VariableDeclaration */:
68972                         var decl = parent;
68973                         if (decl.name.kind !== 75 /* Identifier */) {
68974                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
68975                         }
68976                         if (!ts.isVariableDeclarationInVariableStatement(decl)) {
68977                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
68978                         }
68979                         if (!(decl.parent.flags & 2 /* Const */)) {
68980                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
68981                         }
68982                         break;
68983                     case 159 /* PropertyDeclaration */:
68984                         if (!ts.hasModifier(parent, 32 /* Static */) ||
68985                             !ts.hasModifier(parent, 64 /* Readonly */)) {
68986                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
68987                         }
68988                         break;
68989                     case 158 /* PropertySignature */:
68990                         if (!ts.hasModifier(parent, 64 /* Readonly */)) {
68991                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
68992                         }
68993                         break;
68994                     default:
68995                         return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
68996                 }
68997             }
68998             else if (node.operator === 138 /* ReadonlyKeyword */) {
68999                 if (node.type.kind !== 174 /* ArrayType */ && node.type.kind !== 175 /* TupleType */) {
69000                     return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(144 /* SymbolKeyword */));
69001                 }
69002             }
69003         }
69004         function checkGrammarForInvalidDynamicName(node, message) {
69005             if (isNonBindableDynamicName(node)) {
69006                 return grammarErrorOnNode(node, message);
69007             }
69008         }
69009         function checkGrammarMethod(node) {
69010             if (checkGrammarFunctionLikeDeclaration(node)) {
69011                 return true;
69012             }
69013             if (node.kind === 161 /* MethodDeclaration */) {
69014                 if (node.parent.kind === 193 /* ObjectLiteralExpression */) {
69015                     // We only disallow modifier on a method declaration if it is a property of object-literal-expression
69016                     if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 126 /* AsyncKeyword */)) {
69017                         return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
69018                     }
69019                     else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
69020                         return true;
69021                     }
69022                     else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
69023                         return true;
69024                     }
69025                     else if (node.body === undefined) {
69026                         return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
69027                     }
69028                 }
69029                 if (checkGrammarForGenerator(node)) {
69030                     return true;
69031                 }
69032             }
69033             if (ts.isClassLike(node.parent)) {
69034                 // Technically, computed properties in ambient contexts is disallowed
69035                 // for property declarations and accessors too, not just methods.
69036                 // However, property declarations disallow computed names in general,
69037                 // and accessors are not allowed in ambient contexts in general,
69038                 // so this error only really matters for methods.
69039                 if (node.flags & 8388608 /* Ambient */) {
69040                     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);
69041                 }
69042                 else if (node.kind === 161 /* MethodDeclaration */ && !node.body) {
69043                     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);
69044                 }
69045             }
69046             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69047                 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);
69048             }
69049             else if (node.parent.kind === 173 /* TypeLiteral */) {
69050                 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);
69051             }
69052         }
69053         function checkGrammarBreakOrContinueStatement(node) {
69054             var current = node;
69055             while (current) {
69056                 if (ts.isFunctionLike(current)) {
69057                     return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
69058                 }
69059                 switch (current.kind) {
69060                     case 238 /* LabeledStatement */:
69061                         if (node.label && current.label.escapedText === node.label.escapedText) {
69062                             // found matching label - verify that label usage is correct
69063                             // continue can only target labels that are on iteration statements
69064                             var isMisplacedContinueLabel = node.kind === 233 /* ContinueStatement */
69065                                 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
69066                             if (isMisplacedContinueLabel) {
69067                                 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
69068                             }
69069                             return false;
69070                         }
69071                         break;
69072                     case 237 /* SwitchStatement */:
69073                         if (node.kind === 234 /* BreakStatement */ && !node.label) {
69074                             // unlabeled break within switch statement - ok
69075                             return false;
69076                         }
69077                         break;
69078                     default:
69079                         if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
69080                             // unlabeled break or continue within iteration statement - ok
69081                             return false;
69082                         }
69083                         break;
69084                 }
69085                 current = current.parent;
69086             }
69087             if (node.label) {
69088                 var message = node.kind === 234 /* BreakStatement */
69089                     ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
69090                     : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
69091                 return grammarErrorOnNode(node, message);
69092             }
69093             else {
69094                 var message = node.kind === 234 /* BreakStatement */
69095                     ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
69096                     : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
69097                 return grammarErrorOnNode(node, message);
69098             }
69099         }
69100         function checkGrammarBindingElement(node) {
69101             if (node.dotDotDotToken) {
69102                 var elements = node.parent.elements;
69103                 if (node !== ts.last(elements)) {
69104                     return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
69105                 }
69106                 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
69107                 if (node.propertyName) {
69108                     return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
69109                 }
69110                 if (node.initializer) {
69111                     // Error on equals token which immediately precedes the initializer
69112                     return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
69113                 }
69114             }
69115         }
69116         function isStringOrNumberLiteralExpression(expr) {
69117             return ts.isStringOrNumericLiteralLike(expr) ||
69118                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69119                     expr.operand.kind === 8 /* NumericLiteral */;
69120         }
69121         function isBigIntLiteralExpression(expr) {
69122             return expr.kind === 9 /* BigIntLiteral */ ||
69123                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69124                     expr.operand.kind === 9 /* BigIntLiteral */;
69125         }
69126         function isSimpleLiteralEnumReference(expr) {
69127             if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
69128                 ts.isEntityNameExpression(expr.expression)) {
69129                 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
69130             }
69131         }
69132         function checkAmbientInitializer(node) {
69133             var initializer = node.initializer;
69134             if (initializer) {
69135                 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
69136                     isSimpleLiteralEnumReference(initializer) ||
69137                     initializer.kind === 106 /* TrueKeyword */ || initializer.kind === 91 /* FalseKeyword */ ||
69138                     isBigIntLiteralExpression(initializer));
69139                 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
69140                 if (isConstOrReadonly && !node.type) {
69141                     if (isInvalidInitializer) {
69142                         return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
69143                     }
69144                 }
69145                 else {
69146                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69147                 }
69148                 if (!isConstOrReadonly || isInvalidInitializer) {
69149                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69150                 }
69151             }
69152         }
69153         function checkGrammarVariableDeclaration(node) {
69154             if (node.parent.parent.kind !== 231 /* ForInStatement */ && node.parent.parent.kind !== 232 /* ForOfStatement */) {
69155                 if (node.flags & 8388608 /* Ambient */) {
69156                     checkAmbientInitializer(node);
69157                 }
69158                 else if (!node.initializer) {
69159                     if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
69160                         return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
69161                     }
69162                     if (ts.isVarConst(node)) {
69163                         return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
69164                     }
69165                 }
69166             }
69167             if (node.exclamationToken && (node.parent.parent.kind !== 225 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
69168                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation);
69169             }
69170             var moduleKind = ts.getEmitModuleKind(compilerOptions);
69171             if (moduleKind < ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System && !compilerOptions.noEmit &&
69172                 !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) {
69173                 checkESModuleMarker(node.name);
69174             }
69175             var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
69176             // 1. LexicalDeclaration : LetOrConst BindingList ;
69177             // It is a Syntax Error if the BoundNames of BindingList contains "let".
69178             // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
69179             // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
69180             // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
69181             // and its Identifier is eval or arguments
69182             return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
69183         }
69184         function checkESModuleMarker(name) {
69185             if (name.kind === 75 /* Identifier */) {
69186                 if (ts.idText(name) === "__esModule") {
69187                     return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
69188                 }
69189             }
69190             else {
69191                 var elements = name.elements;
69192                 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
69193                     var element = elements_1[_i];
69194                     if (!ts.isOmittedExpression(element)) {
69195                         return checkESModuleMarker(element.name);
69196                     }
69197                 }
69198             }
69199             return false;
69200         }
69201         function checkGrammarNameInLetOrConstDeclarations(name) {
69202             if (name.kind === 75 /* Identifier */) {
69203                 if (name.originalKeywordKind === 115 /* LetKeyword */) {
69204                     return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
69205                 }
69206             }
69207             else {
69208                 var elements = name.elements;
69209                 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
69210                     var element = elements_2[_i];
69211                     if (!ts.isOmittedExpression(element)) {
69212                         checkGrammarNameInLetOrConstDeclarations(element.name);
69213                     }
69214                 }
69215             }
69216             return false;
69217         }
69218         function checkGrammarVariableDeclarationList(declarationList) {
69219             var declarations = declarationList.declarations;
69220             if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
69221                 return true;
69222             }
69223             if (!declarationList.declarations.length) {
69224                 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
69225             }
69226             return false;
69227         }
69228         function allowLetAndConstDeclarations(parent) {
69229             switch (parent.kind) {
69230                 case 227 /* IfStatement */:
69231                 case 228 /* DoStatement */:
69232                 case 229 /* WhileStatement */:
69233                 case 236 /* WithStatement */:
69234                 case 230 /* ForStatement */:
69235                 case 231 /* ForInStatement */:
69236                 case 232 /* ForOfStatement */:
69237                     return false;
69238                 case 238 /* LabeledStatement */:
69239                     return allowLetAndConstDeclarations(parent.parent);
69240             }
69241             return true;
69242         }
69243         function checkGrammarForDisallowedLetOrConstStatement(node) {
69244             if (!allowLetAndConstDeclarations(node.parent)) {
69245                 if (ts.isLet(node.declarationList)) {
69246                     return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
69247                 }
69248                 else if (ts.isVarConst(node.declarationList)) {
69249                     return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
69250                 }
69251             }
69252         }
69253         function checkGrammarMetaProperty(node) {
69254             var escapedText = node.name.escapedText;
69255             switch (node.keywordToken) {
69256                 case 99 /* NewKeyword */:
69257                     if (escapedText !== "target") {
69258                         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");
69259                     }
69260                     break;
69261                 case 96 /* ImportKeyword */:
69262                     if (escapedText !== "meta") {
69263                         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");
69264                     }
69265                     break;
69266             }
69267         }
69268         function hasParseDiagnostics(sourceFile) {
69269             return sourceFile.parseDiagnostics.length > 0;
69270         }
69271         function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
69272             var sourceFile = ts.getSourceFileOfNode(node);
69273             if (!hasParseDiagnostics(sourceFile)) {
69274                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69275                 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
69276                 return true;
69277             }
69278             return false;
69279         }
69280         function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
69281             var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
69282             if (!hasParseDiagnostics(sourceFile)) {
69283                 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
69284                 return true;
69285             }
69286             return false;
69287         }
69288         function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
69289             var sourceFile = ts.getSourceFileOfNode(node);
69290             if (!hasParseDiagnostics(sourceFile)) {
69291                 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
69292                 return true;
69293             }
69294             return false;
69295         }
69296         function checkGrammarConstructorTypeParameters(node) {
69297             var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
69298             var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
69299             if (range) {
69300                 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
69301                 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
69302             }
69303         }
69304         function checkGrammarConstructorTypeAnnotation(node) {
69305             var type = ts.getEffectiveReturnTypeNode(node);
69306             if (type) {
69307                 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
69308             }
69309         }
69310         function checkGrammarProperty(node) {
69311             if (ts.isClassLike(node.parent)) {
69312                 if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
69313                     return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
69314                 }
69315                 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)) {
69316                     return true;
69317                 }
69318                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
69319                     return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
69320                 }
69321             }
69322             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69323                 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)) {
69324                     return true;
69325                 }
69326                 if (node.initializer) {
69327                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
69328                 }
69329             }
69330             else if (node.parent.kind === 173 /* TypeLiteral */) {
69331                 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)) {
69332                     return true;
69333                 }
69334                 if (node.initializer) {
69335                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
69336                 }
69337             }
69338             if (node.flags & 8388608 /* Ambient */) {
69339                 checkAmbientInitializer(node);
69340             }
69341             if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
69342                 node.flags & 8388608 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
69343                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
69344             }
69345         }
69346         function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
69347             // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
69348             // interfaces and imports categories:
69349             //
69350             //  DeclarationElement:
69351             //     ExportAssignment
69352             //     export_opt   InterfaceDeclaration
69353             //     export_opt   TypeAliasDeclaration
69354             //     export_opt   ImportDeclaration
69355             //     export_opt   ExternalImportDeclaration
69356             //     export_opt   AmbientDeclaration
69357             //
69358             // TODO: The spec needs to be amended to reflect this grammar.
69359             if (node.kind === 246 /* InterfaceDeclaration */ ||
69360                 node.kind === 247 /* TypeAliasDeclaration */ ||
69361                 node.kind === 254 /* ImportDeclaration */ ||
69362                 node.kind === 253 /* ImportEqualsDeclaration */ ||
69363                 node.kind === 260 /* ExportDeclaration */ ||
69364                 node.kind === 259 /* ExportAssignment */ ||
69365                 node.kind === 252 /* NamespaceExportDeclaration */ ||
69366                 ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
69367                 return false;
69368             }
69369             return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
69370         }
69371         function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
69372             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
69373                 var decl = _a[_i];
69374                 if (ts.isDeclaration(decl) || decl.kind === 225 /* VariableStatement */) {
69375                     if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
69376                         return true;
69377                     }
69378                 }
69379             }
69380             return false;
69381         }
69382         function checkGrammarSourceFile(node) {
69383             return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
69384         }
69385         function checkGrammarStatementInAmbientContext(node) {
69386             if (node.flags & 8388608 /* Ambient */) {
69387                 // Find containing block which is either Block, ModuleBlock, SourceFile
69388                 var links = getNodeLinks(node);
69389                 if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
69390                     return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
69391                 }
69392                 // We are either parented by another statement, or some sort of block.
69393                 // If we're in a block, we only want to really report an error once
69394                 // to prevent noisiness.  So use a bit on the block to indicate if
69395                 // this has already been reported, and don't report if it has.
69396                 //
69397                 if (node.parent.kind === 223 /* Block */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
69398                     var links_2 = getNodeLinks(node.parent);
69399                     // Check if the containing block ever report this error
69400                     if (!links_2.hasReportedStatementInAmbientContext) {
69401                         return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
69402                     }
69403                 }
69404                 else {
69405                     // We must be parented by a statement.  If so, there's no need
69406                     // to report the error as our parent will have already done it.
69407                     // Debug.assert(isStatement(node.parent));
69408                 }
69409             }
69410             return false;
69411         }
69412         function checkGrammarNumericLiteral(node) {
69413             // Grammar checking
69414             if (node.numericLiteralFlags & 32 /* Octal */) {
69415                 var diagnosticMessage = void 0;
69416                 if (languageVersion >= 1 /* ES5 */) {
69417                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
69418                 }
69419                 else if (ts.isChildOfNodeWithKind(node, 187 /* LiteralType */)) {
69420                     diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
69421                 }
69422                 else if (ts.isChildOfNodeWithKind(node, 284 /* EnumMember */)) {
69423                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
69424                 }
69425                 if (diagnosticMessage) {
69426                     var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
69427                     var literal = (withMinus ? "-" : "") + "0o" + node.text;
69428                     return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
69429                 }
69430             }
69431             // Realism (size) checking
69432             checkNumericLiteralValueSize(node);
69433             return false;
69434         }
69435         function checkNumericLiteralValueSize(node) {
69436             // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
69437             // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
69438             // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
69439             if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
69440                 return;
69441             }
69442             // We can't rely on the runtime to accurately store and compare extremely large numeric values
69443             // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
69444             // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
69445             // it's likely addition operations on it will fail too
69446             var apparentValue = +ts.getTextOfNode(node);
69447             if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
69448                 return;
69449             }
69450             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));
69451         }
69452         function checkGrammarBigIntLiteral(node) {
69453             var literalType = ts.isLiteralTypeNode(node.parent) ||
69454                 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
69455             if (!literalType) {
69456                 if (languageVersion < 7 /* ES2020 */) {
69457                     if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
69458                         return true;
69459                     }
69460                 }
69461             }
69462             return false;
69463         }
69464         function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
69465             var sourceFile = ts.getSourceFileOfNode(node);
69466             if (!hasParseDiagnostics(sourceFile)) {
69467                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69468                 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
69469                 return true;
69470             }
69471             return false;
69472         }
69473         function getAmbientModules() {
69474             if (!ambientModulesCache) {
69475                 ambientModulesCache = [];
69476                 globals.forEach(function (global, sym) {
69477                     // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
69478                     if (ambientModuleSymbolRegex.test(sym)) {
69479                         ambientModulesCache.push(global);
69480                     }
69481                 });
69482             }
69483             return ambientModulesCache;
69484         }
69485         function checkGrammarImportClause(node) {
69486             if (node.isTypeOnly && node.name && node.namedBindings) {
69487                 return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
69488             }
69489             return false;
69490         }
69491         function checkGrammarImportCallExpression(node) {
69492             if (moduleKind === ts.ModuleKind.ES2015) {
69493                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd);
69494             }
69495             if (node.typeArguments) {
69496                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
69497             }
69498             var nodeArguments = node.arguments;
69499             if (nodeArguments.length !== 1) {
69500                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
69501             }
69502             checkGrammarForDisallowedTrailingComma(nodeArguments);
69503             // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
69504             // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
69505             if (ts.isSpreadElement(nodeArguments[0])) {
69506                 return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
69507             }
69508             return false;
69509         }
69510         function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
69511             var sourceObjectFlags = ts.getObjectFlags(source);
69512             if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
69513                 return ts.find(unionTarget.types, function (target) {
69514                     if (target.flags & 524288 /* Object */) {
69515                         var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
69516                         if (overlapObjFlags & 4 /* Reference */) {
69517                             return source.target === target.target;
69518                         }
69519                         if (overlapObjFlags & 16 /* Anonymous */) {
69520                             return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
69521                         }
69522                     }
69523                     return false;
69524                 });
69525             }
69526         }
69527         function findBestTypeForObjectLiteral(source, unionTarget) {
69528             if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
69529                 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
69530             }
69531         }
69532         function findBestTypeForInvokable(source, unionTarget) {
69533             var signatureKind = 0 /* Call */;
69534             var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
69535                 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
69536             if (hasSignatures) {
69537                 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
69538             }
69539         }
69540         function findMostOverlappyType(source, unionTarget) {
69541             var bestMatch;
69542             var matchingCount = 0;
69543             for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
69544                 var target = _a[_i];
69545                 var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
69546                 if (overlap.flags & 4194304 /* Index */) {
69547                     // perfect overlap of keys
69548                     bestMatch = target;
69549                     matchingCount = Infinity;
69550                 }
69551                 else if (overlap.flags & 1048576 /* Union */) {
69552                     // We only want to account for literal types otherwise.
69553                     // If we have a union of index types, it seems likely that we
69554                     // needed to elaborate between two generic mapped types anyway.
69555                     var len = ts.length(ts.filter(overlap.types, isUnitType));
69556                     if (len >= matchingCount) {
69557                         bestMatch = target;
69558                         matchingCount = len;
69559                     }
69560                 }
69561                 else if (isUnitType(overlap) && 1 >= matchingCount) {
69562                     bestMatch = target;
69563                     matchingCount = 1;
69564                 }
69565             }
69566             return bestMatch;
69567         }
69568         function filterPrimitivesIfContainsNonPrimitive(type) {
69569             if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
69570                 var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
69571                 if (!(result.flags & 131072 /* Never */)) {
69572                     return result;
69573                 }
69574             }
69575             return type;
69576         }
69577         // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
69578         function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) {
69579             if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
69580                 var sourceProperties = getPropertiesOfType(source);
69581                 if (sourceProperties) {
69582                     var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
69583                     if (sourcePropertiesFiltered) {
69584                         return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial);
69585                     }
69586                 }
69587             }
69588             return undefined;
69589         }
69590     }
69591     ts.createTypeChecker = createTypeChecker;
69592     function isNotAccessor(declaration) {
69593         // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
69594         return !ts.isAccessor(declaration);
69595     }
69596     function isNotOverload(declaration) {
69597         return (declaration.kind !== 244 /* FunctionDeclaration */ && declaration.kind !== 161 /* MethodDeclaration */) ||
69598             !!declaration.body;
69599     }
69600     /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
69601     function isDeclarationNameOrImportPropertyName(name) {
69602         switch (name.parent.kind) {
69603             case 258 /* ImportSpecifier */:
69604             case 263 /* ExportSpecifier */:
69605                 return ts.isIdentifier(name);
69606             default:
69607                 return ts.isDeclarationName(name);
69608         }
69609     }
69610     function isSomeImportDeclaration(decl) {
69611         switch (decl.kind) {
69612             case 255 /* ImportClause */: // For default import
69613             case 253 /* ImportEqualsDeclaration */:
69614             case 256 /* NamespaceImport */:
69615             case 258 /* ImportSpecifier */: // For rename import `x as y`
69616                 return true;
69617             case 75 /* Identifier */:
69618                 // For regular import, `decl` is an Identifier under the ImportSpecifier.
69619                 return decl.parent.kind === 258 /* ImportSpecifier */;
69620             default:
69621                 return false;
69622         }
69623     }
69624     var JsxNames;
69625     (function (JsxNames) {
69626         JsxNames.JSX = "JSX";
69627         JsxNames.IntrinsicElements = "IntrinsicElements";
69628         JsxNames.ElementClass = "ElementClass";
69629         JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
69630         JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
69631         JsxNames.Element = "Element";
69632         JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
69633         JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
69634         JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
69635     })(JsxNames || (JsxNames = {}));
69636     function getIterationTypesKeyFromIterationTypeKind(typeKind) {
69637         switch (typeKind) {
69638             case 0 /* Yield */: return "yieldType";
69639             case 1 /* Return */: return "returnType";
69640             case 2 /* Next */: return "nextType";
69641         }
69642     }
69643     function signatureHasRestParameter(s) {
69644         return !!(s.flags & 1 /* HasRestParameter */);
69645     }
69646     ts.signatureHasRestParameter = signatureHasRestParameter;
69647     function signatureHasLiteralTypes(s) {
69648         return !!(s.flags & 2 /* HasLiteralTypes */);
69649     }
69650     ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
69651 })(ts || (ts = {}));
69652 var ts;
69653 (function (ts) {
69654     function createSynthesizedNode(kind) {
69655         var node = ts.createNode(kind, -1, -1);
69656         node.flags |= 8 /* Synthesized */;
69657         return node;
69658     }
69659     /* @internal */
69660     function updateNode(updated, original) {
69661         if (updated !== original) {
69662             setOriginalNode(updated, original);
69663             setTextRange(updated, original);
69664             ts.aggregateTransformFlags(updated);
69665         }
69666         return updated;
69667     }
69668     ts.updateNode = updateNode;
69669     /**
69670      * Make `elements` into a `NodeArray<T>`. If `elements` is `undefined`, returns an empty `NodeArray<T>`.
69671      */
69672     function createNodeArray(elements, hasTrailingComma) {
69673         if (!elements || elements === ts.emptyArray) {
69674             elements = [];
69675         }
69676         else if (ts.isNodeArray(elements)) {
69677             return elements;
69678         }
69679         var array = elements;
69680         array.pos = -1;
69681         array.end = -1;
69682         array.hasTrailingComma = hasTrailingComma;
69683         return array;
69684     }
69685     ts.createNodeArray = createNodeArray;
69686     /**
69687      * Creates a shallow, memberwise clone of a node with no source map location.
69688      */
69689     /* @internal */
69690     function getSynthesizedClone(node) {
69691         // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
69692         // the original node. We also need to exclude specific properties and only include own-
69693         // properties (to skip members already defined on the shared prototype).
69694         if (node === undefined) {
69695             return node;
69696         }
69697         var clone = createSynthesizedNode(node.kind);
69698         clone.flags |= node.flags;
69699         setOriginalNode(clone, node);
69700         for (var key in node) {
69701             if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
69702                 continue;
69703             }
69704             clone[key] = node[key];
69705         }
69706         return clone;
69707     }
69708     ts.getSynthesizedClone = getSynthesizedClone;
69709     function createLiteral(value, isSingleQuote) {
69710         if (typeof value === "number") {
69711             return createNumericLiteral(value + "");
69712         }
69713         // eslint-disable-next-line no-in-operator
69714         if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt
69715             return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n");
69716         }
69717         if (typeof value === "boolean") {
69718             return value ? createTrue() : createFalse();
69719         }
69720         if (ts.isString(value)) {
69721             var res = createStringLiteral(value);
69722             if (isSingleQuote)
69723                 res.singleQuote = true;
69724             return res;
69725         }
69726         return createLiteralFromNode(value);
69727     }
69728     ts.createLiteral = createLiteral;
69729     function createNumericLiteral(value, numericLiteralFlags) {
69730         if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
69731         var node = createSynthesizedNode(8 /* NumericLiteral */);
69732         node.text = value;
69733         node.numericLiteralFlags = numericLiteralFlags;
69734         return node;
69735     }
69736     ts.createNumericLiteral = createNumericLiteral;
69737     function createBigIntLiteral(value) {
69738         var node = createSynthesizedNode(9 /* BigIntLiteral */);
69739         node.text = value;
69740         return node;
69741     }
69742     ts.createBigIntLiteral = createBigIntLiteral;
69743     function createStringLiteral(text) {
69744         var node = createSynthesizedNode(10 /* StringLiteral */);
69745         node.text = text;
69746         return node;
69747     }
69748     ts.createStringLiteral = createStringLiteral;
69749     function createRegularExpressionLiteral(text) {
69750         var node = createSynthesizedNode(13 /* RegularExpressionLiteral */);
69751         node.text = text;
69752         return node;
69753     }
69754     ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
69755     function createLiteralFromNode(sourceNode) {
69756         var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
69757         node.textSourceNode = sourceNode;
69758         return node;
69759     }
69760     function createIdentifier(text, typeArguments) {
69761         var node = createSynthesizedNode(75 /* Identifier */);
69762         node.escapedText = ts.escapeLeadingUnderscores(text);
69763         node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */;
69764         node.autoGenerateFlags = 0 /* None */;
69765         node.autoGenerateId = 0;
69766         if (typeArguments) {
69767             node.typeArguments = createNodeArray(typeArguments);
69768         }
69769         return node;
69770     }
69771     ts.createIdentifier = createIdentifier;
69772     function updateIdentifier(node, typeArguments) {
69773         return node.typeArguments !== typeArguments
69774             ? updateNode(createIdentifier(ts.idText(node), typeArguments), node)
69775             : node;
69776     }
69777     ts.updateIdentifier = updateIdentifier;
69778     var nextAutoGenerateId = 0;
69779     function createTempVariable(recordTempVariable, reservedInNestedScopes) {
69780         var name = createIdentifier("");
69781         name.autoGenerateFlags = 1 /* Auto */;
69782         name.autoGenerateId = nextAutoGenerateId;
69783         nextAutoGenerateId++;
69784         if (recordTempVariable) {
69785             recordTempVariable(name);
69786         }
69787         if (reservedInNestedScopes) {
69788             name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
69789         }
69790         return name;
69791     }
69792     ts.createTempVariable = createTempVariable;
69793     /** Create a unique temporary variable for use in a loop. */
69794     function createLoopVariable() {
69795         var name = createIdentifier("");
69796         name.autoGenerateFlags = 2 /* Loop */;
69797         name.autoGenerateId = nextAutoGenerateId;
69798         nextAutoGenerateId++;
69799         return name;
69800     }
69801     ts.createLoopVariable = createLoopVariable;
69802     /** Create a unique name based on the supplied text. */
69803     function createUniqueName(text) {
69804         var name = createIdentifier(text);
69805         name.autoGenerateFlags = 3 /* Unique */;
69806         name.autoGenerateId = nextAutoGenerateId;
69807         nextAutoGenerateId++;
69808         return name;
69809     }
69810     ts.createUniqueName = createUniqueName;
69811     function createOptimisticUniqueName(text) {
69812         var name = createIdentifier(text);
69813         name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
69814         name.autoGenerateId = nextAutoGenerateId;
69815         nextAutoGenerateId++;
69816         return name;
69817     }
69818     ts.createOptimisticUniqueName = createOptimisticUniqueName;
69819     /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
69820     function createFileLevelUniqueName(text) {
69821         var name = createOptimisticUniqueName(text);
69822         name.autoGenerateFlags |= 32 /* FileLevel */;
69823         return name;
69824     }
69825     ts.createFileLevelUniqueName = createFileLevelUniqueName;
69826     function getGeneratedNameForNode(node, flags) {
69827         var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "");
69828         name.autoGenerateFlags = 4 /* Node */ | flags;
69829         name.autoGenerateId = nextAutoGenerateId;
69830         name.original = node;
69831         nextAutoGenerateId++;
69832         return name;
69833     }
69834     ts.getGeneratedNameForNode = getGeneratedNameForNode;
69835     // Private Identifiers
69836     function createPrivateIdentifier(text) {
69837         if (text[0] !== "#") {
69838             ts.Debug.fail("First character of private identifier must be #: " + text);
69839         }
69840         var node = createSynthesizedNode(76 /* PrivateIdentifier */);
69841         node.escapedText = ts.escapeLeadingUnderscores(text);
69842         return node;
69843     }
69844     ts.createPrivateIdentifier = createPrivateIdentifier;
69845     // Punctuation
69846     function createToken(token) {
69847         return createSynthesizedNode(token);
69848     }
69849     ts.createToken = createToken;
69850     // Reserved words
69851     function createSuper() {
69852         return createSynthesizedNode(102 /* SuperKeyword */);
69853     }
69854     ts.createSuper = createSuper;
69855     function createThis() {
69856         return createSynthesizedNode(104 /* ThisKeyword */);
69857     }
69858     ts.createThis = createThis;
69859     function createNull() {
69860         return createSynthesizedNode(100 /* NullKeyword */);
69861     }
69862     ts.createNull = createNull;
69863     function createTrue() {
69864         return createSynthesizedNode(106 /* TrueKeyword */);
69865     }
69866     ts.createTrue = createTrue;
69867     function createFalse() {
69868         return createSynthesizedNode(91 /* FalseKeyword */);
69869     }
69870     ts.createFalse = createFalse;
69871     // Modifiers
69872     function createModifier(kind) {
69873         return createToken(kind);
69874     }
69875     ts.createModifier = createModifier;
69876     function createModifiersFromModifierFlags(flags) {
69877         var result = [];
69878         if (flags & 1 /* Export */) {
69879             result.push(createModifier(89 /* ExportKeyword */));
69880         }
69881         if (flags & 2 /* Ambient */) {
69882             result.push(createModifier(130 /* DeclareKeyword */));
69883         }
69884         if (flags & 512 /* Default */) {
69885             result.push(createModifier(84 /* DefaultKeyword */));
69886         }
69887         if (flags & 2048 /* Const */) {
69888             result.push(createModifier(81 /* ConstKeyword */));
69889         }
69890         if (flags & 4 /* Public */) {
69891             result.push(createModifier(119 /* PublicKeyword */));
69892         }
69893         if (flags & 8 /* Private */) {
69894             result.push(createModifier(117 /* PrivateKeyword */));
69895         }
69896         if (flags & 16 /* Protected */) {
69897             result.push(createModifier(118 /* ProtectedKeyword */));
69898         }
69899         if (flags & 128 /* Abstract */) {
69900             result.push(createModifier(122 /* AbstractKeyword */));
69901         }
69902         if (flags & 32 /* Static */) {
69903             result.push(createModifier(120 /* StaticKeyword */));
69904         }
69905         if (flags & 64 /* Readonly */) {
69906             result.push(createModifier(138 /* ReadonlyKeyword */));
69907         }
69908         if (flags & 256 /* Async */) {
69909             result.push(createModifier(126 /* AsyncKeyword */));
69910         }
69911         return result;
69912     }
69913     ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags;
69914     // Names
69915     function createQualifiedName(left, right) {
69916         var node = createSynthesizedNode(153 /* QualifiedName */);
69917         node.left = left;
69918         node.right = asName(right);
69919         return node;
69920     }
69921     ts.createQualifiedName = createQualifiedName;
69922     function updateQualifiedName(node, left, right) {
69923         return node.left !== left
69924             || node.right !== right
69925             ? updateNode(createQualifiedName(left, right), node)
69926             : node;
69927     }
69928     ts.updateQualifiedName = updateQualifiedName;
69929     function parenthesizeForComputedName(expression) {
69930         return ts.isCommaSequence(expression)
69931             ? createParen(expression)
69932             : expression;
69933     }
69934     function createComputedPropertyName(expression) {
69935         var node = createSynthesizedNode(154 /* ComputedPropertyName */);
69936         node.expression = parenthesizeForComputedName(expression);
69937         return node;
69938     }
69939     ts.createComputedPropertyName = createComputedPropertyName;
69940     function updateComputedPropertyName(node, expression) {
69941         return node.expression !== expression
69942             ? updateNode(createComputedPropertyName(expression), node)
69943             : node;
69944     }
69945     ts.updateComputedPropertyName = updateComputedPropertyName;
69946     // Signature elements
69947     function createTypeParameterDeclaration(name, constraint, defaultType) {
69948         var node = createSynthesizedNode(155 /* TypeParameter */);
69949         node.name = asName(name);
69950         node.constraint = constraint;
69951         node.default = defaultType;
69952         return node;
69953     }
69954     ts.createTypeParameterDeclaration = createTypeParameterDeclaration;
69955     function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
69956         return node.name !== name
69957             || node.constraint !== constraint
69958             || node.default !== defaultType
69959             ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node)
69960             : node;
69961     }
69962     ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration;
69963     function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
69964         var node = createSynthesizedNode(156 /* Parameter */);
69965         node.decorators = asNodeArray(decorators);
69966         node.modifiers = asNodeArray(modifiers);
69967         node.dotDotDotToken = dotDotDotToken;
69968         node.name = asName(name);
69969         node.questionToken = questionToken;
69970         node.type = type;
69971         node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined;
69972         return node;
69973     }
69974     ts.createParameter = createParameter;
69975     function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
69976         return node.decorators !== decorators
69977             || node.modifiers !== modifiers
69978             || node.dotDotDotToken !== dotDotDotToken
69979             || node.name !== name
69980             || node.questionToken !== questionToken
69981             || node.type !== type
69982             || node.initializer !== initializer
69983             ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
69984             : node;
69985     }
69986     ts.updateParameter = updateParameter;
69987     function createDecorator(expression) {
69988         var node = createSynthesizedNode(157 /* Decorator */);
69989         node.expression = ts.parenthesizeForAccess(expression);
69990         return node;
69991     }
69992     ts.createDecorator = createDecorator;
69993     function updateDecorator(node, expression) {
69994         return node.expression !== expression
69995             ? updateNode(createDecorator(expression), node)
69996             : node;
69997     }
69998     ts.updateDecorator = updateDecorator;
69999     // Type Elements
70000     function createPropertySignature(modifiers, name, questionToken, type, initializer) {
70001         var node = createSynthesizedNode(158 /* PropertySignature */);
70002         node.modifiers = asNodeArray(modifiers);
70003         node.name = asName(name);
70004         node.questionToken = questionToken;
70005         node.type = type;
70006         node.initializer = initializer;
70007         return node;
70008     }
70009     ts.createPropertySignature = createPropertySignature;
70010     function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) {
70011         return node.modifiers !== modifiers
70012             || node.name !== name
70013             || node.questionToken !== questionToken
70014             || node.type !== type
70015             || node.initializer !== initializer
70016             ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node)
70017             : node;
70018     }
70019     ts.updatePropertySignature = updatePropertySignature;
70020     function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
70021         var node = createSynthesizedNode(159 /* PropertyDeclaration */);
70022         node.decorators = asNodeArray(decorators);
70023         node.modifiers = asNodeArray(modifiers);
70024         node.name = asName(name);
70025         node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined;
70026         node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined;
70027         node.type = type;
70028         node.initializer = initializer;
70029         return node;
70030     }
70031     ts.createProperty = createProperty;
70032     function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
70033         return node.decorators !== decorators
70034             || node.modifiers !== modifiers
70035             || node.name !== name
70036             || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined)
70037             || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined)
70038             || node.type !== type
70039             || node.initializer !== initializer
70040             ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
70041             : node;
70042     }
70043     ts.updateProperty = updateProperty;
70044     function createMethodSignature(typeParameters, parameters, type, name, questionToken) {
70045         var node = createSignatureDeclaration(160 /* MethodSignature */, typeParameters, parameters, type);
70046         node.name = asName(name);
70047         node.questionToken = questionToken;
70048         return node;
70049     }
70050     ts.createMethodSignature = createMethodSignature;
70051     function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) {
70052         return node.typeParameters !== typeParameters
70053             || node.parameters !== parameters
70054             || node.type !== type
70055             || node.name !== name
70056             || node.questionToken !== questionToken
70057             ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
70058             : node;
70059     }
70060     ts.updateMethodSignature = updateMethodSignature;
70061     function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70062         var node = createSynthesizedNode(161 /* MethodDeclaration */);
70063         node.decorators = asNodeArray(decorators);
70064         node.modifiers = asNodeArray(modifiers);
70065         node.asteriskToken = asteriskToken;
70066         node.name = asName(name);
70067         node.questionToken = questionToken;
70068         node.typeParameters = asNodeArray(typeParameters);
70069         node.parameters = createNodeArray(parameters);
70070         node.type = type;
70071         node.body = body;
70072         return node;
70073     }
70074     ts.createMethod = createMethod;
70075     function createMethodCall(object, methodName, argumentsList) {
70076         return createCall(createPropertyAccess(object, asName(methodName)), 
70077         /*typeArguments*/ undefined, argumentsList);
70078     }
70079     function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
70080         return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
70081     }
70082     /* @internal */
70083     function createObjectDefinePropertyCall(target, propertyName, attributes) {
70084         return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
70085     }
70086     ts.createObjectDefinePropertyCall = createObjectDefinePropertyCall;
70087     function tryAddPropertyAssignment(properties, propertyName, expression) {
70088         if (expression) {
70089             properties.push(createPropertyAssignment(propertyName, expression));
70090             return true;
70091         }
70092         return false;
70093     }
70094     /* @internal */
70095     function createPropertyDescriptor(attributes, singleLine) {
70096         var properties = [];
70097         tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
70098         tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
70099         var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
70100         isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
70101         var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
70102         isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
70103         ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
70104         return createObjectLiteral(properties, !singleLine);
70105     }
70106     ts.createPropertyDescriptor = createPropertyDescriptor;
70107     function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70108         return node.decorators !== decorators
70109             || node.modifiers !== modifiers
70110             || node.asteriskToken !== asteriskToken
70111             || node.name !== name
70112             || node.questionToken !== questionToken
70113             || node.typeParameters !== typeParameters
70114             || node.parameters !== parameters
70115             || node.type !== type
70116             || node.body !== body
70117             ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
70118             : node;
70119     }
70120     ts.updateMethod = updateMethod;
70121     function createConstructor(decorators, modifiers, parameters, body) {
70122         var node = createSynthesizedNode(162 /* Constructor */);
70123         node.decorators = asNodeArray(decorators);
70124         node.modifiers = asNodeArray(modifiers);
70125         node.typeParameters = undefined;
70126         node.parameters = createNodeArray(parameters);
70127         node.type = undefined;
70128         node.body = body;
70129         return node;
70130     }
70131     ts.createConstructor = createConstructor;
70132     function updateConstructor(node, decorators, modifiers, parameters, body) {
70133         return node.decorators !== decorators
70134             || node.modifiers !== modifiers
70135             || node.parameters !== parameters
70136             || node.body !== body
70137             ? updateNode(createConstructor(decorators, modifiers, parameters, body), node)
70138             : node;
70139     }
70140     ts.updateConstructor = updateConstructor;
70141     function createGetAccessor(decorators, modifiers, name, parameters, type, body) {
70142         var node = createSynthesizedNode(163 /* GetAccessor */);
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.type = type;
70149         node.body = body;
70150         return node;
70151     }
70152     ts.createGetAccessor = createGetAccessor;
70153     function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) {
70154         return node.decorators !== decorators
70155             || node.modifiers !== modifiers
70156             || node.name !== name
70157             || node.parameters !== parameters
70158             || node.type !== type
70159             || node.body !== body
70160             ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node)
70161             : node;
70162     }
70163     ts.updateGetAccessor = updateGetAccessor;
70164     function createSetAccessor(decorators, modifiers, name, parameters, body) {
70165         var node = createSynthesizedNode(164 /* SetAccessor */);
70166         node.decorators = asNodeArray(decorators);
70167         node.modifiers = asNodeArray(modifiers);
70168         node.name = asName(name);
70169         node.typeParameters = undefined;
70170         node.parameters = createNodeArray(parameters);
70171         node.body = body;
70172         return node;
70173     }
70174     ts.createSetAccessor = createSetAccessor;
70175     function updateSetAccessor(node, decorators, modifiers, name, parameters, body) {
70176         return node.decorators !== decorators
70177             || node.modifiers !== modifiers
70178             || node.name !== name
70179             || node.parameters !== parameters
70180             || node.body !== body
70181             ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node)
70182             : node;
70183     }
70184     ts.updateSetAccessor = updateSetAccessor;
70185     function createCallSignature(typeParameters, parameters, type) {
70186         return createSignatureDeclaration(165 /* CallSignature */, typeParameters, parameters, type);
70187     }
70188     ts.createCallSignature = createCallSignature;
70189     function updateCallSignature(node, typeParameters, parameters, type) {
70190         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70191     }
70192     ts.updateCallSignature = updateCallSignature;
70193     function createConstructSignature(typeParameters, parameters, type) {
70194         return createSignatureDeclaration(166 /* ConstructSignature */, typeParameters, parameters, type);
70195     }
70196     ts.createConstructSignature = createConstructSignature;
70197     function updateConstructSignature(node, typeParameters, parameters, type) {
70198         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70199     }
70200     ts.updateConstructSignature = updateConstructSignature;
70201     function createIndexSignature(decorators, modifiers, parameters, type) {
70202         var node = createSynthesizedNode(167 /* IndexSignature */);
70203         node.decorators = asNodeArray(decorators);
70204         node.modifiers = asNodeArray(modifiers);
70205         node.parameters = createNodeArray(parameters);
70206         node.type = type;
70207         return node;
70208     }
70209     ts.createIndexSignature = createIndexSignature;
70210     function updateIndexSignature(node, decorators, modifiers, parameters, type) {
70211         return node.parameters !== parameters
70212             || node.type !== type
70213             || node.decorators !== decorators
70214             || node.modifiers !== modifiers
70215             ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node)
70216             : node;
70217     }
70218     ts.updateIndexSignature = updateIndexSignature;
70219     /* @internal */
70220     function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) {
70221         var node = createSynthesizedNode(kind);
70222         node.typeParameters = asNodeArray(typeParameters);
70223         node.parameters = asNodeArray(parameters);
70224         node.type = type;
70225         node.typeArguments = asNodeArray(typeArguments);
70226         return node;
70227     }
70228     ts.createSignatureDeclaration = createSignatureDeclaration;
70229     function updateSignatureDeclaration(node, typeParameters, parameters, type) {
70230         return node.typeParameters !== typeParameters
70231             || node.parameters !== parameters
70232             || node.type !== type
70233             ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
70234             : node;
70235     }
70236     // Types
70237     function createKeywordTypeNode(kind) {
70238         return createSynthesizedNode(kind);
70239     }
70240     ts.createKeywordTypeNode = createKeywordTypeNode;
70241     function createTypePredicateNode(parameterName, type) {
70242         return createTypePredicateNodeWithModifier(/*assertsModifier*/ undefined, parameterName, type);
70243     }
70244     ts.createTypePredicateNode = createTypePredicateNode;
70245     function createTypePredicateNodeWithModifier(assertsModifier, parameterName, type) {
70246         var node = createSynthesizedNode(168 /* TypePredicate */);
70247         node.assertsModifier = assertsModifier;
70248         node.parameterName = asName(parameterName);
70249         node.type = type;
70250         return node;
70251     }
70252     ts.createTypePredicateNodeWithModifier = createTypePredicateNodeWithModifier;
70253     function updateTypePredicateNode(node, parameterName, type) {
70254         return updateTypePredicateNodeWithModifier(node, node.assertsModifier, parameterName, type);
70255     }
70256     ts.updateTypePredicateNode = updateTypePredicateNode;
70257     function updateTypePredicateNodeWithModifier(node, assertsModifier, parameterName, type) {
70258         return node.assertsModifier !== assertsModifier
70259             || node.parameterName !== parameterName
70260             || node.type !== type
70261             ? updateNode(createTypePredicateNodeWithModifier(assertsModifier, parameterName, type), node)
70262             : node;
70263     }
70264     ts.updateTypePredicateNodeWithModifier = updateTypePredicateNodeWithModifier;
70265     function createTypeReferenceNode(typeName, typeArguments) {
70266         var node = createSynthesizedNode(169 /* TypeReference */);
70267         node.typeName = asName(typeName);
70268         node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments);
70269         return node;
70270     }
70271     ts.createTypeReferenceNode = createTypeReferenceNode;
70272     function updateTypeReferenceNode(node, typeName, typeArguments) {
70273         return node.typeName !== typeName
70274             || node.typeArguments !== typeArguments
70275             ? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
70276             : node;
70277     }
70278     ts.updateTypeReferenceNode = updateTypeReferenceNode;
70279     function createFunctionTypeNode(typeParameters, parameters, type) {
70280         return createSignatureDeclaration(170 /* FunctionType */, typeParameters, parameters, type);
70281     }
70282     ts.createFunctionTypeNode = createFunctionTypeNode;
70283     function updateFunctionTypeNode(node, typeParameters, parameters, type) {
70284         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70285     }
70286     ts.updateFunctionTypeNode = updateFunctionTypeNode;
70287     function createConstructorTypeNode(typeParameters, parameters, type) {
70288         return createSignatureDeclaration(171 /* ConstructorType */, typeParameters, parameters, type);
70289     }
70290     ts.createConstructorTypeNode = createConstructorTypeNode;
70291     function updateConstructorTypeNode(node, typeParameters, parameters, type) {
70292         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70293     }
70294     ts.updateConstructorTypeNode = updateConstructorTypeNode;
70295     function createTypeQueryNode(exprName) {
70296         var node = createSynthesizedNode(172 /* TypeQuery */);
70297         node.exprName = exprName;
70298         return node;
70299     }
70300     ts.createTypeQueryNode = createTypeQueryNode;
70301     function updateTypeQueryNode(node, exprName) {
70302         return node.exprName !== exprName
70303             ? updateNode(createTypeQueryNode(exprName), node)
70304             : node;
70305     }
70306     ts.updateTypeQueryNode = updateTypeQueryNode;
70307     function createTypeLiteralNode(members) {
70308         var node = createSynthesizedNode(173 /* TypeLiteral */);
70309         node.members = createNodeArray(members);
70310         return node;
70311     }
70312     ts.createTypeLiteralNode = createTypeLiteralNode;
70313     function updateTypeLiteralNode(node, members) {
70314         return node.members !== members
70315             ? updateNode(createTypeLiteralNode(members), node)
70316             : node;
70317     }
70318     ts.updateTypeLiteralNode = updateTypeLiteralNode;
70319     function createArrayTypeNode(elementType) {
70320         var node = createSynthesizedNode(174 /* ArrayType */);
70321         node.elementType = ts.parenthesizeArrayTypeMember(elementType);
70322         return node;
70323     }
70324     ts.createArrayTypeNode = createArrayTypeNode;
70325     function updateArrayTypeNode(node, elementType) {
70326         return node.elementType !== elementType
70327             ? updateNode(createArrayTypeNode(elementType), node)
70328             : node;
70329     }
70330     ts.updateArrayTypeNode = updateArrayTypeNode;
70331     function createTupleTypeNode(elementTypes) {
70332         var node = createSynthesizedNode(175 /* TupleType */);
70333         node.elementTypes = createNodeArray(elementTypes);
70334         return node;
70335     }
70336     ts.createTupleTypeNode = createTupleTypeNode;
70337     function updateTupleTypeNode(node, elementTypes) {
70338         return node.elementTypes !== elementTypes
70339             ? updateNode(createTupleTypeNode(elementTypes), node)
70340             : node;
70341     }
70342     ts.updateTupleTypeNode = updateTupleTypeNode;
70343     function createOptionalTypeNode(type) {
70344         var node = createSynthesizedNode(176 /* OptionalType */);
70345         node.type = ts.parenthesizeArrayTypeMember(type);
70346         return node;
70347     }
70348     ts.createOptionalTypeNode = createOptionalTypeNode;
70349     function updateOptionalTypeNode(node, type) {
70350         return node.type !== type
70351             ? updateNode(createOptionalTypeNode(type), node)
70352             : node;
70353     }
70354     ts.updateOptionalTypeNode = updateOptionalTypeNode;
70355     function createRestTypeNode(type) {
70356         var node = createSynthesizedNode(177 /* RestType */);
70357         node.type = type;
70358         return node;
70359     }
70360     ts.createRestTypeNode = createRestTypeNode;
70361     function updateRestTypeNode(node, type) {
70362         return node.type !== type
70363             ? updateNode(createRestTypeNode(type), node)
70364             : node;
70365     }
70366     ts.updateRestTypeNode = updateRestTypeNode;
70367     function createUnionTypeNode(types) {
70368         return createUnionOrIntersectionTypeNode(178 /* UnionType */, types);
70369     }
70370     ts.createUnionTypeNode = createUnionTypeNode;
70371     function updateUnionTypeNode(node, types) {
70372         return updateUnionOrIntersectionTypeNode(node, types);
70373     }
70374     ts.updateUnionTypeNode = updateUnionTypeNode;
70375     function createIntersectionTypeNode(types) {
70376         return createUnionOrIntersectionTypeNode(179 /* IntersectionType */, types);
70377     }
70378     ts.createIntersectionTypeNode = createIntersectionTypeNode;
70379     function updateIntersectionTypeNode(node, types) {
70380         return updateUnionOrIntersectionTypeNode(node, types);
70381     }
70382     ts.updateIntersectionTypeNode = updateIntersectionTypeNode;
70383     function createUnionOrIntersectionTypeNode(kind, types) {
70384         var node = createSynthesizedNode(kind);
70385         node.types = ts.parenthesizeElementTypeMembers(types);
70386         return node;
70387     }
70388     ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode;
70389     function updateUnionOrIntersectionTypeNode(node, types) {
70390         return node.types !== types
70391             ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
70392             : node;
70393     }
70394     function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
70395         var node = createSynthesizedNode(180 /* ConditionalType */);
70396         node.checkType = ts.parenthesizeConditionalTypeMember(checkType);
70397         node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType);
70398         node.trueType = trueType;
70399         node.falseType = falseType;
70400         return node;
70401     }
70402     ts.createConditionalTypeNode = createConditionalTypeNode;
70403     function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
70404         return node.checkType !== checkType
70405             || node.extendsType !== extendsType
70406             || node.trueType !== trueType
70407             || node.falseType !== falseType
70408             ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
70409             : node;
70410     }
70411     ts.updateConditionalTypeNode = updateConditionalTypeNode;
70412     function createInferTypeNode(typeParameter) {
70413         var node = createSynthesizedNode(181 /* InferType */);
70414         node.typeParameter = typeParameter;
70415         return node;
70416     }
70417     ts.createInferTypeNode = createInferTypeNode;
70418     function updateInferTypeNode(node, typeParameter) {
70419         return node.typeParameter !== typeParameter
70420             ? updateNode(createInferTypeNode(typeParameter), node)
70421             : node;
70422     }
70423     ts.updateInferTypeNode = updateInferTypeNode;
70424     function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
70425         var node = createSynthesizedNode(188 /* ImportType */);
70426         node.argument = argument;
70427         node.qualifier = qualifier;
70428         node.typeArguments = ts.parenthesizeTypeParameters(typeArguments);
70429         node.isTypeOf = isTypeOf;
70430         return node;
70431     }
70432     ts.createImportTypeNode = createImportTypeNode;
70433     function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
70434         return node.argument !== argument
70435             || node.qualifier !== qualifier
70436             || node.typeArguments !== typeArguments
70437             || node.isTypeOf !== isTypeOf
70438             ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
70439             : node;
70440     }
70441     ts.updateImportTypeNode = updateImportTypeNode;
70442     function createParenthesizedType(type) {
70443         var node = createSynthesizedNode(182 /* ParenthesizedType */);
70444         node.type = type;
70445         return node;
70446     }
70447     ts.createParenthesizedType = createParenthesizedType;
70448     function updateParenthesizedType(node, type) {
70449         return node.type !== type
70450             ? updateNode(createParenthesizedType(type), node)
70451             : node;
70452     }
70453     ts.updateParenthesizedType = updateParenthesizedType;
70454     function createThisTypeNode() {
70455         return createSynthesizedNode(183 /* ThisType */);
70456     }
70457     ts.createThisTypeNode = createThisTypeNode;
70458     function createTypeOperatorNode(operatorOrType, type) {
70459         var node = createSynthesizedNode(184 /* TypeOperator */);
70460         node.operator = typeof operatorOrType === "number" ? operatorOrType : 134 /* KeyOfKeyword */;
70461         node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType);
70462         return node;
70463     }
70464     ts.createTypeOperatorNode = createTypeOperatorNode;
70465     function updateTypeOperatorNode(node, type) {
70466         return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node;
70467     }
70468     ts.updateTypeOperatorNode = updateTypeOperatorNode;
70469     function createIndexedAccessTypeNode(objectType, indexType) {
70470         var node = createSynthesizedNode(185 /* IndexedAccessType */);
70471         node.objectType = ts.parenthesizeElementTypeMember(objectType);
70472         node.indexType = indexType;
70473         return node;
70474     }
70475     ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode;
70476     function updateIndexedAccessTypeNode(node, objectType, indexType) {
70477         return node.objectType !== objectType
70478             || node.indexType !== indexType
70479             ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
70480             : node;
70481     }
70482     ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode;
70483     function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) {
70484         var node = createSynthesizedNode(186 /* MappedType */);
70485         node.readonlyToken = readonlyToken;
70486         node.typeParameter = typeParameter;
70487         node.questionToken = questionToken;
70488         node.type = type;
70489         return node;
70490     }
70491     ts.createMappedTypeNode = createMappedTypeNode;
70492     function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) {
70493         return node.readonlyToken !== readonlyToken
70494             || node.typeParameter !== typeParameter
70495             || node.questionToken !== questionToken
70496             || node.type !== type
70497             ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
70498             : node;
70499     }
70500     ts.updateMappedTypeNode = updateMappedTypeNode;
70501     function createLiteralTypeNode(literal) {
70502         var node = createSynthesizedNode(187 /* LiteralType */);
70503         node.literal = literal;
70504         return node;
70505     }
70506     ts.createLiteralTypeNode = createLiteralTypeNode;
70507     function updateLiteralTypeNode(node, literal) {
70508         return node.literal !== literal
70509             ? updateNode(createLiteralTypeNode(literal), node)
70510             : node;
70511     }
70512     ts.updateLiteralTypeNode = updateLiteralTypeNode;
70513     // Binding Patterns
70514     function createObjectBindingPattern(elements) {
70515         var node = createSynthesizedNode(189 /* ObjectBindingPattern */);
70516         node.elements = createNodeArray(elements);
70517         return node;
70518     }
70519     ts.createObjectBindingPattern = createObjectBindingPattern;
70520     function updateObjectBindingPattern(node, elements) {
70521         return node.elements !== elements
70522             ? updateNode(createObjectBindingPattern(elements), node)
70523             : node;
70524     }
70525     ts.updateObjectBindingPattern = updateObjectBindingPattern;
70526     function createArrayBindingPattern(elements) {
70527         var node = createSynthesizedNode(190 /* ArrayBindingPattern */);
70528         node.elements = createNodeArray(elements);
70529         return node;
70530     }
70531     ts.createArrayBindingPattern = createArrayBindingPattern;
70532     function updateArrayBindingPattern(node, elements) {
70533         return node.elements !== elements
70534             ? updateNode(createArrayBindingPattern(elements), node)
70535             : node;
70536     }
70537     ts.updateArrayBindingPattern = updateArrayBindingPattern;
70538     function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
70539         var node = createSynthesizedNode(191 /* BindingElement */);
70540         node.dotDotDotToken = dotDotDotToken;
70541         node.propertyName = asName(propertyName);
70542         node.name = asName(name);
70543         node.initializer = initializer;
70544         return node;
70545     }
70546     ts.createBindingElement = createBindingElement;
70547     function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
70548         return node.propertyName !== propertyName
70549             || node.dotDotDotToken !== dotDotDotToken
70550             || node.name !== name
70551             || node.initializer !== initializer
70552             ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
70553             : node;
70554     }
70555     ts.updateBindingElement = updateBindingElement;
70556     // Expression
70557     function createArrayLiteral(elements, multiLine) {
70558         var node = createSynthesizedNode(192 /* ArrayLiteralExpression */);
70559         node.elements = ts.parenthesizeListElements(createNodeArray(elements));
70560         if (multiLine)
70561             node.multiLine = true;
70562         return node;
70563     }
70564     ts.createArrayLiteral = createArrayLiteral;
70565     function updateArrayLiteral(node, elements) {
70566         return node.elements !== elements
70567             ? updateNode(createArrayLiteral(elements, node.multiLine), node)
70568             : node;
70569     }
70570     ts.updateArrayLiteral = updateArrayLiteral;
70571     function createObjectLiteral(properties, multiLine) {
70572         var node = createSynthesizedNode(193 /* ObjectLiteralExpression */);
70573         node.properties = createNodeArray(properties);
70574         if (multiLine)
70575             node.multiLine = true;
70576         return node;
70577     }
70578     ts.createObjectLiteral = createObjectLiteral;
70579     function updateObjectLiteral(node, properties) {
70580         return node.properties !== properties
70581             ? updateNode(createObjectLiteral(properties, node.multiLine), node)
70582             : node;
70583     }
70584     ts.updateObjectLiteral = updateObjectLiteral;
70585     function createPropertyAccess(expression, name) {
70586         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70587         node.expression = ts.parenthesizeForAccess(expression);
70588         node.name = asName(name);
70589         setEmitFlags(node, 131072 /* NoIndentation */);
70590         return node;
70591     }
70592     ts.createPropertyAccess = createPropertyAccess;
70593     function updatePropertyAccess(node, expression, name) {
70594         if (ts.isPropertyAccessChain(node)) {
70595             return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
70596         }
70597         // Because we are updating existed propertyAccess we want to inherit its emitFlags
70598         // instead of using the default from createPropertyAccess
70599         return node.expression !== expression
70600             || node.name !== name
70601             ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node)
70602             : node;
70603     }
70604     ts.updatePropertyAccess = updatePropertyAccess;
70605     function createPropertyAccessChain(expression, questionDotToken, name) {
70606         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70607         node.flags |= 32 /* OptionalChain */;
70608         node.expression = ts.parenthesizeForAccess(expression);
70609         node.questionDotToken = questionDotToken;
70610         node.name = asName(name);
70611         setEmitFlags(node, 131072 /* NoIndentation */);
70612         return node;
70613     }
70614     ts.createPropertyAccessChain = createPropertyAccessChain;
70615     function updatePropertyAccessChain(node, expression, questionDotToken, name) {
70616         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
70617         // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
70618         // instead of using the default from createPropertyAccess
70619         return node.expression !== expression
70620             || node.questionDotToken !== questionDotToken
70621             || node.name !== name
70622             ? updateNode(setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), ts.getEmitFlags(node)), node)
70623             : node;
70624     }
70625     ts.updatePropertyAccessChain = updatePropertyAccessChain;
70626     function createElementAccess(expression, index) {
70627         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70628         node.expression = ts.parenthesizeForAccess(expression);
70629         node.argumentExpression = asExpression(index);
70630         return node;
70631     }
70632     ts.createElementAccess = createElementAccess;
70633     function updateElementAccess(node, expression, argumentExpression) {
70634         if (ts.isOptionalChain(node)) {
70635             return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
70636         }
70637         return node.expression !== expression
70638             || node.argumentExpression !== argumentExpression
70639             ? updateNode(createElementAccess(expression, argumentExpression), node)
70640             : node;
70641     }
70642     ts.updateElementAccess = updateElementAccess;
70643     function createElementAccessChain(expression, questionDotToken, index) {
70644         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70645         node.flags |= 32 /* OptionalChain */;
70646         node.expression = ts.parenthesizeForAccess(expression);
70647         node.questionDotToken = questionDotToken;
70648         node.argumentExpression = asExpression(index);
70649         return node;
70650     }
70651     ts.createElementAccessChain = createElementAccessChain;
70652     function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
70653         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
70654         return node.expression !== expression
70655             || node.questionDotToken !== questionDotToken
70656             || node.argumentExpression !== argumentExpression
70657             ? updateNode(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
70658             : node;
70659     }
70660     ts.updateElementAccessChain = updateElementAccessChain;
70661     function createCall(expression, typeArguments, argumentsArray) {
70662         var node = createSynthesizedNode(196 /* CallExpression */);
70663         node.expression = ts.parenthesizeForAccess(expression);
70664         node.typeArguments = asNodeArray(typeArguments);
70665         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70666         return node;
70667     }
70668     ts.createCall = createCall;
70669     function updateCall(node, expression, typeArguments, argumentsArray) {
70670         if (ts.isOptionalChain(node)) {
70671             return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
70672         }
70673         return node.expression !== expression
70674             || node.typeArguments !== typeArguments
70675             || node.arguments !== argumentsArray
70676             ? updateNode(createCall(expression, typeArguments, argumentsArray), node)
70677             : node;
70678     }
70679     ts.updateCall = updateCall;
70680     function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
70681         var node = createSynthesizedNode(196 /* CallExpression */);
70682         node.flags |= 32 /* OptionalChain */;
70683         node.expression = ts.parenthesizeForAccess(expression);
70684         node.questionDotToken = questionDotToken;
70685         node.typeArguments = asNodeArray(typeArguments);
70686         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70687         return node;
70688     }
70689     ts.createCallChain = createCallChain;
70690     function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
70691         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
70692         return node.expression !== expression
70693             || node.questionDotToken !== questionDotToken
70694             || node.typeArguments !== typeArguments
70695             || node.arguments !== argumentsArray
70696             ? updateNode(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
70697             : node;
70698     }
70699     ts.updateCallChain = updateCallChain;
70700     function createNew(expression, typeArguments, argumentsArray) {
70701         var node = createSynthesizedNode(197 /* NewExpression */);
70702         node.expression = ts.parenthesizeForNew(expression);
70703         node.typeArguments = asNodeArray(typeArguments);
70704         node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
70705         return node;
70706     }
70707     ts.createNew = createNew;
70708     function updateNew(node, expression, typeArguments, argumentsArray) {
70709         return node.expression !== expression
70710             || node.typeArguments !== typeArguments
70711             || node.arguments !== argumentsArray
70712             ? updateNode(createNew(expression, typeArguments, argumentsArray), node)
70713             : node;
70714     }
70715     ts.updateNew = updateNew;
70716     function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) {
70717         var node = createSynthesizedNode(198 /* TaggedTemplateExpression */);
70718         node.tag = ts.parenthesizeForAccess(tag);
70719         if (template) {
70720             node.typeArguments = asNodeArray(typeArgumentsOrTemplate);
70721             node.template = template;
70722         }
70723         else {
70724             node.typeArguments = undefined;
70725             node.template = typeArgumentsOrTemplate;
70726         }
70727         return node;
70728     }
70729     ts.createTaggedTemplate = createTaggedTemplate;
70730     function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) {
70731         return node.tag !== tag
70732             || (template
70733                 ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template
70734                 : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate)
70735             ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node)
70736             : node;
70737     }
70738     ts.updateTaggedTemplate = updateTaggedTemplate;
70739     function createTypeAssertion(type, expression) {
70740         var node = createSynthesizedNode(199 /* TypeAssertionExpression */);
70741         node.type = type;
70742         node.expression = ts.parenthesizePrefixOperand(expression);
70743         return node;
70744     }
70745     ts.createTypeAssertion = createTypeAssertion;
70746     function updateTypeAssertion(node, type, expression) {
70747         return node.type !== type
70748             || node.expression !== expression
70749             ? updateNode(createTypeAssertion(type, expression), node)
70750             : node;
70751     }
70752     ts.updateTypeAssertion = updateTypeAssertion;
70753     function createParen(expression) {
70754         var node = createSynthesizedNode(200 /* ParenthesizedExpression */);
70755         node.expression = expression;
70756         return node;
70757     }
70758     ts.createParen = createParen;
70759     function updateParen(node, expression) {
70760         return node.expression !== expression
70761             ? updateNode(createParen(expression), node)
70762             : node;
70763     }
70764     ts.updateParen = updateParen;
70765     function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70766         var node = createSynthesizedNode(201 /* FunctionExpression */);
70767         node.modifiers = asNodeArray(modifiers);
70768         node.asteriskToken = asteriskToken;
70769         node.name = asName(name);
70770         node.typeParameters = asNodeArray(typeParameters);
70771         node.parameters = createNodeArray(parameters);
70772         node.type = type;
70773         node.body = body;
70774         return node;
70775     }
70776     ts.createFunctionExpression = createFunctionExpression;
70777     function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70778         return node.name !== name
70779             || node.modifiers !== modifiers
70780             || node.asteriskToken !== asteriskToken
70781             || node.typeParameters !== typeParameters
70782             || node.parameters !== parameters
70783             || node.type !== type
70784             || node.body !== body
70785             ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
70786             : node;
70787     }
70788     ts.updateFunctionExpression = updateFunctionExpression;
70789     function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70790         var node = createSynthesizedNode(202 /* ArrowFunction */);
70791         node.modifiers = asNodeArray(modifiers);
70792         node.typeParameters = asNodeArray(typeParameters);
70793         node.parameters = createNodeArray(parameters);
70794         node.type = type;
70795         node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(38 /* EqualsGreaterThanToken */);
70796         node.body = ts.parenthesizeConciseBody(body);
70797         return node;
70798     }
70799     ts.createArrowFunction = createArrowFunction;
70800     function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70801         return node.modifiers !== modifiers
70802             || node.typeParameters !== typeParameters
70803             || node.parameters !== parameters
70804             || node.type !== type
70805             || node.equalsGreaterThanToken !== equalsGreaterThanToken
70806             || node.body !== body
70807             ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
70808             : node;
70809     }
70810     ts.updateArrowFunction = updateArrowFunction;
70811     function createDelete(expression) {
70812         var node = createSynthesizedNode(203 /* DeleteExpression */);
70813         node.expression = ts.parenthesizePrefixOperand(expression);
70814         return node;
70815     }
70816     ts.createDelete = createDelete;
70817     function updateDelete(node, expression) {
70818         return node.expression !== expression
70819             ? updateNode(createDelete(expression), node)
70820             : node;
70821     }
70822     ts.updateDelete = updateDelete;
70823     function createTypeOf(expression) {
70824         var node = createSynthesizedNode(204 /* TypeOfExpression */);
70825         node.expression = ts.parenthesizePrefixOperand(expression);
70826         return node;
70827     }
70828     ts.createTypeOf = createTypeOf;
70829     function updateTypeOf(node, expression) {
70830         return node.expression !== expression
70831             ? updateNode(createTypeOf(expression), node)
70832             : node;
70833     }
70834     ts.updateTypeOf = updateTypeOf;
70835     function createVoid(expression) {
70836         var node = createSynthesizedNode(205 /* VoidExpression */);
70837         node.expression = ts.parenthesizePrefixOperand(expression);
70838         return node;
70839     }
70840     ts.createVoid = createVoid;
70841     function updateVoid(node, expression) {
70842         return node.expression !== expression
70843             ? updateNode(createVoid(expression), node)
70844             : node;
70845     }
70846     ts.updateVoid = updateVoid;
70847     function createAwait(expression) {
70848         var node = createSynthesizedNode(206 /* AwaitExpression */);
70849         node.expression = ts.parenthesizePrefixOperand(expression);
70850         return node;
70851     }
70852     ts.createAwait = createAwait;
70853     function updateAwait(node, expression) {
70854         return node.expression !== expression
70855             ? updateNode(createAwait(expression), node)
70856             : node;
70857     }
70858     ts.updateAwait = updateAwait;
70859     function createPrefix(operator, operand) {
70860         var node = createSynthesizedNode(207 /* PrefixUnaryExpression */);
70861         node.operator = operator;
70862         node.operand = ts.parenthesizePrefixOperand(operand);
70863         return node;
70864     }
70865     ts.createPrefix = createPrefix;
70866     function updatePrefix(node, operand) {
70867         return node.operand !== operand
70868             ? updateNode(createPrefix(node.operator, operand), node)
70869             : node;
70870     }
70871     ts.updatePrefix = updatePrefix;
70872     function createPostfix(operand, operator) {
70873         var node = createSynthesizedNode(208 /* PostfixUnaryExpression */);
70874         node.operand = ts.parenthesizePostfixOperand(operand);
70875         node.operator = operator;
70876         return node;
70877     }
70878     ts.createPostfix = createPostfix;
70879     function updatePostfix(node, operand) {
70880         return node.operand !== operand
70881             ? updateNode(createPostfix(operand, node.operator), node)
70882             : node;
70883     }
70884     ts.updatePostfix = updatePostfix;
70885     function createBinary(left, operator, right) {
70886         var node = createSynthesizedNode(209 /* BinaryExpression */);
70887         var operatorToken = asToken(operator);
70888         var operatorKind = operatorToken.kind;
70889         node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
70890         node.operatorToken = operatorToken;
70891         node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
70892         return node;
70893     }
70894     ts.createBinary = createBinary;
70895     function updateBinary(node, left, right, operator) {
70896         return node.left !== left
70897             || node.right !== right
70898             ? updateNode(createBinary(left, operator || node.operatorToken, right), node)
70899             : node;
70900     }
70901     ts.updateBinary = updateBinary;
70902     function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) {
70903         var node = createSynthesizedNode(210 /* ConditionalExpression */);
70904         node.condition = ts.parenthesizeForConditionalHead(condition);
70905         node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(57 /* QuestionToken */);
70906         node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue);
70907         node.colonToken = whenFalse ? colonToken : createToken(58 /* ColonToken */);
70908         node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
70909         return node;
70910     }
70911     ts.createConditional = createConditional;
70912     function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
70913         return node.condition !== condition
70914             || node.questionToken !== questionToken
70915             || node.whenTrue !== whenTrue
70916             || node.colonToken !== colonToken
70917             || node.whenFalse !== whenFalse
70918             ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node)
70919             : node;
70920     }
70921     ts.updateConditional = updateConditional;
70922     function createTemplateExpression(head, templateSpans) {
70923         var node = createSynthesizedNode(211 /* TemplateExpression */);
70924         node.head = head;
70925         node.templateSpans = createNodeArray(templateSpans);
70926         return node;
70927     }
70928     ts.createTemplateExpression = createTemplateExpression;
70929     function updateTemplateExpression(node, head, templateSpans) {
70930         return node.head !== head
70931             || node.templateSpans !== templateSpans
70932             ? updateNode(createTemplateExpression(head, templateSpans), node)
70933             : node;
70934     }
70935     ts.updateTemplateExpression = updateTemplateExpression;
70936     var rawTextScanner;
70937     var invalidValueSentinel = {};
70938     function getCookedText(kind, rawText) {
70939         if (!rawTextScanner) {
70940             rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
70941         }
70942         switch (kind) {
70943             case 14 /* NoSubstitutionTemplateLiteral */:
70944                 rawTextScanner.setText("`" + rawText + "`");
70945                 break;
70946             case 15 /* TemplateHead */:
70947                 rawTextScanner.setText("`" + rawText + "${");
70948                 break;
70949             case 16 /* TemplateMiddle */:
70950                 rawTextScanner.setText("}" + rawText + "${");
70951                 break;
70952             case 17 /* TemplateTail */:
70953                 rawTextScanner.setText("}" + rawText + "`");
70954                 break;
70955         }
70956         var token = rawTextScanner.scan();
70957         if (token === 23 /* CloseBracketToken */) {
70958             token = rawTextScanner.reScanTemplateToken(/* isTaggedTemplate */ false);
70959         }
70960         if (rawTextScanner.isUnterminated()) {
70961             rawTextScanner.setText(undefined);
70962             return invalidValueSentinel;
70963         }
70964         var tokenValue;
70965         switch (token) {
70966             case 14 /* NoSubstitutionTemplateLiteral */:
70967             case 15 /* TemplateHead */:
70968             case 16 /* TemplateMiddle */:
70969             case 17 /* TemplateTail */:
70970                 tokenValue = rawTextScanner.getTokenValue();
70971                 break;
70972         }
70973         if (rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
70974             rawTextScanner.setText(undefined);
70975             return invalidValueSentinel;
70976         }
70977         rawTextScanner.setText(undefined);
70978         return tokenValue;
70979     }
70980     function createTemplateLiteralLikeNode(kind, text, rawText) {
70981         var node = createSynthesizedNode(kind);
70982         node.text = text;
70983         if (rawText === undefined || text === rawText) {
70984             node.rawText = rawText;
70985         }
70986         else {
70987             var cooked = getCookedText(kind, rawText);
70988             if (typeof cooked === "object") {
70989                 return ts.Debug.fail("Invalid raw text");
70990             }
70991             ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
70992             node.rawText = rawText;
70993         }
70994         return node;
70995     }
70996     function createTemplateHead(text, rawText) {
70997         var node = createTemplateLiteralLikeNode(15 /* TemplateHead */, text, rawText);
70998         node.text = text;
70999         return node;
71000     }
71001     ts.createTemplateHead = createTemplateHead;
71002     function createTemplateMiddle(text, rawText) {
71003         var node = createTemplateLiteralLikeNode(16 /* TemplateMiddle */, text, rawText);
71004         node.text = text;
71005         return node;
71006     }
71007     ts.createTemplateMiddle = createTemplateMiddle;
71008     function createTemplateTail(text, rawText) {
71009         var node = createTemplateLiteralLikeNode(17 /* TemplateTail */, text, rawText);
71010         node.text = text;
71011         return node;
71012     }
71013     ts.createTemplateTail = createTemplateTail;
71014     function createNoSubstitutionTemplateLiteral(text, rawText) {
71015         var node = createTemplateLiteralLikeNode(14 /* NoSubstitutionTemplateLiteral */, text, rawText);
71016         return node;
71017     }
71018     ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral;
71019     function createYield(asteriskTokenOrExpression, expression) {
71020         var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined;
71021         expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression;
71022         var node = createSynthesizedNode(212 /* YieldExpression */);
71023         node.asteriskToken = asteriskToken;
71024         node.expression = expression && ts.parenthesizeExpressionForList(expression);
71025         return node;
71026     }
71027     ts.createYield = createYield;
71028     function updateYield(node, asteriskToken, expression) {
71029         return node.expression !== expression
71030             || node.asteriskToken !== asteriskToken
71031             ? updateNode(createYield(asteriskToken, expression), node)
71032             : node;
71033     }
71034     ts.updateYield = updateYield;
71035     function createSpread(expression) {
71036         var node = createSynthesizedNode(213 /* SpreadElement */);
71037         node.expression = ts.parenthesizeExpressionForList(expression);
71038         return node;
71039     }
71040     ts.createSpread = createSpread;
71041     function updateSpread(node, expression) {
71042         return node.expression !== expression
71043             ? updateNode(createSpread(expression), node)
71044             : node;
71045     }
71046     ts.updateSpread = updateSpread;
71047     function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
71048         var node = createSynthesizedNode(214 /* ClassExpression */);
71049         node.decorators = undefined;
71050         node.modifiers = asNodeArray(modifiers);
71051         node.name = asName(name);
71052         node.typeParameters = asNodeArray(typeParameters);
71053         node.heritageClauses = asNodeArray(heritageClauses);
71054         node.members = createNodeArray(members);
71055         return node;
71056     }
71057     ts.createClassExpression = createClassExpression;
71058     function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
71059         return node.modifiers !== modifiers
71060             || node.name !== name
71061             || node.typeParameters !== typeParameters
71062             || node.heritageClauses !== heritageClauses
71063             || node.members !== members
71064             ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node)
71065             : node;
71066     }
71067     ts.updateClassExpression = updateClassExpression;
71068     function createOmittedExpression() {
71069         return createSynthesizedNode(215 /* OmittedExpression */);
71070     }
71071     ts.createOmittedExpression = createOmittedExpression;
71072     function createExpressionWithTypeArguments(typeArguments, expression) {
71073         var node = createSynthesizedNode(216 /* ExpressionWithTypeArguments */);
71074         node.expression = ts.parenthesizeForAccess(expression);
71075         node.typeArguments = asNodeArray(typeArguments);
71076         return node;
71077     }
71078     ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments;
71079     function updateExpressionWithTypeArguments(node, typeArguments, expression) {
71080         return node.typeArguments !== typeArguments
71081             || node.expression !== expression
71082             ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
71083             : node;
71084     }
71085     ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments;
71086     function createAsExpression(expression, type) {
71087         var node = createSynthesizedNode(217 /* AsExpression */);
71088         node.expression = expression;
71089         node.type = type;
71090         return node;
71091     }
71092     ts.createAsExpression = createAsExpression;
71093     function updateAsExpression(node, expression, type) {
71094         return node.expression !== expression
71095             || node.type !== type
71096             ? updateNode(createAsExpression(expression, type), node)
71097             : node;
71098     }
71099     ts.updateAsExpression = updateAsExpression;
71100     function createNonNullExpression(expression) {
71101         var node = createSynthesizedNode(218 /* NonNullExpression */);
71102         node.expression = ts.parenthesizeForAccess(expression);
71103         return node;
71104     }
71105     ts.createNonNullExpression = createNonNullExpression;
71106     function updateNonNullExpression(node, expression) {
71107         if (ts.isNonNullChain(node)) {
71108             return updateNonNullChain(node, expression);
71109         }
71110         return node.expression !== expression
71111             ? updateNode(createNonNullExpression(expression), node)
71112             : node;
71113     }
71114     ts.updateNonNullExpression = updateNonNullExpression;
71115     function createNonNullChain(expression) {
71116         var node = createSynthesizedNode(218 /* NonNullExpression */);
71117         node.flags |= 32 /* OptionalChain */;
71118         node.expression = ts.parenthesizeForAccess(expression);
71119         return node;
71120     }
71121     ts.createNonNullChain = createNonNullChain;
71122     function updateNonNullChain(node, expression) {
71123         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
71124         return node.expression !== expression
71125             ? updateNode(createNonNullChain(expression), node)
71126             : node;
71127     }
71128     ts.updateNonNullChain = updateNonNullChain;
71129     function createMetaProperty(keywordToken, name) {
71130         var node = createSynthesizedNode(219 /* MetaProperty */);
71131         node.keywordToken = keywordToken;
71132         node.name = name;
71133         return node;
71134     }
71135     ts.createMetaProperty = createMetaProperty;
71136     function updateMetaProperty(node, name) {
71137         return node.name !== name
71138             ? updateNode(createMetaProperty(node.keywordToken, name), node)
71139             : node;
71140     }
71141     ts.updateMetaProperty = updateMetaProperty;
71142     // Misc
71143     function createTemplateSpan(expression, literal) {
71144         var node = createSynthesizedNode(221 /* TemplateSpan */);
71145         node.expression = expression;
71146         node.literal = literal;
71147         return node;
71148     }
71149     ts.createTemplateSpan = createTemplateSpan;
71150     function updateTemplateSpan(node, expression, literal) {
71151         return node.expression !== expression
71152             || node.literal !== literal
71153             ? updateNode(createTemplateSpan(expression, literal), node)
71154             : node;
71155     }
71156     ts.updateTemplateSpan = updateTemplateSpan;
71157     function createSemicolonClassElement() {
71158         return createSynthesizedNode(222 /* SemicolonClassElement */);
71159     }
71160     ts.createSemicolonClassElement = createSemicolonClassElement;
71161     // Element
71162     function createBlock(statements, multiLine) {
71163         var block = createSynthesizedNode(223 /* Block */);
71164         block.statements = createNodeArray(statements);
71165         if (multiLine)
71166             block.multiLine = multiLine;
71167         return block;
71168     }
71169     ts.createBlock = createBlock;
71170     function updateBlock(node, statements) {
71171         return node.statements !== statements
71172             ? updateNode(createBlock(statements, node.multiLine), node)
71173             : node;
71174     }
71175     ts.updateBlock = updateBlock;
71176     function createVariableStatement(modifiers, declarationList) {
71177         var node = createSynthesizedNode(225 /* VariableStatement */);
71178         node.decorators = undefined;
71179         node.modifiers = asNodeArray(modifiers);
71180         node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
71181         return node;
71182     }
71183     ts.createVariableStatement = createVariableStatement;
71184     function updateVariableStatement(node, modifiers, declarationList) {
71185         return node.modifiers !== modifiers
71186             || node.declarationList !== declarationList
71187             ? updateNode(createVariableStatement(modifiers, declarationList), node)
71188             : node;
71189     }
71190     ts.updateVariableStatement = updateVariableStatement;
71191     function createEmptyStatement() {
71192         return createSynthesizedNode(224 /* EmptyStatement */);
71193     }
71194     ts.createEmptyStatement = createEmptyStatement;
71195     function createExpressionStatement(expression) {
71196         var node = createSynthesizedNode(226 /* ExpressionStatement */);
71197         node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
71198         return node;
71199     }
71200     ts.createExpressionStatement = createExpressionStatement;
71201     function updateExpressionStatement(node, expression) {
71202         return node.expression !== expression
71203             ? updateNode(createExpressionStatement(expression), node)
71204             : node;
71205     }
71206     ts.updateExpressionStatement = updateExpressionStatement;
71207     /** @deprecated Use `createExpressionStatement` instead.  */
71208     ts.createStatement = createExpressionStatement;
71209     /** @deprecated Use `updateExpressionStatement` instead.  */
71210     ts.updateStatement = updateExpressionStatement;
71211     function createIf(expression, thenStatement, elseStatement) {
71212         var node = createSynthesizedNode(227 /* IfStatement */);
71213         node.expression = expression;
71214         node.thenStatement = asEmbeddedStatement(thenStatement);
71215         node.elseStatement = asEmbeddedStatement(elseStatement);
71216         return node;
71217     }
71218     ts.createIf = createIf;
71219     function updateIf(node, expression, thenStatement, elseStatement) {
71220         return node.expression !== expression
71221             || node.thenStatement !== thenStatement
71222             || node.elseStatement !== elseStatement
71223             ? updateNode(createIf(expression, thenStatement, elseStatement), node)
71224             : node;
71225     }
71226     ts.updateIf = updateIf;
71227     function createDo(statement, expression) {
71228         var node = createSynthesizedNode(228 /* DoStatement */);
71229         node.statement = asEmbeddedStatement(statement);
71230         node.expression = expression;
71231         return node;
71232     }
71233     ts.createDo = createDo;
71234     function updateDo(node, statement, expression) {
71235         return node.statement !== statement
71236             || node.expression !== expression
71237             ? updateNode(createDo(statement, expression), node)
71238             : node;
71239     }
71240     ts.updateDo = updateDo;
71241     function createWhile(expression, statement) {
71242         var node = createSynthesizedNode(229 /* WhileStatement */);
71243         node.expression = expression;
71244         node.statement = asEmbeddedStatement(statement);
71245         return node;
71246     }
71247     ts.createWhile = createWhile;
71248     function updateWhile(node, expression, statement) {
71249         return node.expression !== expression
71250             || node.statement !== statement
71251             ? updateNode(createWhile(expression, statement), node)
71252             : node;
71253     }
71254     ts.updateWhile = updateWhile;
71255     function createFor(initializer, condition, incrementor, statement) {
71256         var node = createSynthesizedNode(230 /* ForStatement */);
71257         node.initializer = initializer;
71258         node.condition = condition;
71259         node.incrementor = incrementor;
71260         node.statement = asEmbeddedStatement(statement);
71261         return node;
71262     }
71263     ts.createFor = createFor;
71264     function updateFor(node, initializer, condition, incrementor, statement) {
71265         return node.initializer !== initializer
71266             || node.condition !== condition
71267             || node.incrementor !== incrementor
71268             || node.statement !== statement
71269             ? updateNode(createFor(initializer, condition, incrementor, statement), node)
71270             : node;
71271     }
71272     ts.updateFor = updateFor;
71273     function createForIn(initializer, expression, statement) {
71274         var node = createSynthesizedNode(231 /* ForInStatement */);
71275         node.initializer = initializer;
71276         node.expression = expression;
71277         node.statement = asEmbeddedStatement(statement);
71278         return node;
71279     }
71280     ts.createForIn = createForIn;
71281     function updateForIn(node, initializer, expression, statement) {
71282         return node.initializer !== initializer
71283             || node.expression !== expression
71284             || node.statement !== statement
71285             ? updateNode(createForIn(initializer, expression, statement), node)
71286             : node;
71287     }
71288     ts.updateForIn = updateForIn;
71289     function createForOf(awaitModifier, initializer, expression, statement) {
71290         var node = createSynthesizedNode(232 /* ForOfStatement */);
71291         node.awaitModifier = awaitModifier;
71292         node.initializer = initializer;
71293         node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression;
71294         node.statement = asEmbeddedStatement(statement);
71295         return node;
71296     }
71297     ts.createForOf = createForOf;
71298     function updateForOf(node, awaitModifier, initializer, expression, statement) {
71299         return node.awaitModifier !== awaitModifier
71300             || node.initializer !== initializer
71301             || node.expression !== expression
71302             || node.statement !== statement
71303             ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node)
71304             : node;
71305     }
71306     ts.updateForOf = updateForOf;
71307     function createContinue(label) {
71308         var node = createSynthesizedNode(233 /* ContinueStatement */);
71309         node.label = asName(label);
71310         return node;
71311     }
71312     ts.createContinue = createContinue;
71313     function updateContinue(node, label) {
71314         return node.label !== label
71315             ? updateNode(createContinue(label), node)
71316             : node;
71317     }
71318     ts.updateContinue = updateContinue;
71319     function createBreak(label) {
71320         var node = createSynthesizedNode(234 /* BreakStatement */);
71321         node.label = asName(label);
71322         return node;
71323     }
71324     ts.createBreak = createBreak;
71325     function updateBreak(node, label) {
71326         return node.label !== label
71327             ? updateNode(createBreak(label), node)
71328             : node;
71329     }
71330     ts.updateBreak = updateBreak;
71331     function createReturn(expression) {
71332         var node = createSynthesizedNode(235 /* ReturnStatement */);
71333         node.expression = expression;
71334         return node;
71335     }
71336     ts.createReturn = createReturn;
71337     function updateReturn(node, expression) {
71338         return node.expression !== expression
71339             ? updateNode(createReturn(expression), node)
71340             : node;
71341     }
71342     ts.updateReturn = updateReturn;
71343     function createWith(expression, statement) {
71344         var node = createSynthesizedNode(236 /* WithStatement */);
71345         node.expression = expression;
71346         node.statement = asEmbeddedStatement(statement);
71347         return node;
71348     }
71349     ts.createWith = createWith;
71350     function updateWith(node, expression, statement) {
71351         return node.expression !== expression
71352             || node.statement !== statement
71353             ? updateNode(createWith(expression, statement), node)
71354             : node;
71355     }
71356     ts.updateWith = updateWith;
71357     function createSwitch(expression, caseBlock) {
71358         var node = createSynthesizedNode(237 /* SwitchStatement */);
71359         node.expression = ts.parenthesizeExpressionForList(expression);
71360         node.caseBlock = caseBlock;
71361         return node;
71362     }
71363     ts.createSwitch = createSwitch;
71364     function updateSwitch(node, expression, caseBlock) {
71365         return node.expression !== expression
71366             || node.caseBlock !== caseBlock
71367             ? updateNode(createSwitch(expression, caseBlock), node)
71368             : node;
71369     }
71370     ts.updateSwitch = updateSwitch;
71371     function createLabel(label, statement) {
71372         var node = createSynthesizedNode(238 /* LabeledStatement */);
71373         node.label = asName(label);
71374         node.statement = asEmbeddedStatement(statement);
71375         return node;
71376     }
71377     ts.createLabel = createLabel;
71378     function updateLabel(node, label, statement) {
71379         return node.label !== label
71380             || node.statement !== statement
71381             ? updateNode(createLabel(label, statement), node)
71382             : node;
71383     }
71384     ts.updateLabel = updateLabel;
71385     function createThrow(expression) {
71386         var node = createSynthesizedNode(239 /* ThrowStatement */);
71387         node.expression = expression;
71388         return node;
71389     }
71390     ts.createThrow = createThrow;
71391     function updateThrow(node, expression) {
71392         return node.expression !== expression
71393             ? updateNode(createThrow(expression), node)
71394             : node;
71395     }
71396     ts.updateThrow = updateThrow;
71397     function createTry(tryBlock, catchClause, finallyBlock) {
71398         var node = createSynthesizedNode(240 /* TryStatement */);
71399         node.tryBlock = tryBlock;
71400         node.catchClause = catchClause;
71401         node.finallyBlock = finallyBlock;
71402         return node;
71403     }
71404     ts.createTry = createTry;
71405     function updateTry(node, tryBlock, catchClause, finallyBlock) {
71406         return node.tryBlock !== tryBlock
71407             || node.catchClause !== catchClause
71408             || node.finallyBlock !== finallyBlock
71409             ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node)
71410             : node;
71411     }
71412     ts.updateTry = updateTry;
71413     function createDebuggerStatement() {
71414         return createSynthesizedNode(241 /* DebuggerStatement */);
71415     }
71416     ts.createDebuggerStatement = createDebuggerStatement;
71417     function createVariableDeclaration(name, type, initializer) {
71418         /* Internally, one should probably use createTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71419         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71420         node.name = asName(name);
71421         node.type = type;
71422         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71423         return node;
71424     }
71425     ts.createVariableDeclaration = createVariableDeclaration;
71426     function updateVariableDeclaration(node, name, type, initializer) {
71427         /* Internally, one should probably use updateTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71428         return node.name !== name
71429             || node.type !== type
71430             || node.initializer !== initializer
71431             ? updateNode(createVariableDeclaration(name, type, initializer), node)
71432             : node;
71433     }
71434     ts.updateVariableDeclaration = updateVariableDeclaration;
71435     /* @internal */
71436     function createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer) {
71437         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71438         node.name = asName(name);
71439         node.type = type;
71440         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71441         node.exclamationToken = exclaimationToken;
71442         return node;
71443     }
71444     ts.createTypeScriptVariableDeclaration = createTypeScriptVariableDeclaration;
71445     /* @internal */
71446     function updateTypeScriptVariableDeclaration(node, name, exclaimationToken, type, initializer) {
71447         return node.name !== name
71448             || node.type !== type
71449             || node.initializer !== initializer
71450             || node.exclamationToken !== exclaimationToken
71451             ? updateNode(createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer), node)
71452             : node;
71453     }
71454     ts.updateTypeScriptVariableDeclaration = updateTypeScriptVariableDeclaration;
71455     function createVariableDeclarationList(declarations, flags) {
71456         if (flags === void 0) { flags = 0 /* None */; }
71457         var node = createSynthesizedNode(243 /* VariableDeclarationList */);
71458         node.flags |= flags & 3 /* BlockScoped */;
71459         node.declarations = createNodeArray(declarations);
71460         return node;
71461     }
71462     ts.createVariableDeclarationList = createVariableDeclarationList;
71463     function updateVariableDeclarationList(node, declarations) {
71464         return node.declarations !== declarations
71465             ? updateNode(createVariableDeclarationList(declarations, node.flags), node)
71466             : node;
71467     }
71468     ts.updateVariableDeclarationList = updateVariableDeclarationList;
71469     function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71470         var node = createSynthesizedNode(244 /* FunctionDeclaration */);
71471         node.decorators = asNodeArray(decorators);
71472         node.modifiers = asNodeArray(modifiers);
71473         node.asteriskToken = asteriskToken;
71474         node.name = asName(name);
71475         node.typeParameters = asNodeArray(typeParameters);
71476         node.parameters = createNodeArray(parameters);
71477         node.type = type;
71478         node.body = body;
71479         return node;
71480     }
71481     ts.createFunctionDeclaration = createFunctionDeclaration;
71482     function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71483         return node.decorators !== decorators
71484             || node.modifiers !== modifiers
71485             || node.asteriskToken !== asteriskToken
71486             || node.name !== name
71487             || node.typeParameters !== typeParameters
71488             || node.parameters !== parameters
71489             || node.type !== type
71490             || node.body !== body
71491             ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
71492             : node;
71493     }
71494     ts.updateFunctionDeclaration = updateFunctionDeclaration;
71495     /* @internal */
71496     function updateFunctionLikeBody(declaration, body) {
71497         switch (declaration.kind) {
71498             case 244 /* FunctionDeclaration */:
71499                 return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71500             case 161 /* MethodDeclaration */:
71501                 return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body);
71502             case 163 /* GetAccessor */:
71503                 return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body);
71504             case 164 /* SetAccessor */:
71505                 return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body);
71506             case 162 /* Constructor */:
71507                 return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body);
71508             case 201 /* FunctionExpression */:
71509                 return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71510             case 202 /* ArrowFunction */:
71511                 return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body);
71512         }
71513     }
71514     ts.updateFunctionLikeBody = updateFunctionLikeBody;
71515     function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71516         var node = createSynthesizedNode(245 /* ClassDeclaration */);
71517         node.decorators = asNodeArray(decorators);
71518         node.modifiers = asNodeArray(modifiers);
71519         node.name = asName(name);
71520         node.typeParameters = asNodeArray(typeParameters);
71521         node.heritageClauses = asNodeArray(heritageClauses);
71522         node.members = createNodeArray(members);
71523         return node;
71524     }
71525     ts.createClassDeclaration = createClassDeclaration;
71526     function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71527         return node.decorators !== decorators
71528             || node.modifiers !== modifiers
71529             || node.name !== name
71530             || node.typeParameters !== typeParameters
71531             || node.heritageClauses !== heritageClauses
71532             || node.members !== members
71533             ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71534             : node;
71535     }
71536     ts.updateClassDeclaration = updateClassDeclaration;
71537     function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71538         var node = createSynthesizedNode(246 /* InterfaceDeclaration */);
71539         node.decorators = asNodeArray(decorators);
71540         node.modifiers = asNodeArray(modifiers);
71541         node.name = asName(name);
71542         node.typeParameters = asNodeArray(typeParameters);
71543         node.heritageClauses = asNodeArray(heritageClauses);
71544         node.members = createNodeArray(members);
71545         return node;
71546     }
71547     ts.createInterfaceDeclaration = createInterfaceDeclaration;
71548     function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71549         return node.decorators !== decorators
71550             || node.modifiers !== modifiers
71551             || node.name !== name
71552             || node.typeParameters !== typeParameters
71553             || node.heritageClauses !== heritageClauses
71554             || node.members !== members
71555             ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71556             : node;
71557     }
71558     ts.updateInterfaceDeclaration = updateInterfaceDeclaration;
71559     function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
71560         var node = createSynthesizedNode(247 /* TypeAliasDeclaration */);
71561         node.decorators = asNodeArray(decorators);
71562         node.modifiers = asNodeArray(modifiers);
71563         node.name = asName(name);
71564         node.typeParameters = asNodeArray(typeParameters);
71565         node.type = type;
71566         return node;
71567     }
71568     ts.createTypeAliasDeclaration = createTypeAliasDeclaration;
71569     function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
71570         return node.decorators !== decorators
71571             || node.modifiers !== modifiers
71572             || node.name !== name
71573             || node.typeParameters !== typeParameters
71574             || node.type !== type
71575             ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
71576             : node;
71577     }
71578     ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration;
71579     function createEnumDeclaration(decorators, modifiers, name, members) {
71580         var node = createSynthesizedNode(248 /* EnumDeclaration */);
71581         node.decorators = asNodeArray(decorators);
71582         node.modifiers = asNodeArray(modifiers);
71583         node.name = asName(name);
71584         node.members = createNodeArray(members);
71585         return node;
71586     }
71587     ts.createEnumDeclaration = createEnumDeclaration;
71588     function updateEnumDeclaration(node, decorators, modifiers, name, members) {
71589         return node.decorators !== decorators
71590             || node.modifiers !== modifiers
71591             || node.name !== name
71592             || node.members !== members
71593             ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node)
71594             : node;
71595     }
71596     ts.updateEnumDeclaration = updateEnumDeclaration;
71597     function createModuleDeclaration(decorators, modifiers, name, body, flags) {
71598         if (flags === void 0) { flags = 0 /* None */; }
71599         var node = createSynthesizedNode(249 /* ModuleDeclaration */);
71600         node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
71601         node.decorators = asNodeArray(decorators);
71602         node.modifiers = asNodeArray(modifiers);
71603         node.name = name;
71604         node.body = body;
71605         return node;
71606     }
71607     ts.createModuleDeclaration = createModuleDeclaration;
71608     function updateModuleDeclaration(node, decorators, modifiers, name, body) {
71609         return node.decorators !== decorators
71610             || node.modifiers !== modifiers
71611             || node.name !== name
71612             || node.body !== body
71613             ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
71614             : node;
71615     }
71616     ts.updateModuleDeclaration = updateModuleDeclaration;
71617     function createModuleBlock(statements) {
71618         var node = createSynthesizedNode(250 /* ModuleBlock */);
71619         node.statements = createNodeArray(statements);
71620         return node;
71621     }
71622     ts.createModuleBlock = createModuleBlock;
71623     function updateModuleBlock(node, statements) {
71624         return node.statements !== statements
71625             ? updateNode(createModuleBlock(statements), node)
71626             : node;
71627     }
71628     ts.updateModuleBlock = updateModuleBlock;
71629     function createCaseBlock(clauses) {
71630         var node = createSynthesizedNode(251 /* CaseBlock */);
71631         node.clauses = createNodeArray(clauses);
71632         return node;
71633     }
71634     ts.createCaseBlock = createCaseBlock;
71635     function updateCaseBlock(node, clauses) {
71636         return node.clauses !== clauses
71637             ? updateNode(createCaseBlock(clauses), node)
71638             : node;
71639     }
71640     ts.updateCaseBlock = updateCaseBlock;
71641     function createNamespaceExportDeclaration(name) {
71642         var node = createSynthesizedNode(252 /* NamespaceExportDeclaration */);
71643         node.name = asName(name);
71644         return node;
71645     }
71646     ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration;
71647     function updateNamespaceExportDeclaration(node, name) {
71648         return node.name !== name
71649             ? updateNode(createNamespaceExportDeclaration(name), node)
71650             : node;
71651     }
71652     ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration;
71653     function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
71654         var node = createSynthesizedNode(253 /* ImportEqualsDeclaration */);
71655         node.decorators = asNodeArray(decorators);
71656         node.modifiers = asNodeArray(modifiers);
71657         node.name = asName(name);
71658         node.moduleReference = moduleReference;
71659         return node;
71660     }
71661     ts.createImportEqualsDeclaration = createImportEqualsDeclaration;
71662     function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
71663         return node.decorators !== decorators
71664             || node.modifiers !== modifiers
71665             || node.name !== name
71666             || node.moduleReference !== moduleReference
71667             ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
71668             : node;
71669     }
71670     ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration;
71671     function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
71672         var node = createSynthesizedNode(254 /* ImportDeclaration */);
71673         node.decorators = asNodeArray(decorators);
71674         node.modifiers = asNodeArray(modifiers);
71675         node.importClause = importClause;
71676         node.moduleSpecifier = moduleSpecifier;
71677         return node;
71678     }
71679     ts.createImportDeclaration = createImportDeclaration;
71680     function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
71681         return node.decorators !== decorators
71682             || node.modifiers !== modifiers
71683             || node.importClause !== importClause
71684             || node.moduleSpecifier !== moduleSpecifier
71685             ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
71686             : node;
71687     }
71688     ts.updateImportDeclaration = updateImportDeclaration;
71689     function createImportClause(name, namedBindings, isTypeOnly) {
71690         if (isTypeOnly === void 0) { isTypeOnly = false; }
71691         var node = createSynthesizedNode(255 /* ImportClause */);
71692         node.name = name;
71693         node.namedBindings = namedBindings;
71694         node.isTypeOnly = isTypeOnly;
71695         return node;
71696     }
71697     ts.createImportClause = createImportClause;
71698     function updateImportClause(node, name, namedBindings, isTypeOnly) {
71699         return node.name !== name
71700             || node.namedBindings !== namedBindings
71701             || node.isTypeOnly !== isTypeOnly
71702             ? updateNode(createImportClause(name, namedBindings, isTypeOnly), node)
71703             : node;
71704     }
71705     ts.updateImportClause = updateImportClause;
71706     function createNamespaceImport(name) {
71707         var node = createSynthesizedNode(256 /* NamespaceImport */);
71708         node.name = name;
71709         return node;
71710     }
71711     ts.createNamespaceImport = createNamespaceImport;
71712     function createNamespaceExport(name) {
71713         var node = createSynthesizedNode(262 /* NamespaceExport */);
71714         node.name = name;
71715         return node;
71716     }
71717     ts.createNamespaceExport = createNamespaceExport;
71718     function updateNamespaceImport(node, name) {
71719         return node.name !== name
71720             ? updateNode(createNamespaceImport(name), node)
71721             : node;
71722     }
71723     ts.updateNamespaceImport = updateNamespaceImport;
71724     function updateNamespaceExport(node, name) {
71725         return node.name !== name
71726             ? updateNode(createNamespaceExport(name), node)
71727             : node;
71728     }
71729     ts.updateNamespaceExport = updateNamespaceExport;
71730     function createNamedImports(elements) {
71731         var node = createSynthesizedNode(257 /* NamedImports */);
71732         node.elements = createNodeArray(elements);
71733         return node;
71734     }
71735     ts.createNamedImports = createNamedImports;
71736     function updateNamedImports(node, elements) {
71737         return node.elements !== elements
71738             ? updateNode(createNamedImports(elements), node)
71739             : node;
71740     }
71741     ts.updateNamedImports = updateNamedImports;
71742     function createImportSpecifier(propertyName, name) {
71743         var node = createSynthesizedNode(258 /* ImportSpecifier */);
71744         node.propertyName = propertyName;
71745         node.name = name;
71746         return node;
71747     }
71748     ts.createImportSpecifier = createImportSpecifier;
71749     function updateImportSpecifier(node, propertyName, name) {
71750         return node.propertyName !== propertyName
71751             || node.name !== name
71752             ? updateNode(createImportSpecifier(propertyName, name), node)
71753             : node;
71754     }
71755     ts.updateImportSpecifier = updateImportSpecifier;
71756     function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
71757         var node = createSynthesizedNode(259 /* ExportAssignment */);
71758         node.decorators = asNodeArray(decorators);
71759         node.modifiers = asNodeArray(modifiers);
71760         node.isExportEquals = isExportEquals;
71761         node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(62 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression);
71762         return node;
71763     }
71764     ts.createExportAssignment = createExportAssignment;
71765     function updateExportAssignment(node, decorators, modifiers, expression) {
71766         return node.decorators !== decorators
71767             || node.modifiers !== modifiers
71768             || node.expression !== expression
71769             ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
71770             : node;
71771     }
71772     ts.updateExportAssignment = updateExportAssignment;
71773     function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71774         if (isTypeOnly === void 0) { isTypeOnly = false; }
71775         var node = createSynthesizedNode(260 /* ExportDeclaration */);
71776         node.decorators = asNodeArray(decorators);
71777         node.modifiers = asNodeArray(modifiers);
71778         node.isTypeOnly = isTypeOnly;
71779         node.exportClause = exportClause;
71780         node.moduleSpecifier = moduleSpecifier;
71781         return node;
71782     }
71783     ts.createExportDeclaration = createExportDeclaration;
71784     function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71785         return node.decorators !== decorators
71786             || node.modifiers !== modifiers
71787             || node.isTypeOnly !== isTypeOnly
71788             || node.exportClause !== exportClause
71789             || node.moduleSpecifier !== moduleSpecifier
71790             ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly), node)
71791             : node;
71792     }
71793     ts.updateExportDeclaration = updateExportDeclaration;
71794     /* @internal */
71795     function createEmptyExports() {
71796         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([]), /*moduleSpecifier*/ undefined);
71797     }
71798     ts.createEmptyExports = createEmptyExports;
71799     function createNamedExports(elements) {
71800         var node = createSynthesizedNode(261 /* NamedExports */);
71801         node.elements = createNodeArray(elements);
71802         return node;
71803     }
71804     ts.createNamedExports = createNamedExports;
71805     function updateNamedExports(node, elements) {
71806         return node.elements !== elements
71807             ? updateNode(createNamedExports(elements), node)
71808             : node;
71809     }
71810     ts.updateNamedExports = updateNamedExports;
71811     function createExportSpecifier(propertyName, name) {
71812         var node = createSynthesizedNode(263 /* ExportSpecifier */);
71813         node.propertyName = asName(propertyName);
71814         node.name = asName(name);
71815         return node;
71816     }
71817     ts.createExportSpecifier = createExportSpecifier;
71818     function updateExportSpecifier(node, propertyName, name) {
71819         return node.propertyName !== propertyName
71820             || node.name !== name
71821             ? updateNode(createExportSpecifier(propertyName, name), node)
71822             : node;
71823     }
71824     ts.updateExportSpecifier = updateExportSpecifier;
71825     // Module references
71826     function createExternalModuleReference(expression) {
71827         var node = createSynthesizedNode(265 /* ExternalModuleReference */);
71828         node.expression = expression;
71829         return node;
71830     }
71831     ts.createExternalModuleReference = createExternalModuleReference;
71832     function updateExternalModuleReference(node, expression) {
71833         return node.expression !== expression
71834             ? updateNode(createExternalModuleReference(expression), node)
71835             : node;
71836     }
71837     ts.updateExternalModuleReference = updateExternalModuleReference;
71838     // JSDoc
71839     /* @internal */
71840     function createJSDocTypeExpression(type) {
71841         var node = createSynthesizedNode(294 /* JSDocTypeExpression */);
71842         node.type = type;
71843         return node;
71844     }
71845     ts.createJSDocTypeExpression = createJSDocTypeExpression;
71846     /* @internal */
71847     function createJSDocTypeTag(typeExpression, comment) {
71848         var tag = createJSDocTag(320 /* JSDocTypeTag */, "type");
71849         tag.typeExpression = typeExpression;
71850         tag.comment = comment;
71851         return tag;
71852     }
71853     ts.createJSDocTypeTag = createJSDocTypeTag;
71854     /* @internal */
71855     function createJSDocReturnTag(typeExpression, comment) {
71856         var tag = createJSDocTag(318 /* JSDocReturnTag */, "returns");
71857         tag.typeExpression = typeExpression;
71858         tag.comment = comment;
71859         return tag;
71860     }
71861     ts.createJSDocReturnTag = createJSDocReturnTag;
71862     /** @internal */
71863     function createJSDocThisTag(typeExpression) {
71864         var tag = createJSDocTag(319 /* JSDocThisTag */, "this");
71865         tag.typeExpression = typeExpression;
71866         return tag;
71867     }
71868     ts.createJSDocThisTag = createJSDocThisTag;
71869     /* @internal */
71870     function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
71871         var tag = createJSDocTag(317 /* JSDocParameterTag */, "param");
71872         tag.typeExpression = typeExpression;
71873         tag.name = name;
71874         tag.isBracketed = isBracketed;
71875         tag.comment = comment;
71876         return tag;
71877     }
71878     ts.createJSDocParamTag = createJSDocParamTag;
71879     /* @internal */
71880     function createJSDocClassTag() {
71881         return createJSDocTag(310 /* JSDocClassTag */, "class");
71882     }
71883     ts.createJSDocClassTag = createJSDocClassTag;
71884     /* @internal */
71885     function createJSDocComment(comment, tags) {
71886         var node = createSynthesizedNode(303 /* JSDocComment */);
71887         node.comment = comment;
71888         node.tags = tags;
71889         return node;
71890     }
71891     ts.createJSDocComment = createJSDocComment;
71892     /* @internal */
71893     function createJSDocTag(kind, tagName) {
71894         var node = createSynthesizedNode(kind);
71895         node.tagName = createIdentifier(tagName);
71896         return node;
71897     }
71898     // JSX
71899     function createJsxElement(openingElement, children, closingElement) {
71900         var node = createSynthesizedNode(266 /* JsxElement */);
71901         node.openingElement = openingElement;
71902         node.children = createNodeArray(children);
71903         node.closingElement = closingElement;
71904         return node;
71905     }
71906     ts.createJsxElement = createJsxElement;
71907     function updateJsxElement(node, openingElement, children, closingElement) {
71908         return node.openingElement !== openingElement
71909             || node.children !== children
71910             || node.closingElement !== closingElement
71911             ? updateNode(createJsxElement(openingElement, children, closingElement), node)
71912             : node;
71913     }
71914     ts.updateJsxElement = updateJsxElement;
71915     function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
71916         var node = createSynthesizedNode(267 /* JsxSelfClosingElement */);
71917         node.tagName = tagName;
71918         node.typeArguments = asNodeArray(typeArguments);
71919         node.attributes = attributes;
71920         return node;
71921     }
71922     ts.createJsxSelfClosingElement = createJsxSelfClosingElement;
71923     function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
71924         return node.tagName !== tagName
71925             || node.typeArguments !== typeArguments
71926             || node.attributes !== attributes
71927             ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
71928             : node;
71929     }
71930     ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement;
71931     function createJsxOpeningElement(tagName, typeArguments, attributes) {
71932         var node = createSynthesizedNode(268 /* JsxOpeningElement */);
71933         node.tagName = tagName;
71934         node.typeArguments = asNodeArray(typeArguments);
71935         node.attributes = attributes;
71936         return node;
71937     }
71938     ts.createJsxOpeningElement = createJsxOpeningElement;
71939     function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
71940         return node.tagName !== tagName
71941             || node.typeArguments !== typeArguments
71942             || node.attributes !== attributes
71943             ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node)
71944             : node;
71945     }
71946     ts.updateJsxOpeningElement = updateJsxOpeningElement;
71947     function createJsxClosingElement(tagName) {
71948         var node = createSynthesizedNode(269 /* JsxClosingElement */);
71949         node.tagName = tagName;
71950         return node;
71951     }
71952     ts.createJsxClosingElement = createJsxClosingElement;
71953     function updateJsxClosingElement(node, tagName) {
71954         return node.tagName !== tagName
71955             ? updateNode(createJsxClosingElement(tagName), node)
71956             : node;
71957     }
71958     ts.updateJsxClosingElement = updateJsxClosingElement;
71959     function createJsxFragment(openingFragment, children, closingFragment) {
71960         var node = createSynthesizedNode(270 /* JsxFragment */);
71961         node.openingFragment = openingFragment;
71962         node.children = createNodeArray(children);
71963         node.closingFragment = closingFragment;
71964         return node;
71965     }
71966     ts.createJsxFragment = createJsxFragment;
71967     function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
71968         var node = createSynthesizedNode(11 /* JsxText */);
71969         node.text = text;
71970         node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
71971         return node;
71972     }
71973     ts.createJsxText = createJsxText;
71974     function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
71975         return node.text !== text
71976             || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
71977             ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
71978             : node;
71979     }
71980     ts.updateJsxText = updateJsxText;
71981     function createJsxOpeningFragment() {
71982         return createSynthesizedNode(271 /* JsxOpeningFragment */);
71983     }
71984     ts.createJsxOpeningFragment = createJsxOpeningFragment;
71985     function createJsxJsxClosingFragment() {
71986         return createSynthesizedNode(272 /* JsxClosingFragment */);
71987     }
71988     ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
71989     function updateJsxFragment(node, openingFragment, children, closingFragment) {
71990         return node.openingFragment !== openingFragment
71991             || node.children !== children
71992             || node.closingFragment !== closingFragment
71993             ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node)
71994             : node;
71995     }
71996     ts.updateJsxFragment = updateJsxFragment;
71997     function createJsxAttribute(name, initializer) {
71998         var node = createSynthesizedNode(273 /* JsxAttribute */);
71999         node.name = name;
72000         node.initializer = initializer;
72001         return node;
72002     }
72003     ts.createJsxAttribute = createJsxAttribute;
72004     function updateJsxAttribute(node, name, initializer) {
72005         return node.name !== name
72006             || node.initializer !== initializer
72007             ? updateNode(createJsxAttribute(name, initializer), node)
72008             : node;
72009     }
72010     ts.updateJsxAttribute = updateJsxAttribute;
72011     function createJsxAttributes(properties) {
72012         var node = createSynthesizedNode(274 /* JsxAttributes */);
72013         node.properties = createNodeArray(properties);
72014         return node;
72015     }
72016     ts.createJsxAttributes = createJsxAttributes;
72017     function updateJsxAttributes(node, properties) {
72018         return node.properties !== properties
72019             ? updateNode(createJsxAttributes(properties), node)
72020             : node;
72021     }
72022     ts.updateJsxAttributes = updateJsxAttributes;
72023     function createJsxSpreadAttribute(expression) {
72024         var node = createSynthesizedNode(275 /* JsxSpreadAttribute */);
72025         node.expression = expression;
72026         return node;
72027     }
72028     ts.createJsxSpreadAttribute = createJsxSpreadAttribute;
72029     function updateJsxSpreadAttribute(node, expression) {
72030         return node.expression !== expression
72031             ? updateNode(createJsxSpreadAttribute(expression), node)
72032             : node;
72033     }
72034     ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute;
72035     function createJsxExpression(dotDotDotToken, expression) {
72036         var node = createSynthesizedNode(276 /* JsxExpression */);
72037         node.dotDotDotToken = dotDotDotToken;
72038         node.expression = expression;
72039         return node;
72040     }
72041     ts.createJsxExpression = createJsxExpression;
72042     function updateJsxExpression(node, expression) {
72043         return node.expression !== expression
72044             ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node)
72045             : node;
72046     }
72047     ts.updateJsxExpression = updateJsxExpression;
72048     // Clauses
72049     function createCaseClause(expression, statements) {
72050         var node = createSynthesizedNode(277 /* CaseClause */);
72051         node.expression = ts.parenthesizeExpressionForList(expression);
72052         node.statements = createNodeArray(statements);
72053         return node;
72054     }
72055     ts.createCaseClause = createCaseClause;
72056     function updateCaseClause(node, expression, statements) {
72057         return node.expression !== expression
72058             || node.statements !== statements
72059             ? updateNode(createCaseClause(expression, statements), node)
72060             : node;
72061     }
72062     ts.updateCaseClause = updateCaseClause;
72063     function createDefaultClause(statements) {
72064         var node = createSynthesizedNode(278 /* DefaultClause */);
72065         node.statements = createNodeArray(statements);
72066         return node;
72067     }
72068     ts.createDefaultClause = createDefaultClause;
72069     function updateDefaultClause(node, statements) {
72070         return node.statements !== statements
72071             ? updateNode(createDefaultClause(statements), node)
72072             : node;
72073     }
72074     ts.updateDefaultClause = updateDefaultClause;
72075     function createHeritageClause(token, types) {
72076         var node = createSynthesizedNode(279 /* HeritageClause */);
72077         node.token = token;
72078         node.types = createNodeArray(types);
72079         return node;
72080     }
72081     ts.createHeritageClause = createHeritageClause;
72082     function updateHeritageClause(node, types) {
72083         return node.types !== types
72084             ? updateNode(createHeritageClause(node.token, types), node)
72085             : node;
72086     }
72087     ts.updateHeritageClause = updateHeritageClause;
72088     function createCatchClause(variableDeclaration, block) {
72089         var node = createSynthesizedNode(280 /* CatchClause */);
72090         node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration;
72091         node.block = block;
72092         return node;
72093     }
72094     ts.createCatchClause = createCatchClause;
72095     function updateCatchClause(node, variableDeclaration, block) {
72096         return node.variableDeclaration !== variableDeclaration
72097             || node.block !== block
72098             ? updateNode(createCatchClause(variableDeclaration, block), node)
72099             : node;
72100     }
72101     ts.updateCatchClause = updateCatchClause;
72102     // Property assignments
72103     function createPropertyAssignment(name, initializer) {
72104         var node = createSynthesizedNode(281 /* PropertyAssignment */);
72105         node.name = asName(name);
72106         node.questionToken = undefined;
72107         node.initializer = ts.parenthesizeExpressionForList(initializer);
72108         return node;
72109     }
72110     ts.createPropertyAssignment = createPropertyAssignment;
72111     function updatePropertyAssignment(node, name, initializer) {
72112         return node.name !== name
72113             || node.initializer !== initializer
72114             ? updateNode(createPropertyAssignment(name, initializer), node)
72115             : node;
72116     }
72117     ts.updatePropertyAssignment = updatePropertyAssignment;
72118     function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
72119         var node = createSynthesizedNode(282 /* ShorthandPropertyAssignment */);
72120         node.name = asName(name);
72121         node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined;
72122         return node;
72123     }
72124     ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment;
72125     function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
72126         return node.name !== name
72127             || node.objectAssignmentInitializer !== objectAssignmentInitializer
72128             ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
72129             : node;
72130     }
72131     ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment;
72132     function createSpreadAssignment(expression) {
72133         var node = createSynthesizedNode(283 /* SpreadAssignment */);
72134         node.expression = ts.parenthesizeExpressionForList(expression);
72135         return node;
72136     }
72137     ts.createSpreadAssignment = createSpreadAssignment;
72138     function updateSpreadAssignment(node, expression) {
72139         return node.expression !== expression
72140             ? updateNode(createSpreadAssignment(expression), node)
72141             : node;
72142     }
72143     ts.updateSpreadAssignment = updateSpreadAssignment;
72144     // Enum
72145     function createEnumMember(name, initializer) {
72146         var node = createSynthesizedNode(284 /* EnumMember */);
72147         node.name = asName(name);
72148         node.initializer = initializer && ts.parenthesizeExpressionForList(initializer);
72149         return node;
72150     }
72151     ts.createEnumMember = createEnumMember;
72152     function updateEnumMember(node, name, initializer) {
72153         return node.name !== name
72154             || node.initializer !== initializer
72155             ? updateNode(createEnumMember(name, initializer), node)
72156             : node;
72157     }
72158     ts.updateEnumMember = updateEnumMember;
72159     // Top-level nodes
72160     function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
72161         if (node.statements !== statements ||
72162             (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) ||
72163             (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) ||
72164             (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
72165             (libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
72166             (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
72167             var updated = createSynthesizedNode(290 /* SourceFile */);
72168             updated.flags |= node.flags;
72169             updated.statements = createNodeArray(statements);
72170             updated.endOfFileToken = node.endOfFileToken;
72171             updated.fileName = node.fileName;
72172             updated.path = node.path;
72173             updated.text = node.text;
72174             updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile;
72175             updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles;
72176             updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences;
72177             updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib;
72178             updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences;
72179             if (node.amdDependencies !== undefined)
72180                 updated.amdDependencies = node.amdDependencies;
72181             if (node.moduleName !== undefined)
72182                 updated.moduleName = node.moduleName;
72183             if (node.languageVariant !== undefined)
72184                 updated.languageVariant = node.languageVariant;
72185             if (node.renamedDependencies !== undefined)
72186                 updated.renamedDependencies = node.renamedDependencies;
72187             if (node.languageVersion !== undefined)
72188                 updated.languageVersion = node.languageVersion;
72189             if (node.scriptKind !== undefined)
72190                 updated.scriptKind = node.scriptKind;
72191             if (node.externalModuleIndicator !== undefined)
72192                 updated.externalModuleIndicator = node.externalModuleIndicator;
72193             if (node.commonJsModuleIndicator !== undefined)
72194                 updated.commonJsModuleIndicator = node.commonJsModuleIndicator;
72195             if (node.identifiers !== undefined)
72196                 updated.identifiers = node.identifiers;
72197             if (node.nodeCount !== undefined)
72198                 updated.nodeCount = node.nodeCount;
72199             if (node.identifierCount !== undefined)
72200                 updated.identifierCount = node.identifierCount;
72201             if (node.symbolCount !== undefined)
72202                 updated.symbolCount = node.symbolCount;
72203             if (node.parseDiagnostics !== undefined)
72204                 updated.parseDiagnostics = node.parseDiagnostics;
72205             if (node.bindDiagnostics !== undefined)
72206                 updated.bindDiagnostics = node.bindDiagnostics;
72207             if (node.bindSuggestionDiagnostics !== undefined)
72208                 updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics;
72209             if (node.lineMap !== undefined)
72210                 updated.lineMap = node.lineMap;
72211             if (node.classifiableNames !== undefined)
72212                 updated.classifiableNames = node.classifiableNames;
72213             if (node.resolvedModules !== undefined)
72214                 updated.resolvedModules = node.resolvedModules;
72215             if (node.resolvedTypeReferenceDirectiveNames !== undefined)
72216                 updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames;
72217             if (node.imports !== undefined)
72218                 updated.imports = node.imports;
72219             if (node.moduleAugmentations !== undefined)
72220                 updated.moduleAugmentations = node.moduleAugmentations;
72221             if (node.pragmas !== undefined)
72222                 updated.pragmas = node.pragmas;
72223             if (node.localJsxFactory !== undefined)
72224                 updated.localJsxFactory = node.localJsxFactory;
72225             if (node.localJsxNamespace !== undefined)
72226                 updated.localJsxNamespace = node.localJsxNamespace;
72227             return updateNode(updated, node);
72228         }
72229         return node;
72230     }
72231     ts.updateSourceFileNode = updateSourceFileNode;
72232     /**
72233      * Creates a shallow, memberwise clone of a node for mutation.
72234      */
72235     function getMutableClone(node) {
72236         var clone = getSynthesizedClone(node);
72237         clone.pos = node.pos;
72238         clone.end = node.end;
72239         clone.parent = node.parent;
72240         return clone;
72241     }
72242     ts.getMutableClone = getMutableClone;
72243     // Transformation nodes
72244     /**
72245      * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
72246      * order to preserve comments.
72247      *
72248      * @param original The original statement.
72249      */
72250     function createNotEmittedStatement(original) {
72251         var node = createSynthesizedNode(325 /* NotEmittedStatement */);
72252         node.original = original;
72253         setTextRange(node, original);
72254         return node;
72255     }
72256     ts.createNotEmittedStatement = createNotEmittedStatement;
72257     /**
72258      * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
72259      * order to properly emit exports.
72260      */
72261     /* @internal */
72262     function createEndOfDeclarationMarker(original) {
72263         var node = createSynthesizedNode(329 /* EndOfDeclarationMarker */);
72264         node.emitNode = {};
72265         node.original = original;
72266         return node;
72267     }
72268     ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker;
72269     /**
72270      * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
72271      * order to properly emit exports.
72272      */
72273     /* @internal */
72274     function createMergeDeclarationMarker(original) {
72275         var node = createSynthesizedNode(328 /* MergeDeclarationMarker */);
72276         node.emitNode = {};
72277         node.original = original;
72278         return node;
72279     }
72280     ts.createMergeDeclarationMarker = createMergeDeclarationMarker;
72281     /**
72282      * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
72283      * order to preserve comments or sourcemap positions.
72284      *
72285      * @param expression The inner expression to emit.
72286      * @param original The original outer expression.
72287      * @param location The location for the expression. Defaults to the positions from "original" if provided.
72288      */
72289     function createPartiallyEmittedExpression(expression, original) {
72290         var node = createSynthesizedNode(326 /* PartiallyEmittedExpression */);
72291         node.expression = expression;
72292         node.original = original;
72293         setTextRange(node, original);
72294         return node;
72295     }
72296     ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression;
72297     function updatePartiallyEmittedExpression(node, expression) {
72298         if (node.expression !== expression) {
72299             return updateNode(createPartiallyEmittedExpression(expression, node.original), node);
72300         }
72301         return node;
72302     }
72303     ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
72304     function flattenCommaElements(node) {
72305         if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
72306             if (node.kind === 327 /* CommaListExpression */) {
72307                 return node.elements;
72308             }
72309             if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
72310                 return [node.left, node.right];
72311             }
72312         }
72313         return node;
72314     }
72315     function createCommaList(elements) {
72316         var node = createSynthesizedNode(327 /* CommaListExpression */);
72317         node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
72318         return node;
72319     }
72320     ts.createCommaList = createCommaList;
72321     function updateCommaList(node, elements) {
72322         return node.elements !== elements
72323             ? updateNode(createCommaList(elements), node)
72324             : node;
72325     }
72326     ts.updateCommaList = updateCommaList;
72327     /* @internal */
72328     function createSyntheticReferenceExpression(expression, thisArg) {
72329         var node = createSynthesizedNode(330 /* SyntheticReferenceExpression */);
72330         node.expression = expression;
72331         node.thisArg = thisArg;
72332         return node;
72333     }
72334     ts.createSyntheticReferenceExpression = createSyntheticReferenceExpression;
72335     /* @internal */
72336     function updateSyntheticReferenceExpression(node, expression, thisArg) {
72337         return node.expression !== expression
72338             || node.thisArg !== thisArg
72339             ? updateNode(createSyntheticReferenceExpression(expression, thisArg), node)
72340             : node;
72341     }
72342     ts.updateSyntheticReferenceExpression = updateSyntheticReferenceExpression;
72343     function createBundle(sourceFiles, prepends) {
72344         if (prepends === void 0) { prepends = ts.emptyArray; }
72345         var node = ts.createNode(291 /* Bundle */);
72346         node.prepends = prepends;
72347         node.sourceFiles = sourceFiles;
72348         return node;
72349     }
72350     ts.createBundle = createBundle;
72351     var allUnscopedEmitHelpers;
72352     function getAllUnscopedEmitHelpers() {
72353         return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
72354             ts.valuesHelper,
72355             ts.readHelper,
72356             ts.spreadHelper,
72357             ts.spreadArraysHelper,
72358             ts.restHelper,
72359             ts.decorateHelper,
72360             ts.metadataHelper,
72361             ts.paramHelper,
72362             ts.awaiterHelper,
72363             ts.assignHelper,
72364             ts.awaitHelper,
72365             ts.asyncGeneratorHelper,
72366             ts.asyncDelegator,
72367             ts.asyncValues,
72368             ts.extendsHelper,
72369             ts.templateObjectHelper,
72370             ts.generatorHelper,
72371             ts.importStarHelper,
72372             ts.importDefaultHelper,
72373             ts.classPrivateFieldGetHelper,
72374             ts.classPrivateFieldSetHelper,
72375             ts.createBindingHelper,
72376             ts.setModuleDefaultHelper
72377         ], function (helper) { return helper.name; }));
72378     }
72379     function createUnparsedSource() {
72380         var node = ts.createNode(292 /* UnparsedSource */);
72381         node.prologues = ts.emptyArray;
72382         node.referencedFiles = ts.emptyArray;
72383         node.libReferenceDirectives = ts.emptyArray;
72384         node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
72385         return node;
72386     }
72387     function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
72388         var node = createUnparsedSource();
72389         var stripInternal;
72390         var bundleFileInfo;
72391         if (!ts.isString(textOrInputFiles)) {
72392             ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
72393             node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
72394             node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
72395             Object.defineProperties(node, {
72396                 text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
72397                 sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
72398             });
72399             if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
72400                 node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
72401                 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
72402                 stripInternal = mapTextOrStripInternal;
72403                 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
72404                 if (node.oldFileOfCurrentEmit) {
72405                     parseOldFileOfCurrentEmit(node, ts.Debug.checkDefined(bundleFileInfo));
72406                     return node;
72407                 }
72408             }
72409         }
72410         else {
72411             node.fileName = "";
72412             node.text = textOrInputFiles;
72413             node.sourceMapPath = mapPathOrType;
72414             node.sourceMapText = mapTextOrStripInternal;
72415         }
72416         ts.Debug.assert(!node.oldFileOfCurrentEmit);
72417         parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
72418         return node;
72419     }
72420     ts.createUnparsedSourceFile = createUnparsedSourceFile;
72421     function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
72422         var prologues;
72423         var helpers;
72424         var referencedFiles;
72425         var typeReferenceDirectives;
72426         var libReferenceDirectives;
72427         var texts;
72428         for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
72429             var section = _a[_i];
72430             switch (section.kind) {
72431                 case "prologue" /* Prologue */:
72432                     (prologues || (prologues = [])).push(createUnparsedNode(section, node));
72433                     break;
72434                 case "emitHelpers" /* EmitHelpers */:
72435                     (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
72436                     break;
72437                 case "no-default-lib" /* NoDefaultLib */:
72438                     node.hasNoDefaultLib = true;
72439                     break;
72440                 case "reference" /* Reference */:
72441                     (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
72442                     break;
72443                 case "type" /* Type */:
72444                     (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
72445                     break;
72446                 case "lib" /* Lib */:
72447                     (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
72448                     break;
72449                 case "prepend" /* Prepend */:
72450                     var prependNode = createUnparsedNode(section, node);
72451                     var prependTexts = void 0;
72452                     for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
72453                         var text = _c[_b];
72454                         if (!stripInternal || text.kind !== "internal" /* Internal */) {
72455                             (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
72456                         }
72457                     }
72458                     prependNode.texts = prependTexts || ts.emptyArray;
72459                     (texts || (texts = [])).push(prependNode);
72460                     break;
72461                 case "internal" /* Internal */:
72462                     if (stripInternal) {
72463                         if (!texts)
72464                             texts = [];
72465                         break;
72466                     }
72467                 // falls through
72468                 case "text" /* Text */:
72469                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72470                     break;
72471                 default:
72472                     ts.Debug.assertNever(section);
72473             }
72474         }
72475         node.prologues = prologues || ts.emptyArray;
72476         node.helpers = helpers;
72477         node.referencedFiles = referencedFiles || ts.emptyArray;
72478         node.typeReferenceDirectives = typeReferenceDirectives;
72479         node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
72480         node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
72481     }
72482     function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
72483         ts.Debug.assert(!!node.oldFileOfCurrentEmit);
72484         var texts;
72485         var syntheticReferences;
72486         for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
72487             var section = _a[_i];
72488             switch (section.kind) {
72489                 case "internal" /* Internal */:
72490                 case "text" /* Text */:
72491                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72492                     break;
72493                 case "no-default-lib" /* NoDefaultLib */:
72494                 case "reference" /* Reference */:
72495                 case "type" /* Type */:
72496                 case "lib" /* Lib */:
72497                     (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
72498                     break;
72499                 // Ignore
72500                 case "prologue" /* Prologue */:
72501                 case "emitHelpers" /* EmitHelpers */:
72502                 case "prepend" /* Prepend */:
72503                     break;
72504                 default:
72505                     ts.Debug.assertNever(section);
72506             }
72507         }
72508         node.texts = texts || ts.emptyArray;
72509         node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
72510         node.syntheticReferences = syntheticReferences;
72511         return node;
72512     }
72513     function mapBundleFileSectionKindToSyntaxKind(kind) {
72514         switch (kind) {
72515             case "prologue" /* Prologue */: return 285 /* UnparsedPrologue */;
72516             case "prepend" /* Prepend */: return 286 /* UnparsedPrepend */;
72517             case "internal" /* Internal */: return 288 /* UnparsedInternalText */;
72518             case "text" /* Text */: return 287 /* UnparsedText */;
72519             case "emitHelpers" /* EmitHelpers */:
72520             case "no-default-lib" /* NoDefaultLib */:
72521             case "reference" /* Reference */:
72522             case "type" /* Type */:
72523             case "lib" /* Lib */:
72524                 return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
72525             default:
72526                 return ts.Debug.assertNever(kind);
72527         }
72528     }
72529     function createUnparsedNode(section, parent) {
72530         var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
72531         node.parent = parent;
72532         node.data = section.data;
72533         return node;
72534     }
72535     function createUnparsedSyntheticReference(section, parent) {
72536         var node = ts.createNode(289 /* UnparsedSyntheticReference */, section.pos, section.end);
72537         node.parent = parent;
72538         node.data = section.data;
72539         node.section = section;
72540         return node;
72541     }
72542     function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
72543         var node = ts.createNode(293 /* InputFiles */);
72544         if (!ts.isString(javascriptTextOrReadFileText)) {
72545             var cache_1 = ts.createMap();
72546             var textGetter_1 = function (path) {
72547                 if (path === undefined)
72548                     return undefined;
72549                 var value = cache_1.get(path);
72550                 if (value === undefined) {
72551                     value = javascriptTextOrReadFileText(path);
72552                     cache_1.set(path, value !== undefined ? value : false);
72553                 }
72554                 return value !== false ? value : undefined;
72555             };
72556             var definedTextGetter_1 = function (path) {
72557                 var result = textGetter_1(path);
72558                 return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
72559             };
72560             var buildInfo_1;
72561             var getAndCacheBuildInfo_1 = function (getText) {
72562                 if (buildInfo_1 === undefined) {
72563                     var result = getText();
72564                     buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
72565                 }
72566                 return buildInfo_1 || undefined;
72567             };
72568             node.javascriptPath = declarationTextOrJavascriptPath;
72569             node.javascriptMapPath = javascriptMapPath;
72570             node.declarationPath = ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath);
72571             node.declarationMapPath = declarationMapPath;
72572             node.buildInfoPath = declarationMapTextOrBuildInfoPath;
72573             Object.defineProperties(node, {
72574                 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
72575                 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
72576                 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } },
72577                 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
72578                 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
72579             });
72580         }
72581         else {
72582             node.javascriptText = javascriptTextOrReadFileText;
72583             node.javascriptMapPath = javascriptMapPath;
72584             node.javascriptMapText = javascriptMapTextOrDeclarationPath;
72585             node.declarationText = declarationTextOrJavascriptPath;
72586             node.declarationMapPath = declarationMapPath;
72587             node.declarationMapText = declarationMapTextOrBuildInfoPath;
72588             node.javascriptPath = javascriptPath;
72589             node.declarationPath = declarationPath;
72590             node.buildInfoPath = buildInfoPath;
72591             node.buildInfo = buildInfo;
72592             node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
72593         }
72594         return node;
72595     }
72596     ts.createInputFiles = createInputFiles;
72597     function updateBundle(node, sourceFiles, prepends) {
72598         if (prepends === void 0) { prepends = ts.emptyArray; }
72599         if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
72600             return createBundle(sourceFiles, prepends);
72601         }
72602         return node;
72603     }
72604     ts.updateBundle = updateBundle;
72605     function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
72606         return createCall(createFunctionExpression(
72607         /*modifiers*/ undefined, 
72608         /*asteriskToken*/ undefined, 
72609         /*name*/ undefined, 
72610         /*typeParameters*/ undefined, 
72611         /*parameters*/ param ? [param] : [], 
72612         /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72613         /*typeArguments*/ undefined, 
72614         /*argumentsArray*/ paramValue ? [paramValue] : []);
72615     }
72616     ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression;
72617     function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
72618         return createCall(createArrowFunction(
72619         /*modifiers*/ undefined, 
72620         /*typeParameters*/ undefined, 
72621         /*parameters*/ param ? [param] : [], 
72622         /*type*/ undefined, 
72623         /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72624         /*typeArguments*/ undefined, 
72625         /*argumentsArray*/ paramValue ? [paramValue] : []);
72626     }
72627     ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction;
72628     function createComma(left, right) {
72629         return createBinary(left, 27 /* CommaToken */, right);
72630     }
72631     ts.createComma = createComma;
72632     function createLessThan(left, right) {
72633         return createBinary(left, 29 /* LessThanToken */, right);
72634     }
72635     ts.createLessThan = createLessThan;
72636     function createAssignment(left, right) {
72637         return createBinary(left, 62 /* EqualsToken */, right);
72638     }
72639     ts.createAssignment = createAssignment;
72640     function createStrictEquality(left, right) {
72641         return createBinary(left, 36 /* EqualsEqualsEqualsToken */, right);
72642     }
72643     ts.createStrictEquality = createStrictEquality;
72644     function createStrictInequality(left, right) {
72645         return createBinary(left, 37 /* ExclamationEqualsEqualsToken */, right);
72646     }
72647     ts.createStrictInequality = createStrictInequality;
72648     function createAdd(left, right) {
72649         return createBinary(left, 39 /* PlusToken */, right);
72650     }
72651     ts.createAdd = createAdd;
72652     function createSubtract(left, right) {
72653         return createBinary(left, 40 /* MinusToken */, right);
72654     }
72655     ts.createSubtract = createSubtract;
72656     function createPostfixIncrement(operand) {
72657         return createPostfix(operand, 45 /* PlusPlusToken */);
72658     }
72659     ts.createPostfixIncrement = createPostfixIncrement;
72660     function createLogicalAnd(left, right) {
72661         return createBinary(left, 55 /* AmpersandAmpersandToken */, right);
72662     }
72663     ts.createLogicalAnd = createLogicalAnd;
72664     function createLogicalOr(left, right) {
72665         return createBinary(left, 56 /* BarBarToken */, right);
72666     }
72667     ts.createLogicalOr = createLogicalOr;
72668     function createNullishCoalesce(left, right) {
72669         return createBinary(left, 60 /* QuestionQuestionToken */, right);
72670     }
72671     ts.createNullishCoalesce = createNullishCoalesce;
72672     function createLogicalNot(operand) {
72673         return createPrefix(53 /* ExclamationToken */, operand);
72674     }
72675     ts.createLogicalNot = createLogicalNot;
72676     function createVoidZero() {
72677         return createVoid(createLiteral(0));
72678     }
72679     ts.createVoidZero = createVoidZero;
72680     function createExportDefault(expression) {
72681         return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
72682     }
72683     ts.createExportDefault = createExportDefault;
72684     function createExternalModuleExport(exportName) {
72685         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)]));
72686     }
72687     ts.createExternalModuleExport = createExternalModuleExport;
72688     // Utilities
72689     function asName(name) {
72690         return ts.isString(name) ? createIdentifier(name) : name;
72691     }
72692     function asExpression(value) {
72693         return typeof value === "string" ? createStringLiteral(value) :
72694             typeof value === "number" ? createNumericLiteral("" + value) :
72695                 typeof value === "boolean" ? value ? createTrue() : createFalse() :
72696                     value;
72697     }
72698     function asNodeArray(array) {
72699         return array ? createNodeArray(array) : undefined;
72700     }
72701     function asToken(value) {
72702         return typeof value === "number" ? createToken(value) : value;
72703     }
72704     function asEmbeddedStatement(statement) {
72705         return statement && ts.isNotEmittedStatement(statement) ? setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
72706     }
72707     /**
72708      * Clears any EmitNode entries from parse-tree nodes.
72709      * @param sourceFile A source file.
72710      */
72711     function disposeEmitNodes(sourceFile) {
72712         // During transformation we may need to annotate a parse tree node with transient
72713         // transformation properties. As parse tree nodes live longer than transformation
72714         // nodes, we need to make sure we reclaim any memory allocated for custom ranges
72715         // from these nodes to ensure we do not hold onto entire subtrees just for position
72716         // information. We also need to reset these nodes to a pre-transformation state
72717         // for incremental parsing scenarios so that we do not impact later emit.
72718         sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
72719         var emitNode = sourceFile && sourceFile.emitNode;
72720         var annotatedNodes = emitNode && emitNode.annotatedNodes;
72721         if (annotatedNodes) {
72722             for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
72723                 var node = annotatedNodes_1[_i];
72724                 node.emitNode = undefined;
72725             }
72726         }
72727     }
72728     ts.disposeEmitNodes = disposeEmitNodes;
72729     /**
72730      * Associates a node with the current transformation, initializing
72731      * various transient transformation properties.
72732      */
72733     /* @internal */
72734     function getOrCreateEmitNode(node) {
72735         if (!node.emitNode) {
72736             if (ts.isParseTreeNode(node)) {
72737                 // To avoid holding onto transformation artifacts, we keep track of any
72738                 // parse tree node we are annotating. This allows us to clean them up after
72739                 // all transformations have completed.
72740                 if (node.kind === 290 /* SourceFile */) {
72741                     return node.emitNode = { annotatedNodes: [node] };
72742                 }
72743                 var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
72744                 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
72745             }
72746             node.emitNode = {};
72747         }
72748         return node.emitNode;
72749     }
72750     ts.getOrCreateEmitNode = getOrCreateEmitNode;
72751     /**
72752      * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
72753      * @internal
72754      */
72755     function removeAllComments(node) {
72756         var emitNode = getOrCreateEmitNode(node);
72757         emitNode.flags |= 1536 /* NoComments */;
72758         emitNode.leadingComments = undefined;
72759         emitNode.trailingComments = undefined;
72760         return node;
72761     }
72762     ts.removeAllComments = removeAllComments;
72763     function setTextRange(range, location) {
72764         if (location) {
72765             range.pos = location.pos;
72766             range.end = location.end;
72767         }
72768         return range;
72769     }
72770     ts.setTextRange = setTextRange;
72771     /**
72772      * Sets flags that control emit behavior of a node.
72773      */
72774     function setEmitFlags(node, emitFlags) {
72775         getOrCreateEmitNode(node).flags = emitFlags;
72776         return node;
72777     }
72778     ts.setEmitFlags = setEmitFlags;
72779     /**
72780      * Sets flags that control emit behavior of a node.
72781      */
72782     /* @internal */
72783     function addEmitFlags(node, emitFlags) {
72784         var emitNode = getOrCreateEmitNode(node);
72785         emitNode.flags = emitNode.flags | emitFlags;
72786         return node;
72787     }
72788     ts.addEmitFlags = addEmitFlags;
72789     /**
72790      * Gets a custom text range to use when emitting source maps.
72791      */
72792     function getSourceMapRange(node) {
72793         var emitNode = node.emitNode;
72794         return (emitNode && emitNode.sourceMapRange) || node;
72795     }
72796     ts.getSourceMapRange = getSourceMapRange;
72797     /**
72798      * Sets a custom text range to use when emitting source maps.
72799      */
72800     function setSourceMapRange(node, range) {
72801         getOrCreateEmitNode(node).sourceMapRange = range;
72802         return node;
72803     }
72804     ts.setSourceMapRange = setSourceMapRange;
72805     var SourceMapSource;
72806     /**
72807      * Create an external source map source file reference
72808      */
72809     function createSourceMapSource(fileName, text, skipTrivia) {
72810         return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
72811     }
72812     ts.createSourceMapSource = createSourceMapSource;
72813     /**
72814      * Gets the TextRange to use for source maps for a token of a node.
72815      */
72816     function getTokenSourceMapRange(node, token) {
72817         var emitNode = node.emitNode;
72818         var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
72819         return tokenSourceMapRanges && tokenSourceMapRanges[token];
72820     }
72821     ts.getTokenSourceMapRange = getTokenSourceMapRange;
72822     /**
72823      * Sets the TextRange to use for source maps for a token of a node.
72824      */
72825     function setTokenSourceMapRange(node, token, range) {
72826         var emitNode = getOrCreateEmitNode(node);
72827         var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []);
72828         tokenSourceMapRanges[token] = range;
72829         return node;
72830     }
72831     ts.setTokenSourceMapRange = setTokenSourceMapRange;
72832     /**
72833      * Gets a custom text range to use when emitting comments.
72834      */
72835     /*@internal*/
72836     function getStartsOnNewLine(node) {
72837         var emitNode = node.emitNode;
72838         return emitNode && emitNode.startsOnNewLine;
72839     }
72840     ts.getStartsOnNewLine = getStartsOnNewLine;
72841     /**
72842      * Sets a custom text range to use when emitting comments.
72843      */
72844     /*@internal*/
72845     function setStartsOnNewLine(node, newLine) {
72846         getOrCreateEmitNode(node).startsOnNewLine = newLine;
72847         return node;
72848     }
72849     ts.setStartsOnNewLine = setStartsOnNewLine;
72850     /**
72851      * Gets a custom text range to use when emitting comments.
72852      */
72853     function getCommentRange(node) {
72854         var emitNode = node.emitNode;
72855         return (emitNode && emitNode.commentRange) || node;
72856     }
72857     ts.getCommentRange = getCommentRange;
72858     /**
72859      * Sets a custom text range to use when emitting comments.
72860      */
72861     function setCommentRange(node, range) {
72862         getOrCreateEmitNode(node).commentRange = range;
72863         return node;
72864     }
72865     ts.setCommentRange = setCommentRange;
72866     function getSyntheticLeadingComments(node) {
72867         var emitNode = node.emitNode;
72868         return emitNode && emitNode.leadingComments;
72869     }
72870     ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
72871     function setSyntheticLeadingComments(node, comments) {
72872         getOrCreateEmitNode(node).leadingComments = comments;
72873         return node;
72874     }
72875     ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
72876     function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
72877         return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
72878     }
72879     ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
72880     function getSyntheticTrailingComments(node) {
72881         var emitNode = node.emitNode;
72882         return emitNode && emitNode.trailingComments;
72883     }
72884     ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
72885     function setSyntheticTrailingComments(node, comments) {
72886         getOrCreateEmitNode(node).trailingComments = comments;
72887         return node;
72888     }
72889     ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
72890     function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
72891         return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
72892     }
72893     ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
72894     function moveSyntheticComments(node, original) {
72895         setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
72896         setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
72897         var emit = getOrCreateEmitNode(original);
72898         emit.leadingComments = undefined;
72899         emit.trailingComments = undefined;
72900         return node;
72901     }
72902     ts.moveSyntheticComments = moveSyntheticComments;
72903     /** @internal */
72904     function ignoreSourceNewlines(node) {
72905         getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
72906         return node;
72907     }
72908     ts.ignoreSourceNewlines = ignoreSourceNewlines;
72909     /**
72910      * Gets the constant value to emit for an expression.
72911      */
72912     function getConstantValue(node) {
72913         var emitNode = node.emitNode;
72914         return emitNode && emitNode.constantValue;
72915     }
72916     ts.getConstantValue = getConstantValue;
72917     /**
72918      * Sets the constant value to emit for an expression.
72919      */
72920     function setConstantValue(node, value) {
72921         var emitNode = getOrCreateEmitNode(node);
72922         emitNode.constantValue = value;
72923         return node;
72924     }
72925     ts.setConstantValue = setConstantValue;
72926     /**
72927      * Adds an EmitHelper to a node.
72928      */
72929     function addEmitHelper(node, helper) {
72930         var emitNode = getOrCreateEmitNode(node);
72931         emitNode.helpers = ts.append(emitNode.helpers, helper);
72932         return node;
72933     }
72934     ts.addEmitHelper = addEmitHelper;
72935     /**
72936      * Add EmitHelpers to a node.
72937      */
72938     function addEmitHelpers(node, helpers) {
72939         if (ts.some(helpers)) {
72940             var emitNode = getOrCreateEmitNode(node);
72941             for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
72942                 var helper = helpers_1[_i];
72943                 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
72944             }
72945         }
72946         return node;
72947     }
72948     ts.addEmitHelpers = addEmitHelpers;
72949     /**
72950      * Removes an EmitHelper from a node.
72951      */
72952     function removeEmitHelper(node, helper) {
72953         var emitNode = node.emitNode;
72954         if (emitNode) {
72955             var helpers = emitNode.helpers;
72956             if (helpers) {
72957                 return ts.orderedRemoveItem(helpers, helper);
72958             }
72959         }
72960         return false;
72961     }
72962     ts.removeEmitHelper = removeEmitHelper;
72963     /**
72964      * Gets the EmitHelpers of a node.
72965      */
72966     function getEmitHelpers(node) {
72967         var emitNode = node.emitNode;
72968         return emitNode && emitNode.helpers;
72969     }
72970     ts.getEmitHelpers = getEmitHelpers;
72971     /**
72972      * Moves matching emit helpers from a source node to a target node.
72973      */
72974     function moveEmitHelpers(source, target, predicate) {
72975         var sourceEmitNode = source.emitNode;
72976         var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
72977         if (!ts.some(sourceEmitHelpers))
72978             return;
72979         var targetEmitNode = getOrCreateEmitNode(target);
72980         var helpersRemoved = 0;
72981         for (var i = 0; i < sourceEmitHelpers.length; i++) {
72982             var helper = sourceEmitHelpers[i];
72983             if (predicate(helper)) {
72984                 helpersRemoved++;
72985                 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
72986             }
72987             else if (helpersRemoved > 0) {
72988                 sourceEmitHelpers[i - helpersRemoved] = helper;
72989             }
72990         }
72991         if (helpersRemoved > 0) {
72992             sourceEmitHelpers.length -= helpersRemoved;
72993         }
72994     }
72995     ts.moveEmitHelpers = moveEmitHelpers;
72996     /* @internal */
72997     function compareEmitHelpers(x, y) {
72998         if (x === y)
72999             return 0 /* EqualTo */;
73000         if (x.priority === y.priority)
73001             return 0 /* EqualTo */;
73002         if (x.priority === undefined)
73003             return 1 /* GreaterThan */;
73004         if (y.priority === undefined)
73005             return -1 /* LessThan */;
73006         return ts.compareValues(x.priority, y.priority);
73007     }
73008     ts.compareEmitHelpers = compareEmitHelpers;
73009     function setOriginalNode(node, original) {
73010         node.original = original;
73011         if (original) {
73012             var emitNode = original.emitNode;
73013             if (emitNode)
73014                 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
73015         }
73016         return node;
73017     }
73018     ts.setOriginalNode = setOriginalNode;
73019     function mergeEmitNode(sourceEmitNode, destEmitNode) {
73020         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;
73021         if (!destEmitNode)
73022             destEmitNode = {};
73023         // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
73024         if (leadingComments)
73025             destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
73026         if (trailingComments)
73027             destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
73028         if (flags)
73029             destEmitNode.flags = flags;
73030         if (commentRange)
73031             destEmitNode.commentRange = commentRange;
73032         if (sourceMapRange)
73033             destEmitNode.sourceMapRange = sourceMapRange;
73034         if (tokenSourceMapRanges)
73035             destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
73036         if (constantValue !== undefined)
73037             destEmitNode.constantValue = constantValue;
73038         if (helpers)
73039             destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers);
73040         if (startsOnNewLine !== undefined)
73041             destEmitNode.startsOnNewLine = startsOnNewLine;
73042         return destEmitNode;
73043     }
73044     function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
73045         if (!destRanges)
73046             destRanges = [];
73047         for (var key in sourceRanges) {
73048             destRanges[key] = sourceRanges[key];
73049         }
73050         return destRanges;
73051     }
73052 })(ts || (ts = {}));
73053 /* @internal */
73054 var ts;
73055 (function (ts) {
73056     ts.nullTransformationContext = {
73057         enableEmitNotification: ts.noop,
73058         enableSubstitution: ts.noop,
73059         endLexicalEnvironment: ts.returnUndefined,
73060         getCompilerOptions: function () { return ({}); },
73061         getEmitHost: ts.notImplemented,
73062         getEmitResolver: ts.notImplemented,
73063         setLexicalEnvironmentFlags: ts.noop,
73064         getLexicalEnvironmentFlags: function () { return 0; },
73065         hoistFunctionDeclaration: ts.noop,
73066         hoistVariableDeclaration: ts.noop,
73067         addInitializationStatement: ts.noop,
73068         isEmitNotificationEnabled: ts.notImplemented,
73069         isSubstitutionEnabled: ts.notImplemented,
73070         onEmitNode: ts.noop,
73071         onSubstituteNode: ts.notImplemented,
73072         readEmitHelpers: ts.notImplemented,
73073         requestEmitHelper: ts.noop,
73074         resumeLexicalEnvironment: ts.noop,
73075         startLexicalEnvironment: ts.noop,
73076         suspendLexicalEnvironment: ts.noop,
73077         addDiagnostic: ts.noop,
73078     };
73079     function createTypeCheck(value, tag) {
73080         return tag === "undefined"
73081             ? ts.createStrictEquality(value, ts.createVoidZero())
73082             : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag));
73083     }
73084     ts.createTypeCheck = createTypeCheck;
73085     function createMemberAccessForPropertyName(target, memberName, location) {
73086         if (ts.isComputedPropertyName(memberName)) {
73087             return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location);
73088         }
73089         else {
73090             var expression = ts.setTextRange((ts.isIdentifier(memberName) || ts.isPrivateIdentifier(memberName))
73091                 ? ts.createPropertyAccess(target, memberName)
73092                 : ts.createElementAccess(target, memberName), memberName);
73093             ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
73094             return expression;
73095         }
73096     }
73097     ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
73098     function createFunctionCall(func, thisArg, argumentsList, location) {
73099         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), 
73100         /*typeArguments*/ undefined, __spreadArrays([
73101             thisArg
73102         ], argumentsList)), location);
73103     }
73104     ts.createFunctionCall = createFunctionCall;
73105     function createFunctionApply(func, thisArg, argumentsExpression, location) {
73106         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), 
73107         /*typeArguments*/ undefined, [
73108             thisArg,
73109             argumentsExpression
73110         ]), location);
73111     }
73112     ts.createFunctionApply = createFunctionApply;
73113     function createArraySlice(array, start) {
73114         var argumentsList = [];
73115         if (start !== undefined) {
73116             argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start);
73117         }
73118         return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
73119     }
73120     ts.createArraySlice = createArraySlice;
73121     function createArrayConcat(array, values) {
73122         return ts.createCall(ts.createPropertyAccess(array, "concat"), 
73123         /*typeArguments*/ undefined, values);
73124     }
73125     ts.createArrayConcat = createArrayConcat;
73126     function createMathPow(left, right, location) {
73127         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), 
73128         /*typeArguments*/ undefined, [left, right]), location);
73129     }
73130     ts.createMathPow = createMathPow;
73131     function createReactNamespace(reactNamespace, parent) {
73132         // To ensure the emit resolver can properly resolve the namespace, we need to
73133         // treat this identifier as if it were a source tree node by clearing the `Synthesized`
73134         // flag and setting a parent node.
73135         var react = ts.createIdentifier(reactNamespace || "React");
73136         react.flags &= ~8 /* Synthesized */;
73137         // Set the parent that is in parse tree
73138         // this makes sure that parent chain is intact for checker to traverse complete scope tree
73139         react.parent = ts.getParseTreeNode(parent);
73140         return react;
73141     }
73142     function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) {
73143         if (ts.isQualifiedName(jsxFactory)) {
73144             var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent);
73145             var right = ts.createIdentifier(ts.idText(jsxFactory.right));
73146             right.escapedText = jsxFactory.right.escapedText;
73147             return ts.createPropertyAccess(left, right);
73148         }
73149         else {
73150             return createReactNamespace(ts.idText(jsxFactory), parent);
73151         }
73152     }
73153     function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) {
73154         return jsxFactoryEntity ?
73155             createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
73156             ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement");
73157     }
73158     function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
73159         var argumentsList = [tagName];
73160         if (props) {
73161             argumentsList.push(props);
73162         }
73163         if (children && children.length > 0) {
73164             if (!props) {
73165                 argumentsList.push(ts.createNull());
73166             }
73167             if (children.length > 1) {
73168                 for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
73169                     var child = children_2[_i];
73170                     startOnNewLine(child);
73171                     argumentsList.push(child);
73172                 }
73173             }
73174             else {
73175                 argumentsList.push(children[0]);
73176             }
73177         }
73178         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73179         /*typeArguments*/ undefined, argumentsList), location);
73180     }
73181     ts.createExpressionForJsxElement = createExpressionForJsxElement;
73182     function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) {
73183         var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment");
73184         var argumentsList = [tagName];
73185         argumentsList.push(ts.createNull());
73186         if (children && children.length > 0) {
73187             if (children.length > 1) {
73188                 for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
73189                     var child = children_3[_i];
73190                     startOnNewLine(child);
73191                     argumentsList.push(child);
73192                 }
73193             }
73194             else {
73195                 argumentsList.push(children[0]);
73196             }
73197         }
73198         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73199         /*typeArguments*/ undefined, argumentsList), location);
73200     }
73201     ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
73202     // Helpers
73203     /**
73204      * Gets an identifier for the name of an *unscoped* emit helper.
73205      */
73206     function getUnscopedHelperName(name) {
73207         return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
73208     }
73209     ts.getUnscopedHelperName = getUnscopedHelperName;
73210     ts.valuesHelper = {
73211         name: "typescript:values",
73212         importName: "__values",
73213         scoped: false,
73214         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            };"
73215     };
73216     function createValuesHelper(context, expression, location) {
73217         context.requestEmitHelper(ts.valuesHelper);
73218         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__values"), 
73219         /*typeArguments*/ undefined, [expression]), location);
73220     }
73221     ts.createValuesHelper = createValuesHelper;
73222     ts.readHelper = {
73223         name: "typescript:read",
73224         importName: "__read",
73225         scoped: false,
73226         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            };"
73227     };
73228     function createReadHelper(context, iteratorRecord, count, location) {
73229         context.requestEmitHelper(ts.readHelper);
73230         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__read"), 
73231         /*typeArguments*/ undefined, count !== undefined
73232             ? [iteratorRecord, ts.createLiteral(count)]
73233             : [iteratorRecord]), location);
73234     }
73235     ts.createReadHelper = createReadHelper;
73236     ts.spreadHelper = {
73237         name: "typescript:spread",
73238         importName: "__spread",
73239         scoped: false,
73240         dependencies: [ts.readHelper],
73241         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            };"
73242     };
73243     function createSpreadHelper(context, argumentList, location) {
73244         context.requestEmitHelper(ts.spreadHelper);
73245         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spread"), 
73246         /*typeArguments*/ undefined, argumentList), location);
73247     }
73248     ts.createSpreadHelper = createSpreadHelper;
73249     ts.spreadArraysHelper = {
73250         name: "typescript:spreadArrays",
73251         importName: "__spreadArrays",
73252         scoped: false,
73253         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            };"
73254     };
73255     function createSpreadArraysHelper(context, argumentList, location) {
73256         context.requestEmitHelper(ts.spreadArraysHelper);
73257         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spreadArrays"), 
73258         /*typeArguments*/ undefined, argumentList), location);
73259     }
73260     ts.createSpreadArraysHelper = createSpreadArraysHelper;
73261     // Utilities
73262     function createForOfBindingStatement(node, boundValue) {
73263         if (ts.isVariableDeclarationList(node)) {
73264             var firstDeclaration = ts.first(node.declarations);
73265             var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, 
73266             /*typeNode*/ undefined, boundValue);
73267             return ts.setTextRange(ts.createVariableStatement(
73268             /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), 
73269             /*location*/ node);
73270         }
73271         else {
73272             var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node);
73273             return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node);
73274         }
73275     }
73276     ts.createForOfBindingStatement = createForOfBindingStatement;
73277     function insertLeadingStatement(dest, source) {
73278         if (ts.isBlock(dest)) {
73279             return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
73280         }
73281         else {
73282             return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true);
73283         }
73284     }
73285     ts.insertLeadingStatement = insertLeadingStatement;
73286     function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
73287         if (!outermostLabeledStatement) {
73288             return node;
73289         }
73290         var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 238 /* LabeledStatement */
73291             ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
73292             : node);
73293         if (afterRestoreLabelCallback) {
73294             afterRestoreLabelCallback(outermostLabeledStatement);
73295         }
73296         return updated;
73297     }
73298     ts.restoreEnclosingLabel = restoreEnclosingLabel;
73299     function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
73300         var target = ts.skipParentheses(node);
73301         switch (target.kind) {
73302             case 75 /* Identifier */:
73303                 return cacheIdentifiers;
73304             case 104 /* ThisKeyword */:
73305             case 8 /* NumericLiteral */:
73306             case 9 /* BigIntLiteral */:
73307             case 10 /* StringLiteral */:
73308                 return false;
73309             case 192 /* ArrayLiteralExpression */:
73310                 var elements = target.elements;
73311                 if (elements.length === 0) {
73312                     return false;
73313                 }
73314                 return true;
73315             case 193 /* ObjectLiteralExpression */:
73316                 return target.properties.length > 0;
73317             default:
73318                 return true;
73319         }
73320     }
73321     function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
73322         if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
73323         var callee = skipOuterExpressions(expression, 15 /* All */);
73324         var thisArg;
73325         var target;
73326         if (ts.isSuperProperty(callee)) {
73327             thisArg = ts.createThis();
73328             target = callee;
73329         }
73330         else if (callee.kind === 102 /* SuperKeyword */) {
73331             thisArg = ts.createThis();
73332             target = languageVersion < 2 /* ES2015 */
73333                 ? ts.setTextRange(ts.createIdentifier("_super"), callee)
73334                 : callee;
73335         }
73336         else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
73337             thisArg = ts.createVoidZero();
73338             target = parenthesizeForAccess(callee);
73339         }
73340         else {
73341             switch (callee.kind) {
73342                 case 194 /* PropertyAccessExpression */: {
73343                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73344                         // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
73345                         thisArg = ts.createTempVariable(recordTempVariable);
73346                         target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
73347                         ts.setTextRange(target, callee);
73348                     }
73349                     else {
73350                         thisArg = callee.expression;
73351                         target = callee;
73352                     }
73353                     break;
73354                 }
73355                 case 195 /* ElementAccessExpression */: {
73356                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73357                         // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
73358                         thisArg = ts.createTempVariable(recordTempVariable);
73359                         target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
73360                         ts.setTextRange(target, callee);
73361                     }
73362                     else {
73363                         thisArg = callee.expression;
73364                         target = callee;
73365                     }
73366                     break;
73367                 }
73368                 default: {
73369                     // for `a()` target is `a` and thisArg is `void 0`
73370                     thisArg = ts.createVoidZero();
73371                     target = parenthesizeForAccess(expression);
73372                     break;
73373                 }
73374             }
73375         }
73376         return { target: target, thisArg: thisArg };
73377     }
73378     ts.createCallBinding = createCallBinding;
73379     function inlineExpressions(expressions) {
73380         // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
73381         // stack size exceeded" errors.
73382         return expressions.length > 10
73383             ? ts.createCommaList(expressions)
73384             : ts.reduceLeft(expressions, ts.createComma);
73385     }
73386     ts.inlineExpressions = inlineExpressions;
73387     function createExpressionFromEntityName(node) {
73388         if (ts.isQualifiedName(node)) {
73389             var left = createExpressionFromEntityName(node.left);
73390             var right = ts.getMutableClone(node.right);
73391             return ts.setTextRange(ts.createPropertyAccess(left, right), node);
73392         }
73393         else {
73394             return ts.getMutableClone(node);
73395         }
73396     }
73397     ts.createExpressionFromEntityName = createExpressionFromEntityName;
73398     function createExpressionForPropertyName(memberName) {
73399         if (ts.isIdentifier(memberName)) {
73400             return ts.createLiteral(memberName);
73401         }
73402         else if (ts.isComputedPropertyName(memberName)) {
73403             return ts.getMutableClone(memberName.expression);
73404         }
73405         else {
73406             return ts.getMutableClone(memberName);
73407         }
73408     }
73409     ts.createExpressionForPropertyName = createExpressionForPropertyName;
73410     function createExpressionForObjectLiteralElementLike(node, property, receiver) {
73411         if (property.name && ts.isPrivateIdentifier(property.name)) {
73412             ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
73413         }
73414         switch (property.kind) {
73415             case 163 /* GetAccessor */:
73416             case 164 /* SetAccessor */:
73417                 return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine);
73418             case 281 /* PropertyAssignment */:
73419                 return createExpressionForPropertyAssignment(property, receiver);
73420             case 282 /* ShorthandPropertyAssignment */:
73421                 return createExpressionForShorthandPropertyAssignment(property, receiver);
73422             case 161 /* MethodDeclaration */:
73423                 return createExpressionForMethodDeclaration(property, receiver);
73424         }
73425     }
73426     ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
73427     function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
73428         var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
73429         if (property === firstAccessor) {
73430             var properties_7 = [];
73431             if (getAccessor) {
73432                 var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, 
73433                 /*asteriskToken*/ undefined, 
73434                 /*name*/ undefined, 
73435                 /*typeParameters*/ undefined, getAccessor.parameters, 
73436                 /*type*/ undefined, getAccessor.body // TODO: GH#18217
73437                 );
73438                 ts.setTextRange(getterFunction, getAccessor);
73439                 ts.setOriginalNode(getterFunction, getAccessor);
73440                 var getter = ts.createPropertyAssignment("get", getterFunction);
73441                 properties_7.push(getter);
73442             }
73443             if (setAccessor) {
73444                 var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, 
73445                 /*asteriskToken*/ undefined, 
73446                 /*name*/ undefined, 
73447                 /*typeParameters*/ undefined, setAccessor.parameters, 
73448                 /*type*/ undefined, setAccessor.body // TODO: GH#18217
73449                 );
73450                 ts.setTextRange(setterFunction, setAccessor);
73451                 ts.setOriginalNode(setterFunction, setAccessor);
73452                 var setter = ts.createPropertyAssignment("set", setterFunction);
73453                 properties_7.push(setter);
73454             }
73455             properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()));
73456             properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
73457             var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
73458             /*typeArguments*/ undefined, [
73459                 receiver,
73460                 createExpressionForPropertyName(property.name),
73461                 ts.createObjectLiteral(properties_7, multiLine)
73462             ]), 
73463             /*location*/ firstAccessor);
73464             return ts.aggregateTransformFlags(expression);
73465         }
73466         return undefined;
73467     }
73468     function createExpressionForPropertyAssignment(property, receiver) {
73469         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property));
73470     }
73471     function createExpressionForShorthandPropertyAssignment(property, receiver) {
73472         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), 
73473         /*location*/ property), 
73474         /*original*/ property));
73475     }
73476     function createExpressionForMethodDeclaration(method, receiver) {
73477         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, 
73478         /*name*/ undefined, 
73479         /*typeParameters*/ undefined, method.parameters, 
73480         /*type*/ undefined, method.body // TODO: GH#18217
73481         ), 
73482         /*location*/ method), 
73483         /*original*/ method)), 
73484         /*location*/ method), 
73485         /*original*/ method));
73486     }
73487     /**
73488      * Gets the internal name of a declaration. This is primarily used for declarations that can be
73489      * referred to by name in the body of an ES5 class function body. An internal name will *never*
73490      * be prefixed with an module or namespace export modifier like "exports." when emitted as an
73491      * expression. An internal name will also *never* be renamed due to a collision with a block
73492      * scoped variable.
73493      *
73494      * @param node The declaration.
73495      * @param allowComments A value indicating whether comments may be emitted for the name.
73496      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73497      */
73498     function getInternalName(node, allowComments, allowSourceMaps) {
73499         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
73500     }
73501     ts.getInternalName = getInternalName;
73502     /**
73503      * Gets whether an identifier should only be referred to by its internal name.
73504      */
73505     function isInternalName(node) {
73506         return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
73507     }
73508     ts.isInternalName = isInternalName;
73509     /**
73510      * Gets the local name of a declaration. This is primarily used for declarations that can be
73511      * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
73512      * local name will *never* be prefixed with an module or namespace export modifier like
73513      * "exports." when emitted as an expression.
73514      *
73515      * @param node The declaration.
73516      * @param allowComments A value indicating whether comments may be emitted for the name.
73517      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73518      */
73519     function getLocalName(node, allowComments, allowSourceMaps) {
73520         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
73521     }
73522     ts.getLocalName = getLocalName;
73523     /**
73524      * Gets whether an identifier should only be referred to by its local name.
73525      */
73526     function isLocalName(node) {
73527         return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
73528     }
73529     ts.isLocalName = isLocalName;
73530     /**
73531      * Gets the export name of a declaration. This is primarily used for declarations that can be
73532      * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
73533      * export name will *always* be prefixed with an module or namespace export modifier like
73534      * `"exports."` when emitted as an expression if the name points to an exported symbol.
73535      *
73536      * @param node The declaration.
73537      * @param allowComments A value indicating whether comments may be emitted for the name.
73538      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73539      */
73540     function getExportName(node, allowComments, allowSourceMaps) {
73541         return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
73542     }
73543     ts.getExportName = getExportName;
73544     /**
73545      * Gets whether an identifier should only be referred to by its export representation if the
73546      * name points to an exported symbol.
73547      */
73548     function isExportName(node) {
73549         return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
73550     }
73551     ts.isExportName = isExportName;
73552     /**
73553      * Gets the name of a declaration for use in declarations.
73554      *
73555      * @param node The declaration.
73556      * @param allowComments A value indicating whether comments may be emitted for the name.
73557      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73558      */
73559     function getDeclarationName(node, allowComments, allowSourceMaps) {
73560         return getName(node, allowComments, allowSourceMaps);
73561     }
73562     ts.getDeclarationName = getDeclarationName;
73563     function getName(node, allowComments, allowSourceMaps, emitFlags) {
73564         if (emitFlags === void 0) { emitFlags = 0; }
73565         var nodeName = ts.getNameOfDeclaration(node);
73566         if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
73567             var name = ts.getMutableClone(nodeName);
73568             emitFlags |= ts.getEmitFlags(nodeName);
73569             if (!allowSourceMaps)
73570                 emitFlags |= 48 /* NoSourceMap */;
73571             if (!allowComments)
73572                 emitFlags |= 1536 /* NoComments */;
73573             if (emitFlags)
73574                 ts.setEmitFlags(name, emitFlags);
73575             return name;
73576         }
73577         return ts.getGeneratedNameForNode(node);
73578     }
73579     /**
73580      * Gets the exported name of a declaration for use in expressions.
73581      *
73582      * An exported name will *always* be prefixed with an module or namespace export modifier like
73583      * "exports." if the name points to an exported symbol.
73584      *
73585      * @param ns The namespace identifier.
73586      * @param node The declaration.
73587      * @param allowComments A value indicating whether comments may be emitted for the name.
73588      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73589      */
73590     function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
73591         if (ns && ts.hasModifier(node, 1 /* Export */)) {
73592             return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
73593         }
73594         return getExportName(node, allowComments, allowSourceMaps);
73595     }
73596     ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName;
73597     /**
73598      * Gets a namespace-qualified name for use in expressions.
73599      *
73600      * @param ns The namespace identifier.
73601      * @param name The name.
73602      * @param allowComments A value indicating whether comments may be emitted for the name.
73603      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73604      */
73605     function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
73606         var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name));
73607         ts.setTextRange(qualifiedName, name);
73608         var emitFlags = 0;
73609         if (!allowSourceMaps)
73610             emitFlags |= 48 /* NoSourceMap */;
73611         if (!allowComments)
73612             emitFlags |= 1536 /* NoComments */;
73613         if (emitFlags)
73614             ts.setEmitFlags(qualifiedName, emitFlags);
73615         return qualifiedName;
73616     }
73617     ts.getNamespaceMemberName = getNamespaceMemberName;
73618     function convertToFunctionBody(node, multiLine) {
73619         return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node);
73620     }
73621     ts.convertToFunctionBody = convertToFunctionBody;
73622     function convertFunctionDeclarationToExpression(node) {
73623         if (!node.body)
73624             return ts.Debug.fail();
73625         var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
73626         ts.setOriginalNode(updated, node);
73627         ts.setTextRange(updated, node);
73628         if (ts.getStartsOnNewLine(node)) {
73629             ts.setStartsOnNewLine(updated, /*newLine*/ true);
73630         }
73631         ts.aggregateTransformFlags(updated);
73632         return updated;
73633     }
73634     ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression;
73635     function isUseStrictPrologue(node) {
73636         return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
73637     }
73638     /**
73639      * Add any necessary prologue-directives into target statement-array.
73640      * The function needs to be called during each transformation step.
73641      * This function needs to be called whenever we transform the statement
73642      * list of a source file, namespace, or function-like body.
73643      *
73644      * @param target: result statements array
73645      * @param source: origin statements array
73646      * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives
73647      * @param visitor: Optional callback used to visit any custom prologue directives.
73648      */
73649     function addPrologue(target, source, ensureUseStrict, visitor) {
73650         var offset = addStandardPrologue(target, source, ensureUseStrict);
73651         return addCustomPrologue(target, source, offset, visitor);
73652     }
73653     ts.addPrologue = addPrologue;
73654     /**
73655      * Add just the standard (string-expression) prologue-directives into target statement-array.
73656      * The function needs to be called during each transformation step.
73657      * This function needs to be called whenever we transform the statement
73658      * list of a source file, namespace, or function-like body.
73659      */
73660     function addStandardPrologue(target, source, ensureUseStrict) {
73661         ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
73662         var foundUseStrict = false;
73663         var statementOffset = 0;
73664         var numStatements = source.length;
73665         while (statementOffset < numStatements) {
73666             var statement = source[statementOffset];
73667             if (ts.isPrologueDirective(statement)) {
73668                 if (isUseStrictPrologue(statement)) {
73669                     foundUseStrict = true;
73670                 }
73671                 target.push(statement);
73672             }
73673             else {
73674                 break;
73675             }
73676             statementOffset++;
73677         }
73678         if (ensureUseStrict && !foundUseStrict) {
73679             target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))));
73680         }
73681         return statementOffset;
73682     }
73683     ts.addStandardPrologue = addStandardPrologue;
73684     function addCustomPrologue(target, source, statementOffset, visitor, filter) {
73685         if (filter === void 0) { filter = ts.returnTrue; }
73686         var numStatements = source.length;
73687         while (statementOffset !== undefined && statementOffset < numStatements) {
73688             var statement = source[statementOffset];
73689             if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
73690                 ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
73691             }
73692             else {
73693                 break;
73694             }
73695             statementOffset++;
73696         }
73697         return statementOffset;
73698     }
73699     ts.addCustomPrologue = addCustomPrologue;
73700     function findUseStrictPrologue(statements) {
73701         for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
73702             var statement = statements_4[_i];
73703             if (ts.isPrologueDirective(statement)) {
73704                 if (isUseStrictPrologue(statement)) {
73705                     return statement;
73706                 }
73707             }
73708             else {
73709                 break;
73710             }
73711         }
73712         return undefined;
73713     }
73714     ts.findUseStrictPrologue = findUseStrictPrologue;
73715     function startsWithUseStrict(statements) {
73716         var firstStatement = ts.firstOrUndefined(statements);
73717         return firstStatement !== undefined
73718             && ts.isPrologueDirective(firstStatement)
73719             && isUseStrictPrologue(firstStatement);
73720     }
73721     ts.startsWithUseStrict = startsWithUseStrict;
73722     /**
73723      * Ensures "use strict" directive is added
73724      *
73725      * @param statements An array of statements
73726      */
73727     function ensureUseStrict(statements) {
73728         var foundUseStrict = findUseStrictPrologue(statements);
73729         if (!foundUseStrict) {
73730             return ts.setTextRange(ts.createNodeArray(__spreadArrays([
73731                 startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
73732             ], statements)), statements);
73733         }
73734         return statements;
73735     }
73736     ts.ensureUseStrict = ensureUseStrict;
73737     /**
73738      * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
73739      * order of operations.
73740      *
73741      * @param binaryOperator The operator for the BinaryExpression.
73742      * @param operand The operand for the BinaryExpression.
73743      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73744      *                           BinaryExpression.
73745      */
73746     function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73747         var skipped = ts.skipPartiallyEmittedExpressions(operand);
73748         // If the resulting expression is already parenthesized, we do not need to do any further processing.
73749         if (skipped.kind === 200 /* ParenthesizedExpression */) {
73750             return operand;
73751         }
73752         return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
73753             ? ts.createParen(operand)
73754             : operand;
73755     }
73756     ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand;
73757     /**
73758      * Determines whether the operand to a BinaryExpression needs to be parenthesized.
73759      *
73760      * @param binaryOperator The operator for the BinaryExpression.
73761      * @param operand The operand for the BinaryExpression.
73762      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73763      *                           BinaryExpression.
73764      */
73765     function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73766         // If the operand has lower precedence, then it needs to be parenthesized to preserve the
73767         // intent of the expression. For example, if the operand is `a + b` and the operator is
73768         // `*`, then we need to parenthesize the operand to preserve the intended order of
73769         // operations: `(a + b) * x`.
73770         //
73771         // If the operand has higher precedence, then it does not need to be parenthesized. For
73772         // example, if the operand is `a * b` and the operator is `+`, then we do not need to
73773         // parenthesize to preserve the intended order of operations: `a * b + x`.
73774         //
73775         // If the operand has the same precedence, then we need to check the associativity of
73776         // the operator based on whether this is the left or right operand of the expression.
73777         //
73778         // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
73779         // to preserve the intended order of operations: `x * (a / d)`
73780         //
73781         // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
73782         // the intended order of operations: `(a ** b) ** c`
73783         var binaryOperatorPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, binaryOperator);
73784         var binaryOperatorAssociativity = ts.getOperatorAssociativity(209 /* BinaryExpression */, binaryOperator);
73785         var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
73786         if (!isLeftSideOfBinary && operand.kind === 202 /* ArrowFunction */ && binaryOperatorPrecedence > 3) {
73787             // We need to parenthesize arrow functions on the right side to avoid it being
73788             // parsed as parenthesized expression: `a && (() => {})`
73789             return true;
73790         }
73791         var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
73792         switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
73793             case -1 /* LessThan */:
73794                 // If the operand is the right side of a right-associative binary operation
73795                 // and is a yield expression, then we do not need parentheses.
73796                 if (!isLeftSideOfBinary
73797                     && binaryOperatorAssociativity === 1 /* Right */
73798                     && operand.kind === 212 /* YieldExpression */) {
73799                     return false;
73800                 }
73801                 return true;
73802             case 1 /* GreaterThan */:
73803                 return false;
73804             case 0 /* EqualTo */:
73805                 if (isLeftSideOfBinary) {
73806                     // No need to parenthesize the left operand when the binary operator is
73807                     // left associative:
73808                     //  (a*b)/x    -> a*b/x
73809                     //  (a**b)/x   -> a**b/x
73810                     //
73811                     // Parentheses are needed for the left operand when the binary operator is
73812                     // right associative:
73813                     //  (a/b)**x   -> (a/b)**x
73814                     //  (a**b)**x  -> (a**b)**x
73815                     return binaryOperatorAssociativity === 1 /* Right */;
73816                 }
73817                 else {
73818                     if (ts.isBinaryExpression(emittedOperand)
73819                         && emittedOperand.operatorToken.kind === binaryOperator) {
73820                         // No need to parenthesize the right operand when the binary operator and
73821                         // operand are the same and one of the following:
73822                         //  x*(a*b)     => x*a*b
73823                         //  x|(a|b)     => x|a|b
73824                         //  x&(a&b)     => x&a&b
73825                         //  x^(a^b)     => x^a^b
73826                         if (operatorHasAssociativeProperty(binaryOperator)) {
73827                             return false;
73828                         }
73829                         // No need to parenthesize the right operand when the binary operator
73830                         // is plus (+) if both the left and right operands consist solely of either
73831                         // literals of the same kind or binary plus (+) expressions for literals of
73832                         // the same kind (recursively).
73833                         //  "a"+(1+2)       => "a"+(1+2)
73834                         //  "a"+("b"+"c")   => "a"+"b"+"c"
73835                         if (binaryOperator === 39 /* PlusToken */) {
73836                             var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
73837                             if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
73838                                 return false;
73839                             }
73840                         }
73841                     }
73842                     // No need to parenthesize the right operand when the operand is right
73843                     // associative:
73844                     //  x/(a**b)    -> x/a**b
73845                     //  x**(a**b)   -> x**a**b
73846                     //
73847                     // Parentheses are needed for the right operand when the operand is left
73848                     // associative:
73849                     //  x/(a*b)     -> x/(a*b)
73850                     //  x**(a/b)    -> x**(a/b)
73851                     var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
73852                     return operandAssociativity === 0 /* Left */;
73853                 }
73854         }
73855     }
73856     /**
73857      * Determines whether a binary operator is mathematically associative.
73858      *
73859      * @param binaryOperator The binary operator.
73860      */
73861     function operatorHasAssociativeProperty(binaryOperator) {
73862         // The following operators are associative in JavaScript:
73863         //  (a*b)*c     -> a*(b*c)  -> a*b*c
73864         //  (a|b)|c     -> a|(b|c)  -> a|b|c
73865         //  (a&b)&c     -> a&(b&c)  -> a&b&c
73866         //  (a^b)^c     -> a^(b^c)  -> a^b^c
73867         //
73868         // While addition is associative in mathematics, JavaScript's `+` is not
73869         // guaranteed to be associative as it is overloaded with string concatenation.
73870         return binaryOperator === 41 /* AsteriskToken */
73871             || binaryOperator === 51 /* BarToken */
73872             || binaryOperator === 50 /* AmpersandToken */
73873             || binaryOperator === 52 /* CaretToken */;
73874     }
73875     /**
73876      * This function determines whether an expression consists of a homogeneous set of
73877      * literal expressions or binary plus expressions that all share the same literal kind.
73878      * It is used to determine whether the right-hand operand of a binary plus expression can be
73879      * emitted without parentheses.
73880      */
73881     function getLiteralKindOfBinaryPlusOperand(node) {
73882         node = ts.skipPartiallyEmittedExpressions(node);
73883         if (ts.isLiteralKind(node.kind)) {
73884             return node.kind;
73885         }
73886         if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
73887             if (node.cachedLiteralKind !== undefined) {
73888                 return node.cachedLiteralKind;
73889             }
73890             var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
73891             var literalKind = ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) ? leftKind :
73892                 0 /* Unknown */;
73893             node.cachedLiteralKind = literalKind;
73894             return literalKind;
73895         }
73896         return 0 /* Unknown */;
73897     }
73898     function parenthesizeForConditionalHead(condition) {
73899         var conditionalPrecedence = ts.getOperatorPrecedence(210 /* ConditionalExpression */, 57 /* QuestionToken */);
73900         var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
73901         var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
73902         if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
73903             return ts.createParen(condition);
73904         }
73905         return condition;
73906     }
73907     ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead;
73908     function parenthesizeSubexpressionOfConditionalExpression(e) {
73909         // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
73910         // so in case when comma expression is introduced as a part of previous transformations
73911         // if should be wrapped in parens since comma operator has the lowest precedence
73912         var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
73913         return isCommaSequence(emittedExpression)
73914             ? ts.createParen(e)
73915             : e;
73916     }
73917     ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression;
73918     /**
73919      *  [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
73920      *  has a lookahead restriction for `function`, `async function`, and `class`.
73921      *
73922      * Basically, that means we need to parenthesize in the following cases:
73923      *
73924      * - BinaryExpression of CommaToken
73925      * - CommaList (synthetic list of multiple comma expressions)
73926      * - FunctionExpression
73927      * - ClassExpression
73928      */
73929     function parenthesizeDefaultExpression(e) {
73930         var check = ts.skipPartiallyEmittedExpressions(e);
73931         var needsParens = isCommaSequence(check);
73932         if (!needsParens) {
73933             switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
73934                 case 214 /* ClassExpression */:
73935                 case 201 /* FunctionExpression */:
73936                     needsParens = true;
73937             }
73938         }
73939         return needsParens ? ts.createParen(e) : e;
73940     }
73941     ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression;
73942     /**
73943      * Wraps an expression in parentheses if it is needed in order to use the expression
73944      * as the expression of a NewExpression node.
73945      *
73946      * @param expression The Expression node.
73947      */
73948     function parenthesizeForNew(expression) {
73949         var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
73950         switch (leftmostExpr.kind) {
73951             case 196 /* CallExpression */:
73952                 return ts.createParen(expression);
73953             case 197 /* NewExpression */:
73954                 return !leftmostExpr.arguments
73955                     ? ts.createParen(expression)
73956                     : expression;
73957         }
73958         return parenthesizeForAccess(expression);
73959     }
73960     ts.parenthesizeForNew = parenthesizeForNew;
73961     /**
73962      * Wraps an expression in parentheses if it is needed in order to use the expression for
73963      * property or element access.
73964      *
73965      * @param expr The expression node.
73966      */
73967     function parenthesizeForAccess(expression) {
73968         // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
73969         // to parenthesize the expression before a dot. The known exception is:
73970         //
73971         //    NewExpression:
73972         //       new C.x        -> not the same as (new C).x
73973         //
73974         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
73975         if (ts.isLeftHandSideExpression(emittedExpression)
73976             && (emittedExpression.kind !== 197 /* NewExpression */ || emittedExpression.arguments)) {
73977             return expression;
73978         }
73979         return ts.setTextRange(ts.createParen(expression), expression);
73980     }
73981     ts.parenthesizeForAccess = parenthesizeForAccess;
73982     function parenthesizePostfixOperand(operand) {
73983         return ts.isLeftHandSideExpression(operand)
73984             ? operand
73985             : ts.setTextRange(ts.createParen(operand), operand);
73986     }
73987     ts.parenthesizePostfixOperand = parenthesizePostfixOperand;
73988     function parenthesizePrefixOperand(operand) {
73989         return ts.isUnaryExpression(operand)
73990             ? operand
73991             : ts.setTextRange(ts.createParen(operand), operand);
73992     }
73993     ts.parenthesizePrefixOperand = parenthesizePrefixOperand;
73994     function parenthesizeListElements(elements) {
73995         var result;
73996         for (var i = 0; i < elements.length; i++) {
73997             var element = parenthesizeExpressionForList(elements[i]);
73998             if (result !== undefined || element !== elements[i]) {
73999                 if (result === undefined) {
74000                     result = elements.slice(0, i);
74001                 }
74002                 result.push(element);
74003             }
74004         }
74005         if (result !== undefined) {
74006             return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements);
74007         }
74008         return elements;
74009     }
74010     ts.parenthesizeListElements = parenthesizeListElements;
74011     function parenthesizeExpressionForList(expression) {
74012         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
74013         var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
74014         var commaPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, 27 /* CommaToken */);
74015         return expressionPrecedence > commaPrecedence
74016             ? expression
74017             : ts.setTextRange(ts.createParen(expression), expression);
74018     }
74019     ts.parenthesizeExpressionForList = parenthesizeExpressionForList;
74020     function parenthesizeExpressionForExpressionStatement(expression) {
74021         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
74022         if (ts.isCallExpression(emittedExpression)) {
74023             var callee = emittedExpression.expression;
74024             var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
74025             if (kind === 201 /* FunctionExpression */ || kind === 202 /* ArrowFunction */) {
74026                 var mutableCall = ts.getMutableClone(emittedExpression);
74027                 mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee);
74028                 return recreateOuterExpressions(expression, mutableCall, 8 /* PartiallyEmittedExpressions */);
74029             }
74030         }
74031         var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
74032         if (leftmostExpressionKind === 193 /* ObjectLiteralExpression */ || leftmostExpressionKind === 201 /* FunctionExpression */) {
74033             return ts.setTextRange(ts.createParen(expression), expression);
74034         }
74035         return expression;
74036     }
74037     ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement;
74038     function parenthesizeConditionalTypeMember(member) {
74039         return member.kind === 180 /* ConditionalType */ ? ts.createParenthesizedType(member) : member;
74040     }
74041     ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember;
74042     function parenthesizeElementTypeMember(member) {
74043         switch (member.kind) {
74044             case 178 /* UnionType */:
74045             case 179 /* IntersectionType */:
74046             case 170 /* FunctionType */:
74047             case 171 /* ConstructorType */:
74048                 return ts.createParenthesizedType(member);
74049         }
74050         return parenthesizeConditionalTypeMember(member);
74051     }
74052     ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember;
74053     function parenthesizeArrayTypeMember(member) {
74054         switch (member.kind) {
74055             case 172 /* TypeQuery */:
74056             case 184 /* TypeOperator */:
74057             case 181 /* InferType */:
74058                 return ts.createParenthesizedType(member);
74059         }
74060         return parenthesizeElementTypeMember(member);
74061     }
74062     ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember;
74063     function parenthesizeElementTypeMembers(members) {
74064         return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember));
74065     }
74066     ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers;
74067     function parenthesizeTypeParameters(typeParameters) {
74068         if (ts.some(typeParameters)) {
74069             var params = [];
74070             for (var i = 0; i < typeParameters.length; ++i) {
74071                 var entry = typeParameters[i];
74072                 params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ?
74073                     ts.createParenthesizedType(entry) :
74074                     entry);
74075             }
74076             return ts.createNodeArray(params);
74077         }
74078     }
74079     ts.parenthesizeTypeParameters = parenthesizeTypeParameters;
74080     function getLeftmostExpression(node, stopAtCallExpressions) {
74081         while (true) {
74082             switch (node.kind) {
74083                 case 208 /* PostfixUnaryExpression */:
74084                     node = node.operand;
74085                     continue;
74086                 case 209 /* BinaryExpression */:
74087                     node = node.left;
74088                     continue;
74089                 case 210 /* ConditionalExpression */:
74090                     node = node.condition;
74091                     continue;
74092                 case 198 /* TaggedTemplateExpression */:
74093                     node = node.tag;
74094                     continue;
74095                 case 196 /* CallExpression */:
74096                     if (stopAtCallExpressions) {
74097                         return node;
74098                     }
74099                 // falls through
74100                 case 217 /* AsExpression */:
74101                 case 195 /* ElementAccessExpression */:
74102                 case 194 /* PropertyAccessExpression */:
74103                 case 218 /* NonNullExpression */:
74104                 case 326 /* PartiallyEmittedExpression */:
74105                     node = node.expression;
74106                     continue;
74107             }
74108             return node;
74109         }
74110     }
74111     ts.getLeftmostExpression = getLeftmostExpression;
74112     function parenthesizeConciseBody(body) {
74113         if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 193 /* ObjectLiteralExpression */)) {
74114             return ts.setTextRange(ts.createParen(body), body);
74115         }
74116         return body;
74117     }
74118     ts.parenthesizeConciseBody = parenthesizeConciseBody;
74119     function isCommaSequence(node) {
74120         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
74121             node.kind === 327 /* CommaListExpression */;
74122     }
74123     ts.isCommaSequence = isCommaSequence;
74124     var OuterExpressionKinds;
74125     (function (OuterExpressionKinds) {
74126         OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
74127         OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
74128         OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
74129         OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
74130         OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
74131         OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
74132     })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
74133     function isOuterExpression(node, kinds) {
74134         if (kinds === void 0) { kinds = 15 /* All */; }
74135         switch (node.kind) {
74136             case 200 /* ParenthesizedExpression */:
74137                 return (kinds & 1 /* Parentheses */) !== 0;
74138             case 199 /* TypeAssertionExpression */:
74139             case 217 /* AsExpression */:
74140                 return (kinds & 2 /* TypeAssertions */) !== 0;
74141             case 218 /* NonNullExpression */:
74142                 return (kinds & 4 /* NonNullAssertions */) !== 0;
74143             case 326 /* PartiallyEmittedExpression */:
74144                 return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
74145         }
74146         return false;
74147     }
74148     ts.isOuterExpression = isOuterExpression;
74149     function skipOuterExpressions(node, kinds) {
74150         if (kinds === void 0) { kinds = 15 /* All */; }
74151         while (isOuterExpression(node, kinds)) {
74152             node = node.expression;
74153         }
74154         return node;
74155     }
74156     ts.skipOuterExpressions = skipOuterExpressions;
74157     function skipAssertions(node) {
74158         return skipOuterExpressions(node, 6 /* Assertions */);
74159     }
74160     ts.skipAssertions = skipAssertions;
74161     function updateOuterExpression(outerExpression, expression) {
74162         switch (outerExpression.kind) {
74163             case 200 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression);
74164             case 199 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
74165             case 217 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
74166             case 218 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
74167             case 326 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
74168         }
74169     }
74170     /**
74171      * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
74172      *
74173      * A parenthesized expression can be ignored when all of the following are true:
74174      *
74175      * - It's `pos` and `end` are not -1
74176      * - It does not have a custom source map range
74177      * - It does not have a custom comment range
74178      * - It does not have synthetic leading or trailing comments
74179      *
74180      * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
74181      * the expression to maintain precedence, a new parenthesized expression should be created automatically when
74182      * the containing expression is created/updated.
74183      */
74184     function isIgnorableParen(node) {
74185         return node.kind === 200 /* ParenthesizedExpression */
74186             && ts.nodeIsSynthesized(node)
74187             && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
74188             && ts.nodeIsSynthesized(ts.getCommentRange(node))
74189             && !ts.some(ts.getSyntheticLeadingComments(node))
74190             && !ts.some(ts.getSyntheticTrailingComments(node));
74191     }
74192     function recreateOuterExpressions(outerExpression, innerExpression, kinds) {
74193         if (kinds === void 0) { kinds = 15 /* All */; }
74194         if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
74195             return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression));
74196         }
74197         return innerExpression;
74198     }
74199     ts.recreateOuterExpressions = recreateOuterExpressions;
74200     function startOnNewLine(node) {
74201         return ts.setStartsOnNewLine(node, /*newLine*/ true);
74202     }
74203     ts.startOnNewLine = startOnNewLine;
74204     function getExternalHelpersModuleName(node) {
74205         var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74206         var emitNode = parseNode && parseNode.emitNode;
74207         return emitNode && emitNode.externalHelpersModuleName;
74208     }
74209     ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
74210     function hasRecordedExternalHelpers(sourceFile) {
74211         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74212         var emitNode = parseNode && parseNode.emitNode;
74213         return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
74214     }
74215     ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
74216     function createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
74217         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
74218             var namedBindings = void 0;
74219             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74220             if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
74221                 // use named imports
74222                 var helpers = ts.getEmitHelpers(sourceFile);
74223                 if (helpers) {
74224                     var helperNames = [];
74225                     for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
74226                         var helper = helpers_2[_i];
74227                         if (!helper.scoped) {
74228                             var importName = helper.importName;
74229                             if (importName) {
74230                                 ts.pushIfUnique(helperNames, importName);
74231                             }
74232                         }
74233                     }
74234                     if (ts.some(helperNames)) {
74235                         helperNames.sort(ts.compareStringsCaseSensitive);
74236                         // Alias the imports if the names are used somewhere in the file.
74237                         // NOTE: We don't need to care about global import collisions as this is a module.
74238                         namedBindings = ts.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
74239                             ? ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))
74240                             : ts.createImportSpecifier(ts.createIdentifier(name), getUnscopedHelperName(name)); }));
74241                         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74242                         var emitNode = ts.getOrCreateEmitNode(parseNode);
74243                         emitNode.externalHelpers = true;
74244                     }
74245                 }
74246             }
74247             else {
74248                 // use a namespace import
74249                 var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
74250                 if (externalHelpersModuleName) {
74251                     namedBindings = ts.createNamespaceImport(externalHelpersModuleName);
74252                 }
74253             }
74254             if (namedBindings) {
74255                 var externalHelpersImportDeclaration = ts.createImportDeclaration(
74256                 /*decorators*/ undefined, 
74257                 /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, namedBindings), ts.createLiteral(ts.externalHelpersModuleNameText));
74258                 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
74259                 return externalHelpersImportDeclaration;
74260             }
74261         }
74262     }
74263     ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
74264     function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
74265         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
74266             var externalHelpersModuleName = getExternalHelpersModuleName(node);
74267             if (externalHelpersModuleName) {
74268                 return externalHelpersModuleName;
74269             }
74270             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74271             var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
74272                 && moduleKind !== ts.ModuleKind.System
74273                 && moduleKind < ts.ModuleKind.ES2015;
74274             if (!create) {
74275                 var helpers = ts.getEmitHelpers(node);
74276                 if (helpers) {
74277                     for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
74278                         var helper = helpers_3[_i];
74279                         if (!helper.scoped) {
74280                             create = true;
74281                             break;
74282                         }
74283                     }
74284                 }
74285             }
74286             if (create) {
74287                 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74288                 var emitNode = ts.getOrCreateEmitNode(parseNode);
74289                 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText));
74290             }
74291         }
74292     }
74293     ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
74294     /**
74295      * Get the name of that target module from an import or export declaration
74296      */
74297     function getLocalNameForExternalImport(node, sourceFile) {
74298         var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
74299         if (namespaceDeclaration && !ts.isDefaultImport(node)) {
74300             var name = namespaceDeclaration.name;
74301             return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
74302         }
74303         if (node.kind === 254 /* ImportDeclaration */ && node.importClause) {
74304             return ts.getGeneratedNameForNode(node);
74305         }
74306         if (node.kind === 260 /* ExportDeclaration */ && node.moduleSpecifier) {
74307             return ts.getGeneratedNameForNode(node);
74308         }
74309         return undefined;
74310     }
74311     ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
74312     /**
74313      * Get the name of a target module from an import/export declaration as should be written in the emitted output.
74314      * The emitted output name can be different from the input if:
74315      *  1. The module has a /// <amd-module name="<new name>" />
74316      *  2. --out or --outFile is used, making the name relative to the rootDir
74317      *  3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
74318      * Otherwise, a new StringLiteral node representing the module name will be returned.
74319      */
74320     function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) {
74321         var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
74322         if (moduleName.kind === 10 /* StringLiteral */) {
74323             return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
74324                 || tryRenameExternalModule(moduleName, sourceFile)
74325                 || ts.getSynthesizedClone(moduleName);
74326         }
74327         return undefined;
74328     }
74329     ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
74330     /**
74331      * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
74332      * Here we check if alternative name was provided for a given moduleName and return it if possible.
74333      */
74334     function tryRenameExternalModule(moduleName, sourceFile) {
74335         var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
74336         return rename && ts.createLiteral(rename);
74337     }
74338     /**
74339      * Get the name of a module as should be written in the emitted output.
74340      * The emitted output name can be different from the input if:
74341      *  1. The module has a /// <amd-module name="<new name>" />
74342      *  2. --out or --outFile is used, making the name relative to the rootDir
74343      * Otherwise, a new StringLiteral node representing the module name will be returned.
74344      */
74345     function tryGetModuleNameFromFile(file, host, options) {
74346         if (!file) {
74347             return undefined;
74348         }
74349         if (file.moduleName) {
74350             return ts.createLiteral(file.moduleName);
74351         }
74352         if (!file.isDeclarationFile && (options.out || options.outFile)) {
74353             return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
74354         }
74355         return undefined;
74356     }
74357     ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
74358     function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) {
74359         return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
74360     }
74361     /**
74362      * Gets the initializer of an BindingOrAssignmentElement.
74363      */
74364     function getInitializerOfBindingOrAssignmentElement(bindingElement) {
74365         if (ts.isDeclarationBindingElement(bindingElement)) {
74366             // `1` in `let { a = 1 } = ...`
74367             // `1` in `let { a: b = 1 } = ...`
74368             // `1` in `let { a: {b} = 1 } = ...`
74369             // `1` in `let { a: [b] = 1 } = ...`
74370             // `1` in `let [a = 1] = ...`
74371             // `1` in `let [{a} = 1] = ...`
74372             // `1` in `let [[a] = 1] = ...`
74373             return bindingElement.initializer;
74374         }
74375         if (ts.isPropertyAssignment(bindingElement)) {
74376             // `1` in `({ a: b = 1 } = ...)`
74377             // `1` in `({ a: {b} = 1 } = ...)`
74378             // `1` in `({ a: [b] = 1 } = ...)`
74379             var initializer = bindingElement.initializer;
74380             return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
74381                 ? initializer.right
74382                 : undefined;
74383         }
74384         if (ts.isShorthandPropertyAssignment(bindingElement)) {
74385             // `1` in `({ a = 1 } = ...)`
74386             return bindingElement.objectAssignmentInitializer;
74387         }
74388         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74389             // `1` in `[a = 1] = ...`
74390             // `1` in `[{a} = 1] = ...`
74391             // `1` in `[[a] = 1] = ...`
74392             return bindingElement.right;
74393         }
74394         if (ts.isSpreadElement(bindingElement)) {
74395             // Recovery consistent with existing emit.
74396             return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
74397         }
74398     }
74399     ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
74400     /**
74401      * Gets the name of an BindingOrAssignmentElement.
74402      */
74403     function getTargetOfBindingOrAssignmentElement(bindingElement) {
74404         if (ts.isDeclarationBindingElement(bindingElement)) {
74405             // `a` in `let { a } = ...`
74406             // `a` in `let { a = 1 } = ...`
74407             // `b` in `let { a: b } = ...`
74408             // `b` in `let { a: b = 1 } = ...`
74409             // `a` in `let { ...a } = ...`
74410             // `{b}` in `let { a: {b} } = ...`
74411             // `{b}` in `let { a: {b} = 1 } = ...`
74412             // `[b]` in `let { a: [b] } = ...`
74413             // `[b]` in `let { a: [b] = 1 } = ...`
74414             // `a` in `let [a] = ...`
74415             // `a` in `let [a = 1] = ...`
74416             // `a` in `let [...a] = ...`
74417             // `{a}` in `let [{a}] = ...`
74418             // `{a}` in `let [{a} = 1] = ...`
74419             // `[a]` in `let [[a]] = ...`
74420             // `[a]` in `let [[a] = 1] = ...`
74421             return bindingElement.name;
74422         }
74423         if (ts.isObjectLiteralElementLike(bindingElement)) {
74424             switch (bindingElement.kind) {
74425                 case 281 /* PropertyAssignment */:
74426                     // `b` in `({ a: b } = ...)`
74427                     // `b` in `({ a: b = 1 } = ...)`
74428                     // `{b}` in `({ a: {b} } = ...)`
74429                     // `{b}` in `({ a: {b} = 1 } = ...)`
74430                     // `[b]` in `({ a: [b] } = ...)`
74431                     // `[b]` in `({ a: [b] = 1 } = ...)`
74432                     // `b.c` in `({ a: b.c } = ...)`
74433                     // `b.c` in `({ a: b.c = 1 } = ...)`
74434                     // `b[0]` in `({ a: b[0] } = ...)`
74435                     // `b[0]` in `({ a: b[0] = 1 } = ...)`
74436                     return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
74437                 case 282 /* ShorthandPropertyAssignment */:
74438                     // `a` in `({ a } = ...)`
74439                     // `a` in `({ a = 1 } = ...)`
74440                     return bindingElement.name;
74441                 case 283 /* SpreadAssignment */:
74442                     // `a` in `({ ...a } = ...)`
74443                     return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74444             }
74445             // no target
74446             return undefined;
74447         }
74448         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74449             // `a` in `[a = 1] = ...`
74450             // `{a}` in `[{a} = 1] = ...`
74451             // `[a]` in `[[a] = 1] = ...`
74452             // `a.b` in `[a.b = 1] = ...`
74453             // `a[0]` in `[a[0] = 1] = ...`
74454             return getTargetOfBindingOrAssignmentElement(bindingElement.left);
74455         }
74456         if (ts.isSpreadElement(bindingElement)) {
74457             // `a` in `[...a] = ...`
74458             return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74459         }
74460         // `a` in `[a] = ...`
74461         // `{a}` in `[{a}] = ...`
74462         // `[a]` in `[[a]] = ...`
74463         // `a.b` in `[a.b] = ...`
74464         // `a[0]` in `[a[0]] = ...`
74465         return bindingElement;
74466     }
74467     ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
74468     /**
74469      * Determines whether an BindingOrAssignmentElement is a rest element.
74470      */
74471     function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
74472         switch (bindingElement.kind) {
74473             case 156 /* Parameter */:
74474             case 191 /* BindingElement */:
74475                 // `...` in `let [...a] = ...`
74476                 return bindingElement.dotDotDotToken;
74477             case 213 /* SpreadElement */:
74478             case 283 /* SpreadAssignment */:
74479                 // `...` in `[...a] = ...`
74480                 return bindingElement;
74481         }
74482         return undefined;
74483     }
74484     ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
74485     /**
74486      * Gets the property name of a BindingOrAssignmentElement
74487      */
74488     function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74489         var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
74490         ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
74491         return propertyName;
74492     }
74493     ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
74494     function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74495         switch (bindingElement.kind) {
74496             case 191 /* BindingElement */:
74497                 // `a` in `let { a: b } = ...`
74498                 // `[a]` in `let { [a]: b } = ...`
74499                 // `"a"` in `let { "a": b } = ...`
74500                 // `1` in `let { 1: b } = ...`
74501                 if (bindingElement.propertyName) {
74502                     var propertyName = bindingElement.propertyName;
74503                     if (ts.isPrivateIdentifier(propertyName)) {
74504                         return ts.Debug.failBadSyntaxKind(propertyName);
74505                     }
74506                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74507                         ? propertyName.expression
74508                         : propertyName;
74509                 }
74510                 break;
74511             case 281 /* PropertyAssignment */:
74512                 // `a` in `({ a: b } = ...)`
74513                 // `[a]` in `({ [a]: b } = ...)`
74514                 // `"a"` in `({ "a": b } = ...)`
74515                 // `1` in `({ 1: b } = ...)`
74516                 if (bindingElement.name) {
74517                     var propertyName = bindingElement.name;
74518                     if (ts.isPrivateIdentifier(propertyName)) {
74519                         return ts.Debug.failBadSyntaxKind(propertyName);
74520                     }
74521                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74522                         ? propertyName.expression
74523                         : propertyName;
74524                 }
74525                 break;
74526             case 283 /* SpreadAssignment */:
74527                 // `a` in `({ ...a } = ...)`
74528                 if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
74529                     return ts.Debug.failBadSyntaxKind(bindingElement.name);
74530                 }
74531                 return bindingElement.name;
74532         }
74533         var target = getTargetOfBindingOrAssignmentElement(bindingElement);
74534         if (target && ts.isPropertyName(target)) {
74535             return target;
74536         }
74537     }
74538     ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
74539     function isStringOrNumericLiteral(node) {
74540         var kind = node.kind;
74541         return kind === 10 /* StringLiteral */
74542             || kind === 8 /* NumericLiteral */;
74543     }
74544     /**
74545      * Gets the elements of a BindingOrAssignmentPattern
74546      */
74547     function getElementsOfBindingOrAssignmentPattern(name) {
74548         switch (name.kind) {
74549             case 189 /* ObjectBindingPattern */:
74550             case 190 /* ArrayBindingPattern */:
74551             case 192 /* ArrayLiteralExpression */:
74552                 // `a` in `{a}`
74553                 // `a` in `[a]`
74554                 return name.elements;
74555             case 193 /* ObjectLiteralExpression */:
74556                 // `a` in `{a}`
74557                 return name.properties;
74558         }
74559     }
74560     ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
74561     function convertToArrayAssignmentElement(element) {
74562         if (ts.isBindingElement(element)) {
74563             if (element.dotDotDotToken) {
74564                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74565                 return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element);
74566             }
74567             var expression = convertToAssignmentElementTarget(element.name);
74568             return element.initializer
74569                 ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element)
74570                 : expression;
74571         }
74572         ts.Debug.assertNode(element, ts.isExpression);
74573         return element;
74574     }
74575     ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement;
74576     function convertToObjectAssignmentElement(element) {
74577         if (ts.isBindingElement(element)) {
74578             if (element.dotDotDotToken) {
74579                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74580                 return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element);
74581             }
74582             if (element.propertyName) {
74583                 var expression = convertToAssignmentElementTarget(element.name);
74584                 return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element);
74585             }
74586             ts.Debug.assertNode(element.name, ts.isIdentifier);
74587             return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
74588         }
74589         ts.Debug.assertNode(element, ts.isObjectLiteralElementLike);
74590         return element;
74591     }
74592     ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement;
74593     function convertToAssignmentPattern(node) {
74594         switch (node.kind) {
74595             case 190 /* ArrayBindingPattern */:
74596             case 192 /* ArrayLiteralExpression */:
74597                 return convertToArrayAssignmentPattern(node);
74598             case 189 /* ObjectBindingPattern */:
74599             case 193 /* ObjectLiteralExpression */:
74600                 return convertToObjectAssignmentPattern(node);
74601         }
74602     }
74603     ts.convertToAssignmentPattern = convertToAssignmentPattern;
74604     function convertToObjectAssignmentPattern(node) {
74605         if (ts.isObjectBindingPattern(node)) {
74606             return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
74607         }
74608         ts.Debug.assertNode(node, ts.isObjectLiteralExpression);
74609         return node;
74610     }
74611     ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern;
74612     function convertToArrayAssignmentPattern(node) {
74613         if (ts.isArrayBindingPattern(node)) {
74614             return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
74615         }
74616         ts.Debug.assertNode(node, ts.isArrayLiteralExpression);
74617         return node;
74618     }
74619     ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern;
74620     function convertToAssignmentElementTarget(node) {
74621         if (ts.isBindingPattern(node)) {
74622             return convertToAssignmentPattern(node);
74623         }
74624         ts.Debug.assertNode(node, ts.isExpression);
74625         return node;
74626     }
74627     ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget;
74628 })(ts || (ts = {}));
74629 var ts;
74630 (function (ts) {
74631     var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
74632     function visitNode(node, visitor, test, lift) {
74633         if (node === undefined || visitor === undefined) {
74634             return node;
74635         }
74636         ts.aggregateTransformFlags(node);
74637         var visited = visitor(node);
74638         if (visited === node) {
74639             return node;
74640         }
74641         var visitedNode;
74642         if (visited === undefined) {
74643             return undefined;
74644         }
74645         else if (ts.isArray(visited)) {
74646             visitedNode = (lift || extractSingleNode)(visited);
74647         }
74648         else {
74649             visitedNode = visited;
74650         }
74651         ts.Debug.assertNode(visitedNode, test);
74652         ts.aggregateTransformFlags(visitedNode);
74653         return visitedNode;
74654     }
74655     ts.visitNode = visitNode;
74656     /**
74657      * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
74658      *
74659      * @param nodes The NodeArray to visit.
74660      * @param visitor The callback used to visit a Node.
74661      * @param test A node test to execute for each node.
74662      * @param start An optional value indicating the starting offset at which to start visiting.
74663      * @param count An optional value indicating the maximum number of nodes to visit.
74664      */
74665     function visitNodes(nodes, visitor, test, start, count) {
74666         if (nodes === undefined || visitor === undefined) {
74667             return nodes;
74668         }
74669         var updated;
74670         // Ensure start and count have valid values
74671         var length = nodes.length;
74672         if (start === undefined || start < 0) {
74673             start = 0;
74674         }
74675         if (count === undefined || count > length - start) {
74676             count = length - start;
74677         }
74678         if (start > 0 || count < length) {
74679             // If we are not visiting all of the original nodes, we must always create a new array.
74680             // Since this is a fragment of a node array, we do not copy over the previous location
74681             // and will only copy over `hasTrailingComma` if we are including the last element.
74682             updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
74683         }
74684         // Visit each original node.
74685         for (var i = 0; i < count; i++) {
74686             var node = nodes[i + start];
74687             ts.aggregateTransformFlags(node);
74688             var visited = node !== undefined ? visitor(node) : undefined;
74689             if (updated !== undefined || visited === undefined || visited !== node) {
74690                 if (updated === undefined) {
74691                     // Ensure we have a copy of `nodes`, up to the current index.
74692                     updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
74693                     ts.setTextRange(updated, nodes);
74694                 }
74695                 if (visited) {
74696                     if (ts.isArray(visited)) {
74697                         for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
74698                             var visitedNode = visited_1[_i];
74699                             ts.Debug.assertNode(visitedNode, test);
74700                             ts.aggregateTransformFlags(visitedNode);
74701                             updated.push(visitedNode);
74702                         }
74703                     }
74704                     else {
74705                         ts.Debug.assertNode(visited, test);
74706                         ts.aggregateTransformFlags(visited);
74707                         updated.push(visited);
74708                     }
74709                 }
74710             }
74711         }
74712         return updated || nodes;
74713     }
74714     ts.visitNodes = visitNodes;
74715     /**
74716      * Starts a new lexical environment and visits a statement list, ending the lexical environment
74717      * and merging hoisted declarations upon completion.
74718      */
74719     function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
74720         context.startLexicalEnvironment();
74721         statements = visitNodes(statements, visitor, ts.isStatement, start);
74722         if (ensureUseStrict)
74723             statements = ts.ensureUseStrict(statements); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier
74724         return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
74725     }
74726     ts.visitLexicalEnvironment = visitLexicalEnvironment;
74727     function visitParameterList(nodes, visitor, context, nodesVisitor) {
74728         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74729         var updated;
74730         context.startLexicalEnvironment();
74731         if (nodes) {
74732             context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
74733             updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
74734             // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
74735             // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
74736             // that we might transform that introduces a temporary variable would fail as the temporary variable
74737             // exists in a different lexical scope. To address this, we move any binding patterns and initializers
74738             // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
74739             // when the emit target is greater than ES2015.
74740             if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ &&
74741                 ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
74742                 updated = addDefaultValueAssignmentsIfNeeded(updated, context);
74743             }
74744             context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
74745         }
74746         context.suspendLexicalEnvironment();
74747         return updated;
74748     }
74749     ts.visitParameterList = visitParameterList;
74750     function addDefaultValueAssignmentsIfNeeded(parameters, context) {
74751         var result;
74752         for (var i = 0; i < parameters.length; i++) {
74753             var parameter = parameters[i];
74754             var updated = addDefaultValueAssignmentIfNeeded(parameter, context);
74755             if (result || updated !== parameter) {
74756                 if (!result)
74757                     result = parameters.slice(0, i);
74758                 result[i] = updated;
74759             }
74760         }
74761         if (result) {
74762             return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters);
74763         }
74764         return parameters;
74765     }
74766     function addDefaultValueAssignmentIfNeeded(parameter, context) {
74767         // A rest parameter cannot have a binding pattern or an initializer,
74768         // so let's just ignore it.
74769         return parameter.dotDotDotToken ? parameter :
74770             ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
74771                 parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
74772                     parameter;
74773     }
74774     function addDefaultValueAssignmentForBindingPattern(parameter, context) {
74775         context.addInitializationStatement(ts.createVariableStatement(
74776         /*modifiers*/ undefined, ts.createVariableDeclarationList([
74777             ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ?
74778                 ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) :
74779                 ts.getGeneratedNameForNode(parameter)),
74780         ])));
74781         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, 
74782         /*initializer*/ undefined);
74783     }
74784     function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
74785         context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
74786             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 */))
74787         ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)));
74788         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, 
74789         /*initializer*/ undefined);
74790     }
74791     function visitFunctionBody(node, visitor, context) {
74792         context.resumeLexicalEnvironment();
74793         var updated = visitNode(node, visitor, ts.isConciseBody);
74794         var declarations = context.endLexicalEnvironment();
74795         if (ts.some(declarations)) {
74796             var block = ts.convertToFunctionBody(updated);
74797             var statements = ts.mergeLexicalEnvironment(block.statements, declarations);
74798             return ts.updateBlock(block, statements);
74799         }
74800         return updated;
74801     }
74802     ts.visitFunctionBody = visitFunctionBody;
74803     function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) {
74804         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74805         if (node === undefined) {
74806             return undefined;
74807         }
74808         var kind = node.kind;
74809         // No need to visit nodes with no children.
74810         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */) || kind === 183 /* ThisType */) {
74811             return node;
74812         }
74813         switch (kind) {
74814             // Names
74815             case 75 /* Identifier */:
74816                 return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
74817             case 153 /* QualifiedName */:
74818                 return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier));
74819             case 154 /* ComputedPropertyName */:
74820                 return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
74821             // Signature elements
74822             case 155 /* TypeParameter */:
74823                 return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode));
74824             case 156 /* Parameter */:
74825                 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));
74826             case 157 /* Decorator */:
74827                 return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression));
74828             // Type elements
74829             case 158 /* PropertySignature */:
74830                 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));
74831             case 159 /* PropertyDeclaration */:
74832                 return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), 
74833                 // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
74834                 visitNode(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
74835             case 160 /* MethodSignature */:
74836                 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));
74837             case 161 /* MethodDeclaration */:
74838                 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));
74839             case 162 /* Constructor */:
74840                 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));
74841             case 163 /* GetAccessor */:
74842                 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));
74843             case 164 /* SetAccessor */:
74844                 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));
74845             case 165 /* CallSignature */:
74846                 return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74847             case 166 /* ConstructSignature */:
74848                 return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74849             case 167 /* IndexSignature */:
74850                 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));
74851             // Types
74852             case 168 /* TypePredicate */:
74853                 return ts.updateTypePredicateNodeWithModifier(node, visitNode(node.assertsModifier, visitor), visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode));
74854             case 169 /* TypeReference */:
74855                 return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
74856             case 170 /* FunctionType */:
74857                 return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74858             case 171 /* ConstructorType */:
74859                 return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74860             case 172 /* TypeQuery */:
74861                 return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName));
74862             case 173 /* TypeLiteral */:
74863                 return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
74864             case 174 /* ArrayType */:
74865                 return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode));
74866             case 175 /* TupleType */:
74867                 return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode));
74868             case 176 /* OptionalType */:
74869                 return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74870             case 177 /* RestType */:
74871                 return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74872             case 178 /* UnionType */:
74873                 return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
74874             case 179 /* IntersectionType */:
74875                 return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
74876             case 180 /* ConditionalType */:
74877                 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));
74878             case 181 /* InferType */:
74879                 return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
74880             case 188 /* ImportType */:
74881                 return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
74882             case 182 /* ParenthesizedType */:
74883                 return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode));
74884             case 184 /* TypeOperator */:
74885                 return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74886             case 185 /* IndexedAccessType */:
74887                 return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode));
74888             case 186 /* MappedType */:
74889                 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));
74890             case 187 /* LiteralType */:
74891                 return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression));
74892             // Binding patterns
74893             case 189 /* ObjectBindingPattern */:
74894                 return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
74895             case 190 /* ArrayBindingPattern */:
74896                 return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
74897             case 191 /* BindingElement */:
74898                 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));
74899             // Expression
74900             case 192 /* ArrayLiteralExpression */:
74901                 return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression));
74902             case 193 /* ObjectLiteralExpression */:
74903                 return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
74904             case 194 /* PropertyAccessExpression */:
74905                 if (node.flags & 32 /* OptionalChain */) {
74906                     return ts.updatePropertyAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier));
74907                 }
74908                 return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifierOrPrivateIdentifier));
74909             case 195 /* ElementAccessExpression */:
74910                 if (node.flags & 32 /* OptionalChain */) {
74911                     return ts.updateElementAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.argumentExpression, visitor, ts.isExpression));
74912                 }
74913                 return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression));
74914             case 196 /* CallExpression */:
74915                 if (node.flags & 32 /* OptionalChain */) {
74916                     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));
74917                 }
74918                 return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74919             case 197 /* NewExpression */:
74920                 return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74921             case 198 /* TaggedTemplateExpression */:
74922                 return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral));
74923             case 199 /* TypeAssertionExpression */:
74924                 return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
74925             case 200 /* ParenthesizedExpression */:
74926                 return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression));
74927             case 201 /* FunctionExpression */:
74928                 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));
74929             case 202 /* ArrowFunction */:
74930                 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));
74931             case 203 /* DeleteExpression */:
74932                 return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression));
74933             case 204 /* TypeOfExpression */:
74934                 return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression));
74935             case 205 /* VoidExpression */:
74936                 return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression));
74937             case 206 /* AwaitExpression */:
74938                 return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression));
74939             case 207 /* PrefixUnaryExpression */:
74940                 return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression));
74941             case 208 /* PostfixUnaryExpression */:
74942                 return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression));
74943             case 209 /* BinaryExpression */:
74944                 return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, tokenVisitor, ts.isToken));
74945             case 210 /* ConditionalExpression */:
74946                 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));
74947             case 211 /* TemplateExpression */:
74948                 return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
74949             case 212 /* YieldExpression */:
74950                 return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression));
74951             case 213 /* SpreadElement */:
74952                 return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression));
74953             case 214 /* ClassExpression */:
74954                 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));
74955             case 216 /* ExpressionWithTypeArguments */:
74956                 return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
74957             case 217 /* AsExpression */:
74958                 return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode));
74959             case 218 /* NonNullExpression */:
74960                 return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression));
74961             case 219 /* MetaProperty */:
74962                 return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier));
74963             // Misc
74964             case 221 /* TemplateSpan */:
74965                 return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
74966             // Element
74967             case 223 /* Block */:
74968                 return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
74969             case 225 /* VariableStatement */:
74970                 return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList));
74971             case 226 /* ExpressionStatement */:
74972                 return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression));
74973             case 227 /* IfStatement */:
74974                 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));
74975             case 228 /* DoStatement */:
74976                 return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression));
74977             case 229 /* WhileStatement */:
74978                 return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74979             case 230 /* ForStatement */:
74980                 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));
74981             case 231 /* ForInStatement */:
74982                 return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74983             case 232 /* ForOfStatement */:
74984                 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));
74985             case 233 /* ContinueStatement */:
74986                 return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier));
74987             case 234 /* BreakStatement */:
74988                 return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier));
74989             case 235 /* ReturnStatement */:
74990                 return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression));
74991             case 236 /* WithStatement */:
74992                 return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74993             case 237 /* SwitchStatement */:
74994                 return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock));
74995             case 238 /* LabeledStatement */:
74996                 return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74997             case 239 /* ThrowStatement */:
74998                 return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression));
74999             case 240 /* TryStatement */:
75000                 return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock));
75001             case 242 /* VariableDeclaration */:
75002                 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));
75003             case 243 /* VariableDeclarationList */:
75004                 return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
75005             case 244 /* FunctionDeclaration */:
75006                 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));
75007             case 245 /* ClassDeclaration */:
75008                 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));
75009             case 246 /* InterfaceDeclaration */:
75010                 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));
75011             case 247 /* TypeAliasDeclaration */:
75012                 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));
75013             case 248 /* EnumDeclaration */:
75014                 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));
75015             case 249 /* ModuleDeclaration */:
75016                 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));
75017             case 250 /* ModuleBlock */:
75018                 return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75019             case 251 /* CaseBlock */:
75020                 return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
75021             case 252 /* NamespaceExportDeclaration */:
75022                 return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier));
75023             case 253 /* ImportEqualsDeclaration */:
75024                 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));
75025             case 254 /* ImportDeclaration */:
75026                 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));
75027             case 255 /* ImportClause */:
75028                 return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings), node.isTypeOnly);
75029             case 256 /* NamespaceImport */:
75030                 return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier));
75031             case 262 /* NamespaceExport */:
75032                 return ts.updateNamespaceExport(node, visitNode(node.name, visitor, ts.isIdentifier));
75033             case 257 /* NamedImports */:
75034                 return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
75035             case 258 /* ImportSpecifier */:
75036                 return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75037             case 259 /* ExportAssignment */:
75038                 return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression));
75039             case 260 /* ExportDeclaration */:
75040                 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);
75041             case 261 /* NamedExports */:
75042                 return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
75043             case 263 /* ExportSpecifier */:
75044                 return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75045             // Module references
75046             case 265 /* ExternalModuleReference */:
75047                 return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression));
75048             // JSX
75049             case 266 /* JsxElement */:
75050                 return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement));
75051             case 267 /* JsxSelfClosingElement */:
75052                 return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75053             case 268 /* JsxOpeningElement */:
75054                 return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75055             case 269 /* JsxClosingElement */:
75056                 return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression));
75057             case 270 /* JsxFragment */:
75058                 return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment));
75059             case 273 /* JsxAttribute */:
75060                 return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
75061             case 274 /* JsxAttributes */:
75062                 return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
75063             case 275 /* JsxSpreadAttribute */:
75064                 return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression));
75065             case 276 /* JsxExpression */:
75066                 return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75067             // Clauses
75068             case 277 /* CaseClause */:
75069                 return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
75070             case 278 /* DefaultClause */:
75071                 return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75072             case 279 /* HeritageClause */:
75073                 return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
75074             case 280 /* CatchClause */:
75075                 return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock));
75076             // Property assignments
75077             case 281 /* PropertyAssignment */:
75078                 return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75079             case 282 /* ShorthandPropertyAssignment */:
75080                 return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression));
75081             case 283 /* SpreadAssignment */:
75082                 return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
75083             // Enum
75084             case 284 /* EnumMember */:
75085                 return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75086             // Top-level nodes
75087             case 290 /* SourceFile */:
75088                 return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
75089             // Transformation nodes
75090             case 326 /* PartiallyEmittedExpression */:
75091                 return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75092             case 327 /* CommaListExpression */:
75093                 return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
75094             default:
75095                 // No need to visit nodes with no children.
75096                 return node;
75097         }
75098     }
75099     ts.visitEachChild = visitEachChild;
75100     /**
75101      * Extracts the single node from a NodeArray.
75102      *
75103      * @param nodes The NodeArray.
75104      */
75105     function extractSingleNode(nodes) {
75106         ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
75107         return ts.singleOrUndefined(nodes);
75108     }
75109 })(ts || (ts = {}));
75110 /* @internal */
75111 var ts;
75112 (function (ts) {
75113     function reduceNode(node, f, initial) {
75114         return node ? f(initial, node) : initial;
75115     }
75116     function reduceNodeArray(nodes, f, initial) {
75117         return nodes ? f(initial, nodes) : initial;
75118     }
75119     /**
75120      * Similar to `reduceLeft`, performs a reduction against each child of a node.
75121      * NOTE: Unlike `forEachChild`, this does *not* visit every node.
75122      *
75123      * @param node The node containing the children to reduce.
75124      * @param initial The initial value to supply to the reduction.
75125      * @param f The callback function
75126      */
75127     function reduceEachChild(node, initial, cbNode, cbNodeArray) {
75128         if (node === undefined) {
75129             return initial;
75130         }
75131         var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft;
75132         var cbNodes = cbNodeArray || cbNode;
75133         var kind = node.kind;
75134         // No need to visit nodes with no children.
75135         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */)) {
75136             return initial;
75137         }
75138         // We do not yet support types.
75139         if ((kind >= 168 /* TypePredicate */ && kind <= 187 /* LiteralType */)) {
75140             return initial;
75141         }
75142         var result = initial;
75143         switch (node.kind) {
75144             // Leaf nodes
75145             case 222 /* SemicolonClassElement */:
75146             case 224 /* EmptyStatement */:
75147             case 215 /* OmittedExpression */:
75148             case 241 /* DebuggerStatement */:
75149             case 325 /* NotEmittedStatement */:
75150                 // No need to visit nodes with no children.
75151                 break;
75152             // Names
75153             case 153 /* QualifiedName */:
75154                 result = reduceNode(node.left, cbNode, result);
75155                 result = reduceNode(node.right, cbNode, result);
75156                 break;
75157             case 154 /* ComputedPropertyName */:
75158                 result = reduceNode(node.expression, cbNode, result);
75159                 break;
75160             // Signature elements
75161             case 156 /* Parameter */:
75162                 result = reduceNodes(node.decorators, cbNodes, result);
75163                 result = reduceNodes(node.modifiers, cbNodes, result);
75164                 result = reduceNode(node.name, cbNode, result);
75165                 result = reduceNode(node.type, cbNode, result);
75166                 result = reduceNode(node.initializer, cbNode, result);
75167                 break;
75168             case 157 /* Decorator */:
75169                 result = reduceNode(node.expression, cbNode, result);
75170                 break;
75171             // Type member
75172             case 158 /* PropertySignature */:
75173                 result = reduceNodes(node.modifiers, cbNodes, result);
75174                 result = reduceNode(node.name, cbNode, result);
75175                 result = reduceNode(node.questionToken, cbNode, result);
75176                 result = reduceNode(node.type, cbNode, result);
75177                 result = reduceNode(node.initializer, cbNode, result);
75178                 break;
75179             case 159 /* PropertyDeclaration */:
75180                 result = reduceNodes(node.decorators, cbNodes, result);
75181                 result = reduceNodes(node.modifiers, cbNodes, result);
75182                 result = reduceNode(node.name, cbNode, result);
75183                 result = reduceNode(node.type, cbNode, result);
75184                 result = reduceNode(node.initializer, cbNode, result);
75185                 break;
75186             case 161 /* MethodDeclaration */:
75187                 result = reduceNodes(node.decorators, cbNodes, result);
75188                 result = reduceNodes(node.modifiers, cbNodes, result);
75189                 result = reduceNode(node.name, cbNode, result);
75190                 result = reduceNodes(node.typeParameters, cbNodes, result);
75191                 result = reduceNodes(node.parameters, cbNodes, result);
75192                 result = reduceNode(node.type, cbNode, result);
75193                 result = reduceNode(node.body, cbNode, result);
75194                 break;
75195             case 162 /* Constructor */:
75196                 result = reduceNodes(node.modifiers, cbNodes, result);
75197                 result = reduceNodes(node.parameters, cbNodes, result);
75198                 result = reduceNode(node.body, cbNode, result);
75199                 break;
75200             case 163 /* GetAccessor */:
75201                 result = reduceNodes(node.decorators, cbNodes, result);
75202                 result = reduceNodes(node.modifiers, cbNodes, result);
75203                 result = reduceNode(node.name, cbNode, result);
75204                 result = reduceNodes(node.parameters, cbNodes, result);
75205                 result = reduceNode(node.type, cbNode, result);
75206                 result = reduceNode(node.body, cbNode, result);
75207                 break;
75208             case 164 /* SetAccessor */:
75209                 result = reduceNodes(node.decorators, cbNodes, result);
75210                 result = reduceNodes(node.modifiers, cbNodes, result);
75211                 result = reduceNode(node.name, cbNode, result);
75212                 result = reduceNodes(node.parameters, cbNodes, result);
75213                 result = reduceNode(node.body, cbNode, result);
75214                 break;
75215             // Binding patterns
75216             case 189 /* ObjectBindingPattern */:
75217             case 190 /* ArrayBindingPattern */:
75218                 result = reduceNodes(node.elements, cbNodes, result);
75219                 break;
75220             case 191 /* BindingElement */:
75221                 result = reduceNode(node.propertyName, cbNode, result);
75222                 result = reduceNode(node.name, cbNode, result);
75223                 result = reduceNode(node.initializer, cbNode, result);
75224                 break;
75225             // Expression
75226             case 192 /* ArrayLiteralExpression */:
75227                 result = reduceNodes(node.elements, cbNodes, result);
75228                 break;
75229             case 193 /* ObjectLiteralExpression */:
75230                 result = reduceNodes(node.properties, cbNodes, result);
75231                 break;
75232             case 194 /* PropertyAccessExpression */:
75233                 result = reduceNode(node.expression, cbNode, result);
75234                 result = reduceNode(node.name, cbNode, result);
75235                 break;
75236             case 195 /* ElementAccessExpression */:
75237                 result = reduceNode(node.expression, cbNode, result);
75238                 result = reduceNode(node.argumentExpression, cbNode, result);
75239                 break;
75240             case 196 /* CallExpression */:
75241                 result = reduceNode(node.expression, cbNode, result);
75242                 result = reduceNodes(node.typeArguments, cbNodes, result);
75243                 result = reduceNodes(node.arguments, cbNodes, result);
75244                 break;
75245             case 197 /* NewExpression */:
75246                 result = reduceNode(node.expression, cbNode, result);
75247                 result = reduceNodes(node.typeArguments, cbNodes, result);
75248                 result = reduceNodes(node.arguments, cbNodes, result);
75249                 break;
75250             case 198 /* TaggedTemplateExpression */:
75251                 result = reduceNode(node.tag, cbNode, result);
75252                 result = reduceNodes(node.typeArguments, cbNodes, result);
75253                 result = reduceNode(node.template, cbNode, result);
75254                 break;
75255             case 199 /* TypeAssertionExpression */:
75256                 result = reduceNode(node.type, cbNode, result);
75257                 result = reduceNode(node.expression, cbNode, result);
75258                 break;
75259             case 201 /* FunctionExpression */:
75260                 result = reduceNodes(node.modifiers, cbNodes, result);
75261                 result = reduceNode(node.name, cbNode, result);
75262                 result = reduceNodes(node.typeParameters, cbNodes, result);
75263                 result = reduceNodes(node.parameters, cbNodes, result);
75264                 result = reduceNode(node.type, cbNode, result);
75265                 result = reduceNode(node.body, cbNode, result);
75266                 break;
75267             case 202 /* ArrowFunction */:
75268                 result = reduceNodes(node.modifiers, cbNodes, result);
75269                 result = reduceNodes(node.typeParameters, cbNodes, result);
75270                 result = reduceNodes(node.parameters, cbNodes, result);
75271                 result = reduceNode(node.type, cbNode, result);
75272                 result = reduceNode(node.body, cbNode, result);
75273                 break;
75274             case 200 /* ParenthesizedExpression */:
75275             case 203 /* DeleteExpression */:
75276             case 204 /* TypeOfExpression */:
75277             case 205 /* VoidExpression */:
75278             case 206 /* AwaitExpression */:
75279             case 212 /* YieldExpression */:
75280             case 213 /* SpreadElement */:
75281             case 218 /* NonNullExpression */:
75282                 result = reduceNode(node.expression, cbNode, result);
75283                 break;
75284             case 207 /* PrefixUnaryExpression */:
75285             case 208 /* PostfixUnaryExpression */:
75286                 result = reduceNode(node.operand, cbNode, result);
75287                 break;
75288             case 209 /* BinaryExpression */:
75289                 result = reduceNode(node.left, cbNode, result);
75290                 result = reduceNode(node.right, cbNode, result);
75291                 break;
75292             case 210 /* ConditionalExpression */:
75293                 result = reduceNode(node.condition, cbNode, result);
75294                 result = reduceNode(node.whenTrue, cbNode, result);
75295                 result = reduceNode(node.whenFalse, cbNode, result);
75296                 break;
75297             case 211 /* TemplateExpression */:
75298                 result = reduceNode(node.head, cbNode, result);
75299                 result = reduceNodes(node.templateSpans, cbNodes, result);
75300                 break;
75301             case 214 /* ClassExpression */:
75302                 result = reduceNodes(node.modifiers, cbNodes, result);
75303                 result = reduceNode(node.name, cbNode, result);
75304                 result = reduceNodes(node.typeParameters, cbNodes, result);
75305                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75306                 result = reduceNodes(node.members, cbNodes, result);
75307                 break;
75308             case 216 /* ExpressionWithTypeArguments */:
75309                 result = reduceNode(node.expression, cbNode, result);
75310                 result = reduceNodes(node.typeArguments, cbNodes, result);
75311                 break;
75312             case 217 /* AsExpression */:
75313                 result = reduceNode(node.expression, cbNode, result);
75314                 result = reduceNode(node.type, cbNode, result);
75315                 break;
75316             // Misc
75317             case 221 /* TemplateSpan */:
75318                 result = reduceNode(node.expression, cbNode, result);
75319                 result = reduceNode(node.literal, cbNode, result);
75320                 break;
75321             // Element
75322             case 223 /* Block */:
75323                 result = reduceNodes(node.statements, cbNodes, result);
75324                 break;
75325             case 225 /* VariableStatement */:
75326                 result = reduceNodes(node.modifiers, cbNodes, result);
75327                 result = reduceNode(node.declarationList, cbNode, result);
75328                 break;
75329             case 226 /* ExpressionStatement */:
75330                 result = reduceNode(node.expression, cbNode, result);
75331                 break;
75332             case 227 /* IfStatement */:
75333                 result = reduceNode(node.expression, cbNode, result);
75334                 result = reduceNode(node.thenStatement, cbNode, result);
75335                 result = reduceNode(node.elseStatement, cbNode, result);
75336                 break;
75337             case 228 /* DoStatement */:
75338                 result = reduceNode(node.statement, cbNode, result);
75339                 result = reduceNode(node.expression, cbNode, result);
75340                 break;
75341             case 229 /* WhileStatement */:
75342             case 236 /* WithStatement */:
75343                 result = reduceNode(node.expression, cbNode, result);
75344                 result = reduceNode(node.statement, cbNode, result);
75345                 break;
75346             case 230 /* ForStatement */:
75347                 result = reduceNode(node.initializer, cbNode, result);
75348                 result = reduceNode(node.condition, cbNode, result);
75349                 result = reduceNode(node.incrementor, cbNode, result);
75350                 result = reduceNode(node.statement, cbNode, result);
75351                 break;
75352             case 231 /* ForInStatement */:
75353             case 232 /* ForOfStatement */:
75354                 result = reduceNode(node.initializer, cbNode, result);
75355                 result = reduceNode(node.expression, cbNode, result);
75356                 result = reduceNode(node.statement, cbNode, result);
75357                 break;
75358             case 235 /* ReturnStatement */:
75359             case 239 /* ThrowStatement */:
75360                 result = reduceNode(node.expression, cbNode, result);
75361                 break;
75362             case 237 /* SwitchStatement */:
75363                 result = reduceNode(node.expression, cbNode, result);
75364                 result = reduceNode(node.caseBlock, cbNode, result);
75365                 break;
75366             case 238 /* LabeledStatement */:
75367                 result = reduceNode(node.label, cbNode, result);
75368                 result = reduceNode(node.statement, cbNode, result);
75369                 break;
75370             case 240 /* TryStatement */:
75371                 result = reduceNode(node.tryBlock, cbNode, result);
75372                 result = reduceNode(node.catchClause, cbNode, result);
75373                 result = reduceNode(node.finallyBlock, cbNode, result);
75374                 break;
75375             case 242 /* VariableDeclaration */:
75376                 result = reduceNode(node.name, cbNode, result);
75377                 result = reduceNode(node.type, cbNode, result);
75378                 result = reduceNode(node.initializer, cbNode, result);
75379                 break;
75380             case 243 /* VariableDeclarationList */:
75381                 result = reduceNodes(node.declarations, cbNodes, result);
75382                 break;
75383             case 244 /* FunctionDeclaration */:
75384                 result = reduceNodes(node.decorators, cbNodes, result);
75385                 result = reduceNodes(node.modifiers, cbNodes, result);
75386                 result = reduceNode(node.name, cbNode, result);
75387                 result = reduceNodes(node.typeParameters, cbNodes, result);
75388                 result = reduceNodes(node.parameters, cbNodes, result);
75389                 result = reduceNode(node.type, cbNode, result);
75390                 result = reduceNode(node.body, cbNode, result);
75391                 break;
75392             case 245 /* ClassDeclaration */:
75393                 result = reduceNodes(node.decorators, cbNodes, result);
75394                 result = reduceNodes(node.modifiers, cbNodes, result);
75395                 result = reduceNode(node.name, cbNode, result);
75396                 result = reduceNodes(node.typeParameters, cbNodes, result);
75397                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75398                 result = reduceNodes(node.members, cbNodes, result);
75399                 break;
75400             case 248 /* EnumDeclaration */:
75401                 result = reduceNodes(node.decorators, cbNodes, result);
75402                 result = reduceNodes(node.modifiers, cbNodes, result);
75403                 result = reduceNode(node.name, cbNode, result);
75404                 result = reduceNodes(node.members, cbNodes, result);
75405                 break;
75406             case 249 /* ModuleDeclaration */:
75407                 result = reduceNodes(node.decorators, cbNodes, result);
75408                 result = reduceNodes(node.modifiers, cbNodes, result);
75409                 result = reduceNode(node.name, cbNode, result);
75410                 result = reduceNode(node.body, cbNode, result);
75411                 break;
75412             case 250 /* ModuleBlock */:
75413                 result = reduceNodes(node.statements, cbNodes, result);
75414                 break;
75415             case 251 /* CaseBlock */:
75416                 result = reduceNodes(node.clauses, cbNodes, result);
75417                 break;
75418             case 253 /* ImportEqualsDeclaration */:
75419                 result = reduceNodes(node.decorators, cbNodes, result);
75420                 result = reduceNodes(node.modifiers, cbNodes, result);
75421                 result = reduceNode(node.name, cbNode, result);
75422                 result = reduceNode(node.moduleReference, cbNode, result);
75423                 break;
75424             case 254 /* ImportDeclaration */:
75425                 result = reduceNodes(node.decorators, cbNodes, result);
75426                 result = reduceNodes(node.modifiers, cbNodes, result);
75427                 result = reduceNode(node.importClause, cbNode, result);
75428                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75429                 break;
75430             case 255 /* ImportClause */:
75431                 result = reduceNode(node.name, cbNode, result);
75432                 result = reduceNode(node.namedBindings, cbNode, result);
75433                 break;
75434             case 256 /* NamespaceImport */:
75435                 result = reduceNode(node.name, cbNode, result);
75436                 break;
75437             case 262 /* NamespaceExport */:
75438                 result = reduceNode(node.name, cbNode, result);
75439                 break;
75440             case 257 /* NamedImports */:
75441             case 261 /* NamedExports */:
75442                 result = reduceNodes(node.elements, cbNodes, result);
75443                 break;
75444             case 258 /* ImportSpecifier */:
75445             case 263 /* ExportSpecifier */:
75446                 result = reduceNode(node.propertyName, cbNode, result);
75447                 result = reduceNode(node.name, cbNode, result);
75448                 break;
75449             case 259 /* ExportAssignment */:
75450                 result = ts.reduceLeft(node.decorators, cbNode, result);
75451                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75452                 result = reduceNode(node.expression, cbNode, result);
75453                 break;
75454             case 260 /* ExportDeclaration */:
75455                 result = ts.reduceLeft(node.decorators, cbNode, result);
75456                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75457                 result = reduceNode(node.exportClause, cbNode, result);
75458                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75459                 break;
75460             // Module references
75461             case 265 /* ExternalModuleReference */:
75462                 result = reduceNode(node.expression, cbNode, result);
75463                 break;
75464             // JSX
75465             case 266 /* JsxElement */:
75466                 result = reduceNode(node.openingElement, cbNode, result);
75467                 result = ts.reduceLeft(node.children, cbNode, result);
75468                 result = reduceNode(node.closingElement, cbNode, result);
75469                 break;
75470             case 270 /* JsxFragment */:
75471                 result = reduceNode(node.openingFragment, cbNode, result);
75472                 result = ts.reduceLeft(node.children, cbNode, result);
75473                 result = reduceNode(node.closingFragment, cbNode, result);
75474                 break;
75475             case 267 /* JsxSelfClosingElement */:
75476             case 268 /* JsxOpeningElement */:
75477                 result = reduceNode(node.tagName, cbNode, result);
75478                 result = reduceNodes(node.typeArguments, cbNode, result);
75479                 result = reduceNode(node.attributes, cbNode, result);
75480                 break;
75481             case 274 /* JsxAttributes */:
75482                 result = reduceNodes(node.properties, cbNodes, result);
75483                 break;
75484             case 269 /* JsxClosingElement */:
75485                 result = reduceNode(node.tagName, cbNode, result);
75486                 break;
75487             case 273 /* JsxAttribute */:
75488                 result = reduceNode(node.name, cbNode, result);
75489                 result = reduceNode(node.initializer, cbNode, result);
75490                 break;
75491             case 275 /* JsxSpreadAttribute */:
75492                 result = reduceNode(node.expression, cbNode, result);
75493                 break;
75494             case 276 /* JsxExpression */:
75495                 result = reduceNode(node.expression, cbNode, result);
75496                 break;
75497             // Clauses
75498             case 277 /* CaseClause */:
75499                 result = reduceNode(node.expression, cbNode, result);
75500             // falls through
75501             case 278 /* DefaultClause */:
75502                 result = reduceNodes(node.statements, cbNodes, result);
75503                 break;
75504             case 279 /* HeritageClause */:
75505                 result = reduceNodes(node.types, cbNodes, result);
75506                 break;
75507             case 280 /* CatchClause */:
75508                 result = reduceNode(node.variableDeclaration, cbNode, result);
75509                 result = reduceNode(node.block, cbNode, result);
75510                 break;
75511             // Property assignments
75512             case 281 /* PropertyAssignment */:
75513                 result = reduceNode(node.name, cbNode, result);
75514                 result = reduceNode(node.initializer, cbNode, result);
75515                 break;
75516             case 282 /* ShorthandPropertyAssignment */:
75517                 result = reduceNode(node.name, cbNode, result);
75518                 result = reduceNode(node.objectAssignmentInitializer, cbNode, result);
75519                 break;
75520             case 283 /* SpreadAssignment */:
75521                 result = reduceNode(node.expression, cbNode, result);
75522                 break;
75523             // Enum
75524             case 284 /* EnumMember */:
75525                 result = reduceNode(node.name, cbNode, result);
75526                 result = reduceNode(node.initializer, cbNode, result);
75527                 break;
75528             // Top-level nodes
75529             case 290 /* SourceFile */:
75530                 result = reduceNodes(node.statements, cbNodes, result);
75531                 break;
75532             // Transformation nodes
75533             case 326 /* PartiallyEmittedExpression */:
75534                 result = reduceNode(node.expression, cbNode, result);
75535                 break;
75536             case 327 /* CommaListExpression */:
75537                 result = reduceNodes(node.elements, cbNodes, result);
75538                 break;
75539             default:
75540                 break;
75541         }
75542         return result;
75543     }
75544     ts.reduceEachChild = reduceEachChild;
75545     function findSpanEnd(array, test, start) {
75546         var i = start;
75547         while (i < array.length && test(array[i])) {
75548             i++;
75549         }
75550         return i;
75551     }
75552     function mergeLexicalEnvironment(statements, declarations) {
75553         if (!ts.some(declarations)) {
75554             return statements;
75555         }
75556         // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
75557         //
75558         // Given:
75559         //
75560         // | Left                               | Right                               |
75561         // |------------------------------------|-------------------------------------|
75562         // | [standard prologues (left)]        | [standard prologues (right)]        |
75563         // | [hoisted functions (left)]         | [hoisted functions (right)]         |
75564         // | [hoisted variables (left)]         | [hoisted variables (right)]         |
75565         // | [lexical init statements (left)]   | [lexical init statements (right)]   |
75566         // | [other statements (left)]          |                                     |
75567         //
75568         // The resulting statement list will be:
75569         //
75570         // | Result                              |
75571         // |-------------------------------------|
75572         // | [standard prologues (right)]        |
75573         // | [standard prologues (left)]         |
75574         // | [hoisted functions (right)]         |
75575         // | [hoisted functions (left)]          |
75576         // | [hoisted variables (right)]         |
75577         // | [hoisted variables (left)]          |
75578         // | [lexical init statements (right)]   |
75579         // | [lexical init statements (left)]    |
75580         // | [other statements (left)]           |
75581         //
75582         // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
75583         // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
75584         // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
75585         var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
75586         var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
75587         var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
75588         // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
75589         var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
75590         var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
75591         var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
75592         var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
75593         ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
75594         // splice prologues from the right into the left. We do this in reverse order
75595         // so that we don't need to recompute the index on the left when we insert items.
75596         var left = ts.isNodeArray(statements) ? statements.slice() : statements;
75597         // splice other custom prologues from right into left
75598         if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
75599             left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
75600         }
75601         // splice hoisted variables from right into left
75602         if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
75603             left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
75604         }
75605         // splice hoisted functions from right into left
75606         if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
75607             left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
75608         }
75609         // splice standard prologues from right into left (that are not already in left)
75610         if (rightStandardPrologueEnd > 0) {
75611             if (leftStandardPrologueEnd === 0) {
75612                 left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
75613             }
75614             else {
75615                 var leftPrologues = ts.createMap();
75616                 for (var i = 0; i < leftStandardPrologueEnd; i++) {
75617                     var leftPrologue = statements[i];
75618                     leftPrologues.set(leftPrologue.expression.text, true);
75619                 }
75620                 for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
75621                     var rightPrologue = declarations[i];
75622                     if (!leftPrologues.has(rightPrologue.expression.text)) {
75623                         left.unshift(rightPrologue);
75624                     }
75625                 }
75626             }
75627         }
75628         if (ts.isNodeArray(statements)) {
75629             return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements);
75630         }
75631         return statements;
75632     }
75633     ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
75634     /**
75635      * Lifts a NodeArray containing only Statement nodes to a block.
75636      *
75637      * @param nodes The NodeArray.
75638      */
75639     function liftToBlock(nodes) {
75640         ts.Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block.");
75641         return ts.singleOrUndefined(nodes) || ts.createBlock(nodes);
75642     }
75643     ts.liftToBlock = liftToBlock;
75644     /**
75645      * Aggregates the TransformFlags for a Node and its subtree.
75646      */
75647     function aggregateTransformFlags(node) {
75648         aggregateTransformFlagsForNode(node);
75649         return node;
75650     }
75651     ts.aggregateTransformFlags = aggregateTransformFlags;
75652     /**
75653      * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are
75654      * computed first, then the transform flags for the current node are computed from the subtree
75655      * flags and the state of the current node. Finally, the transform flags of the node are
75656      * returned, excluding any flags that should not be included in its parent node's subtree
75657      * flags.
75658      */
75659     function aggregateTransformFlagsForNode(node) {
75660         if (node === undefined) {
75661             return 0 /* None */;
75662         }
75663         if (node.transformFlags & 536870912 /* HasComputedFlags */) {
75664             return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind);
75665         }
75666         var subtreeFlags = aggregateTransformFlagsForSubtree(node);
75667         return ts.computeTransformFlagsForNode(node, subtreeFlags);
75668     }
75669     function aggregateTransformFlagsForNodeArray(nodes) {
75670         if (nodes === undefined) {
75671             return 0 /* None */;
75672         }
75673         var subtreeFlags = 0 /* None */;
75674         var nodeArrayFlags = 0 /* None */;
75675         for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) {
75676             var node = nodes_3[_i];
75677             subtreeFlags |= aggregateTransformFlagsForNode(node);
75678             nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
75679         }
75680         nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
75681         return subtreeFlags;
75682     }
75683     /**
75684      * Aggregates the transform flags for the subtree of a node.
75685      */
75686     function aggregateTransformFlagsForSubtree(node) {
75687         // We do not transform ambient declarations or types, so there is no need to
75688         // recursively aggregate transform flags.
75689         if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 216 /* ExpressionWithTypeArguments */)) {
75690             return 0 /* None */;
75691         }
75692         // Aggregate the transform flags of each child.
75693         return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes);
75694     }
75695     /**
75696      * Aggregates the TransformFlags of a child node with the TransformFlags of its
75697      * siblings.
75698      */
75699     function aggregateTransformFlagsForChildNode(transformFlags, node) {
75700         return transformFlags | aggregateTransformFlagsForNode(node);
75701     }
75702     function aggregateTransformFlagsForChildNodes(transformFlags, nodes) {
75703         return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
75704     }
75705 })(ts || (ts = {}));
75706 /* @internal */
75707 var ts;
75708 (function (ts) {
75709     function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
75710         var _a = generatorOptions.extendedDiagnostics
75711             ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
75712             : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
75713         // Current source map file and its index in the sources list
75714         var rawSources = [];
75715         var sources = [];
75716         var sourceToSourceIndexMap = ts.createMap();
75717         var sourcesContent;
75718         var names = [];
75719         var nameToNameIndexMap;
75720         var mappings = "";
75721         // Last recorded and encoded mappings
75722         var lastGeneratedLine = 0;
75723         var lastGeneratedCharacter = 0;
75724         var lastSourceIndex = 0;
75725         var lastSourceLine = 0;
75726         var lastSourceCharacter = 0;
75727         var lastNameIndex = 0;
75728         var hasLast = false;
75729         var pendingGeneratedLine = 0;
75730         var pendingGeneratedCharacter = 0;
75731         var pendingSourceIndex = 0;
75732         var pendingSourceLine = 0;
75733         var pendingSourceCharacter = 0;
75734         var pendingNameIndex = 0;
75735         var hasPending = false;
75736         var hasPendingSource = false;
75737         var hasPendingName = false;
75738         return {
75739             getSources: function () { return rawSources; },
75740             addSource: addSource,
75741             setSourceContent: setSourceContent,
75742             addName: addName,
75743             addMapping: addMapping,
75744             appendSourceMap: appendSourceMap,
75745             toJSON: toJSON,
75746             toString: function () { return JSON.stringify(toJSON()); }
75747         };
75748         function addSource(fileName) {
75749             enter();
75750             var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
75751             /*isAbsolutePathAnUrl*/ true);
75752             var sourceIndex = sourceToSourceIndexMap.get(source);
75753             if (sourceIndex === undefined) {
75754                 sourceIndex = sources.length;
75755                 sources.push(source);
75756                 rawSources.push(fileName);
75757                 sourceToSourceIndexMap.set(source, sourceIndex);
75758             }
75759             exit();
75760             return sourceIndex;
75761         }
75762         /* eslint-disable boolean-trivia, no-null/no-null */
75763         function setSourceContent(sourceIndex, content) {
75764             enter();
75765             if (content !== null) {
75766                 if (!sourcesContent)
75767                     sourcesContent = [];
75768                 while (sourcesContent.length < sourceIndex) {
75769                     sourcesContent.push(null);
75770                 }
75771                 sourcesContent[sourceIndex] = content;
75772             }
75773             exit();
75774         }
75775         /* eslint-enable boolean-trivia, no-null/no-null */
75776         function addName(name) {
75777             enter();
75778             if (!nameToNameIndexMap)
75779                 nameToNameIndexMap = ts.createMap();
75780             var nameIndex = nameToNameIndexMap.get(name);
75781             if (nameIndex === undefined) {
75782                 nameIndex = names.length;
75783                 names.push(name);
75784                 nameToNameIndexMap.set(name, nameIndex);
75785             }
75786             exit();
75787             return nameIndex;
75788         }
75789         function isNewGeneratedPosition(generatedLine, generatedCharacter) {
75790             return !hasPending
75791                 || pendingGeneratedLine !== generatedLine
75792                 || pendingGeneratedCharacter !== generatedCharacter;
75793         }
75794         function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
75795             return sourceIndex !== undefined
75796                 && sourceLine !== undefined
75797                 && sourceCharacter !== undefined
75798                 && pendingSourceIndex === sourceIndex
75799                 && (pendingSourceLine > sourceLine
75800                     || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
75801         }
75802         function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
75803             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75804             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75805             ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
75806             ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
75807             ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
75808             enter();
75809             // If this location wasn't recorded or the location in source is going backwards, record the mapping
75810             if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
75811                 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
75812                 commitPendingMapping();
75813                 pendingGeneratedLine = generatedLine;
75814                 pendingGeneratedCharacter = generatedCharacter;
75815                 hasPendingSource = false;
75816                 hasPendingName = false;
75817                 hasPending = true;
75818             }
75819             if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
75820                 pendingSourceIndex = sourceIndex;
75821                 pendingSourceLine = sourceLine;
75822                 pendingSourceCharacter = sourceCharacter;
75823                 hasPendingSource = true;
75824                 if (nameIndex !== undefined) {
75825                     pendingNameIndex = nameIndex;
75826                     hasPendingName = true;
75827                 }
75828             }
75829             exit();
75830         }
75831         function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
75832             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75833             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75834             enter();
75835             // First, decode the old component sourcemap
75836             var sourceIndexToNewSourceIndexMap = [];
75837             var nameIndexToNewNameIndexMap;
75838             var mappingIterator = decodeMappings(map.mappings);
75839             for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
75840                 var raw = iterResult.value;
75841                 if (end && (raw.generatedLine > end.line ||
75842                     (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
75843                     break;
75844                 }
75845                 if (start && (raw.generatedLine < start.line ||
75846                     (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
75847                     continue;
75848                 }
75849                 // Then reencode all the updated mappings into the overall map
75850                 var newSourceIndex = void 0;
75851                 var newSourceLine = void 0;
75852                 var newSourceCharacter = void 0;
75853                 var newNameIndex = void 0;
75854                 if (raw.sourceIndex !== undefined) {
75855                     newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
75856                     if (newSourceIndex === undefined) {
75857                         // Apply offsets to each position and fixup source entries
75858                         var rawPath = map.sources[raw.sourceIndex];
75859                         var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
75860                         var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
75861                         sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
75862                         if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
75863                             setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
75864                         }
75865                     }
75866                     newSourceLine = raw.sourceLine;
75867                     newSourceCharacter = raw.sourceCharacter;
75868                     if (map.names && raw.nameIndex !== undefined) {
75869                         if (!nameIndexToNewNameIndexMap)
75870                             nameIndexToNewNameIndexMap = [];
75871                         newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
75872                         if (newNameIndex === undefined) {
75873                             nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
75874                         }
75875                     }
75876                 }
75877                 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
75878                 var newGeneratedLine = rawGeneratedLine + generatedLine;
75879                 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
75880                 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
75881                 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
75882             }
75883             exit();
75884         }
75885         function shouldCommitMapping() {
75886             return !hasLast
75887                 || lastGeneratedLine !== pendingGeneratedLine
75888                 || lastGeneratedCharacter !== pendingGeneratedCharacter
75889                 || lastSourceIndex !== pendingSourceIndex
75890                 || lastSourceLine !== pendingSourceLine
75891                 || lastSourceCharacter !== pendingSourceCharacter
75892                 || lastNameIndex !== pendingNameIndex;
75893         }
75894         function commitPendingMapping() {
75895             if (!hasPending || !shouldCommitMapping()) {
75896                 return;
75897             }
75898             enter();
75899             // Line/Comma delimiters
75900             if (lastGeneratedLine < pendingGeneratedLine) {
75901                 // Emit line delimiters
75902                 do {
75903                     mappings += ";";
75904                     lastGeneratedLine++;
75905                     lastGeneratedCharacter = 0;
75906                 } while (lastGeneratedLine < pendingGeneratedLine);
75907             }
75908             else {
75909                 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
75910                 // Emit comma to separate the entry
75911                 if (hasLast) {
75912                     mappings += ",";
75913                 }
75914             }
75915             // 1. Relative generated character
75916             mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
75917             lastGeneratedCharacter = pendingGeneratedCharacter;
75918             if (hasPendingSource) {
75919                 // 2. Relative sourceIndex
75920                 mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
75921                 lastSourceIndex = pendingSourceIndex;
75922                 // 3. Relative source line
75923                 mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
75924                 lastSourceLine = pendingSourceLine;
75925                 // 4. Relative source character
75926                 mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
75927                 lastSourceCharacter = pendingSourceCharacter;
75928                 if (hasPendingName) {
75929                     // 5. Relative nameIndex
75930                     mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
75931                     lastNameIndex = pendingNameIndex;
75932                 }
75933             }
75934             hasLast = true;
75935             exit();
75936         }
75937         function toJSON() {
75938             commitPendingMapping();
75939             return {
75940                 version: 3,
75941                 file: file,
75942                 sourceRoot: sourceRoot,
75943                 sources: sources,
75944                 names: names,
75945                 mappings: mappings,
75946                 sourcesContent: sourcesContent,
75947             };
75948         }
75949     }
75950     ts.createSourceMapGenerator = createSourceMapGenerator;
75951     // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
75952     var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
75953     var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
75954     function getLineInfo(text, lineStarts) {
75955         return {
75956             getLineCount: function () { return lineStarts.length; },
75957             getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
75958         };
75959     }
75960     ts.getLineInfo = getLineInfo;
75961     /**
75962      * Tries to find the sourceMappingURL comment at the end of a file.
75963      */
75964     function tryGetSourceMappingURL(lineInfo) {
75965         for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
75966             var line = lineInfo.getLineText(index);
75967             var comment = sourceMapCommentRegExp.exec(line);
75968             if (comment) {
75969                 return comment[1];
75970             }
75971             // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
75972             else if (!line.match(whitespaceOrMapCommentRegExp)) {
75973                 break;
75974             }
75975         }
75976     }
75977     ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
75978     /* eslint-disable no-null/no-null */
75979     function isStringOrNull(x) {
75980         return typeof x === "string" || x === null;
75981     }
75982     function isRawSourceMap(x) {
75983         return x !== null
75984             && typeof x === "object"
75985             && x.version === 3
75986             && typeof x.file === "string"
75987             && typeof x.mappings === "string"
75988             && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
75989             && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
75990             && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
75991             && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
75992     }
75993     ts.isRawSourceMap = isRawSourceMap;
75994     /* eslint-enable no-null/no-null */
75995     function tryParseRawSourceMap(text) {
75996         try {
75997             var parsed = JSON.parse(text);
75998             if (isRawSourceMap(parsed)) {
75999                 return parsed;
76000             }
76001         }
76002         catch (_a) {
76003             // empty
76004         }
76005         return undefined;
76006     }
76007     ts.tryParseRawSourceMap = tryParseRawSourceMap;
76008     function decodeMappings(mappings) {
76009         var done = false;
76010         var pos = 0;
76011         var generatedLine = 0;
76012         var generatedCharacter = 0;
76013         var sourceIndex = 0;
76014         var sourceLine = 0;
76015         var sourceCharacter = 0;
76016         var nameIndex = 0;
76017         var error;
76018         return {
76019             get pos() { return pos; },
76020             get error() { return error; },
76021             get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
76022             next: function () {
76023                 while (!done && pos < mappings.length) {
76024                     var ch = mappings.charCodeAt(pos);
76025                     if (ch === 59 /* semicolon */) {
76026                         // new line
76027                         generatedLine++;
76028                         generatedCharacter = 0;
76029                         pos++;
76030                         continue;
76031                     }
76032                     if (ch === 44 /* comma */) {
76033                         // Next entry is on same line - no action needed
76034                         pos++;
76035                         continue;
76036                     }
76037                     var hasSource = false;
76038                     var hasName = false;
76039                     generatedCharacter += base64VLQFormatDecode();
76040                     if (hasReportedError())
76041                         return stopIterating();
76042                     if (generatedCharacter < 0)
76043                         return setErrorAndStopIterating("Invalid generatedCharacter found");
76044                     if (!isSourceMappingSegmentEnd()) {
76045                         hasSource = true;
76046                         sourceIndex += base64VLQFormatDecode();
76047                         if (hasReportedError())
76048                             return stopIterating();
76049                         if (sourceIndex < 0)
76050                             return setErrorAndStopIterating("Invalid sourceIndex found");
76051                         if (isSourceMappingSegmentEnd())
76052                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
76053                         sourceLine += base64VLQFormatDecode();
76054                         if (hasReportedError())
76055                             return stopIterating();
76056                         if (sourceLine < 0)
76057                             return setErrorAndStopIterating("Invalid sourceLine found");
76058                         if (isSourceMappingSegmentEnd())
76059                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
76060                         sourceCharacter += base64VLQFormatDecode();
76061                         if (hasReportedError())
76062                             return stopIterating();
76063                         if (sourceCharacter < 0)
76064                             return setErrorAndStopIterating("Invalid sourceCharacter found");
76065                         if (!isSourceMappingSegmentEnd()) {
76066                             hasName = true;
76067                             nameIndex += base64VLQFormatDecode();
76068                             if (hasReportedError())
76069                                 return stopIterating();
76070                             if (nameIndex < 0)
76071                                 return setErrorAndStopIterating("Invalid nameIndex found");
76072                             if (!isSourceMappingSegmentEnd())
76073                                 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
76074                         }
76075                     }
76076                     return { value: captureMapping(hasSource, hasName), done: done };
76077                 }
76078                 return stopIterating();
76079             }
76080         };
76081         function captureMapping(hasSource, hasName) {
76082             return {
76083                 generatedLine: generatedLine,
76084                 generatedCharacter: generatedCharacter,
76085                 sourceIndex: hasSource ? sourceIndex : undefined,
76086                 sourceLine: hasSource ? sourceLine : undefined,
76087                 sourceCharacter: hasSource ? sourceCharacter : undefined,
76088                 nameIndex: hasName ? nameIndex : undefined
76089             };
76090         }
76091         function stopIterating() {
76092             done = true;
76093             return { value: undefined, done: true };
76094         }
76095         function setError(message) {
76096             if (error === undefined) {
76097                 error = message;
76098             }
76099         }
76100         function setErrorAndStopIterating(message) {
76101             setError(message);
76102             return stopIterating();
76103         }
76104         function hasReportedError() {
76105             return error !== undefined;
76106         }
76107         function isSourceMappingSegmentEnd() {
76108             return (pos === mappings.length ||
76109                 mappings.charCodeAt(pos) === 44 /* comma */ ||
76110                 mappings.charCodeAt(pos) === 59 /* semicolon */);
76111         }
76112         function base64VLQFormatDecode() {
76113             var moreDigits = true;
76114             var shiftCount = 0;
76115             var value = 0;
76116             for (; moreDigits; pos++) {
76117                 if (pos >= mappings.length)
76118                     return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
76119                 // 6 digit number
76120                 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
76121                 if (currentByte === -1)
76122                     return setError("Invalid character in VLQ"), -1;
76123                 // If msb is set, we still have more bits to continue
76124                 moreDigits = (currentByte & 32) !== 0;
76125                 // least significant 5 bits are the next msbs in the final value.
76126                 value = value | ((currentByte & 31) << shiftCount);
76127                 shiftCount += 5;
76128             }
76129             // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
76130             if ((value & 1) === 0) {
76131                 // + number
76132                 value = value >> 1;
76133             }
76134             else {
76135                 // - number
76136                 value = value >> 1;
76137                 value = -value;
76138             }
76139             return value;
76140         }
76141     }
76142     ts.decodeMappings = decodeMappings;
76143     function sameMapping(left, right) {
76144         return left === right
76145             || left.generatedLine === right.generatedLine
76146                 && left.generatedCharacter === right.generatedCharacter
76147                 && left.sourceIndex === right.sourceIndex
76148                 && left.sourceLine === right.sourceLine
76149                 && left.sourceCharacter === right.sourceCharacter
76150                 && left.nameIndex === right.nameIndex;
76151     }
76152     ts.sameMapping = sameMapping;
76153     function isSourceMapping(mapping) {
76154         return mapping.sourceIndex !== undefined
76155             && mapping.sourceLine !== undefined
76156             && mapping.sourceCharacter !== undefined;
76157     }
76158     ts.isSourceMapping = isSourceMapping;
76159     function base64FormatEncode(value) {
76160         return value >= 0 && value < 26 ? 65 /* A */ + value :
76161             value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
76162                 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
76163                     value === 62 ? 43 /* plus */ :
76164                         value === 63 ? 47 /* slash */ :
76165                             ts.Debug.fail(value + ": not a base64 value");
76166     }
76167     function base64FormatDecode(ch) {
76168         return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
76169             ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
76170                 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
76171                     ch === 43 /* plus */ ? 62 :
76172                         ch === 47 /* slash */ ? 63 :
76173                             -1;
76174     }
76175     function base64VLQFormatEncode(inValue) {
76176         // Add a new least significant bit that has the sign of the value.
76177         // if negative number the least significant bit that gets added to the number has value 1
76178         // else least significant bit value that gets added is 0
76179         // eg. -1 changes to binary : 01 [1] => 3
76180         //     +1 changes to binary : 01 [0] => 2
76181         if (inValue < 0) {
76182             inValue = ((-inValue) << 1) + 1;
76183         }
76184         else {
76185             inValue = inValue << 1;
76186         }
76187         // Encode 5 bits at a time starting from least significant bits
76188         var encodedStr = "";
76189         do {
76190             var currentDigit = inValue & 31; // 11111
76191             inValue = inValue >> 5;
76192             if (inValue > 0) {
76193                 // There are still more digits to decode, set the msb (6th bit)
76194                 currentDigit = currentDigit | 32;
76195             }
76196             encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
76197         } while (inValue > 0);
76198         return encodedStr;
76199     }
76200     function isSourceMappedPosition(value) {
76201         return value.sourceIndex !== undefined
76202             && value.sourcePosition !== undefined;
76203     }
76204     function sameMappedPosition(left, right) {
76205         return left.generatedPosition === right.generatedPosition
76206             && left.sourceIndex === right.sourceIndex
76207             && left.sourcePosition === right.sourcePosition;
76208     }
76209     function compareSourcePositions(left, right) {
76210         // Compares sourcePosition without comparing sourceIndex
76211         // since the mappings are grouped by sourceIndex
76212         ts.Debug.assert(left.sourceIndex === right.sourceIndex);
76213         return ts.compareValues(left.sourcePosition, right.sourcePosition);
76214     }
76215     function compareGeneratedPositions(left, right) {
76216         return ts.compareValues(left.generatedPosition, right.generatedPosition);
76217     }
76218     function getSourcePositionOfMapping(value) {
76219         return value.sourcePosition;
76220     }
76221     function getGeneratedPositionOfMapping(value) {
76222         return value.generatedPosition;
76223     }
76224     function createDocumentPositionMapper(host, map, mapPath) {
76225         var mapDirectory = ts.getDirectoryPath(mapPath);
76226         var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
76227         var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
76228         var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
76229         var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
76230         var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
76231         var decodedMappings;
76232         var generatedMappings;
76233         var sourceMappings;
76234         return {
76235             getSourcePosition: getSourcePosition,
76236             getGeneratedPosition: getGeneratedPosition
76237         };
76238         function processMapping(mapping) {
76239             var generatedPosition = generatedFile !== undefined
76240                 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
76241                 : -1;
76242             var source;
76243             var sourcePosition;
76244             if (isSourceMapping(mapping)) {
76245                 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
76246                 source = map.sources[mapping.sourceIndex];
76247                 sourcePosition = sourceFile !== undefined
76248                     ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
76249                     : -1;
76250             }
76251             return {
76252                 generatedPosition: generatedPosition,
76253                 source: source,
76254                 sourceIndex: mapping.sourceIndex,
76255                 sourcePosition: sourcePosition,
76256                 nameIndex: mapping.nameIndex
76257             };
76258         }
76259         function getDecodedMappings() {
76260             if (decodedMappings === undefined) {
76261                 var decoder = decodeMappings(map.mappings);
76262                 var mappings = ts.arrayFrom(decoder, processMapping);
76263                 if (decoder.error !== undefined) {
76264                     if (host.log) {
76265                         host.log("Encountered error while decoding sourcemap: " + decoder.error);
76266                     }
76267                     decodedMappings = ts.emptyArray;
76268                 }
76269                 else {
76270                     decodedMappings = mappings;
76271                 }
76272             }
76273             return decodedMappings;
76274         }
76275         function getSourceMappings(sourceIndex) {
76276             if (sourceMappings === undefined) {
76277                 var lists = [];
76278                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76279                     var mapping = _a[_i];
76280                     if (!isSourceMappedPosition(mapping))
76281                         continue;
76282                     var list = lists[mapping.sourceIndex];
76283                     if (!list)
76284                         lists[mapping.sourceIndex] = list = [];
76285                     list.push(mapping);
76286                 }
76287                 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
76288             }
76289             return sourceMappings[sourceIndex];
76290         }
76291         function getGeneratedMappings() {
76292             if (generatedMappings === undefined) {
76293                 var list = [];
76294                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76295                     var mapping = _a[_i];
76296                     list.push(mapping);
76297                 }
76298                 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
76299             }
76300             return generatedMappings;
76301         }
76302         function getGeneratedPosition(loc) {
76303             var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
76304             if (sourceIndex === undefined)
76305                 return loc;
76306             var sourceMappings = getSourceMappings(sourceIndex);
76307             if (!ts.some(sourceMappings))
76308                 return loc;
76309             var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
76310             if (targetIndex < 0) {
76311                 // if no exact match, closest is 2's complement of result
76312                 targetIndex = ~targetIndex;
76313             }
76314             var mapping = sourceMappings[targetIndex];
76315             if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
76316                 return loc;
76317             }
76318             return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
76319         }
76320         function getSourcePosition(loc) {
76321             var generatedMappings = getGeneratedMappings();
76322             if (!ts.some(generatedMappings))
76323                 return loc;
76324             var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
76325             if (targetIndex < 0) {
76326                 // if no exact match, closest is 2's complement of result
76327                 targetIndex = ~targetIndex;
76328             }
76329             var mapping = generatedMappings[targetIndex];
76330             if (mapping === undefined || !isSourceMappedPosition(mapping)) {
76331                 return loc;
76332             }
76333             return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
76334         }
76335     }
76336     ts.createDocumentPositionMapper = createDocumentPositionMapper;
76337     ts.identitySourceMapConsumer = {
76338         getSourcePosition: ts.identity,
76339         getGeneratedPosition: ts.identity
76340     };
76341 })(ts || (ts = {}));
76342 /* @internal */
76343 var ts;
76344 (function (ts) {
76345     function getOriginalNodeId(node) {
76346         node = ts.getOriginalNode(node);
76347         return node ? ts.getNodeId(node) : 0;
76348     }
76349     ts.getOriginalNodeId = getOriginalNodeId;
76350     function containsDefaultReference(node) {
76351         if (!node)
76352             return false;
76353         if (!ts.isNamedImports(node))
76354             return false;
76355         return ts.some(node.elements, isNamedDefaultReference);
76356     }
76357     function isNamedDefaultReference(e) {
76358         return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
76359     }
76360     function chainBundle(transformSourceFile) {
76361         return transformSourceFileOrBundle;
76362         function transformSourceFileOrBundle(node) {
76363             return node.kind === 290 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
76364         }
76365         function transformBundle(node) {
76366             return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
76367         }
76368     }
76369     ts.chainBundle = chainBundle;
76370     function getExportNeedsImportStarHelper(node) {
76371         return !!ts.getNamespaceDeclarationNode(node);
76372     }
76373     ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
76374     function getImportNeedsImportStarHelper(node) {
76375         if (!!ts.getNamespaceDeclarationNode(node)) {
76376             return true;
76377         }
76378         var bindings = node.importClause && node.importClause.namedBindings;
76379         if (!bindings) {
76380             return false;
76381         }
76382         if (!ts.isNamedImports(bindings))
76383             return false;
76384         var defaultRefCount = 0;
76385         for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
76386             var binding = _a[_i];
76387             if (isNamedDefaultReference(binding)) {
76388                 defaultRefCount++;
76389             }
76390         }
76391         // 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
76392         return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
76393     }
76394     ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
76395     function getImportNeedsImportDefaultHelper(node) {
76396         // 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)
76397         return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
76398     }
76399     ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
76400     function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
76401         var externalImports = [];
76402         var exportSpecifiers = ts.createMultiMap();
76403         var exportedBindings = [];
76404         var uniqueExports = ts.createMap();
76405         var exportedNames;
76406         var hasExportDefault = false;
76407         var exportEquals;
76408         var hasExportStarsToExportValues = false;
76409         var hasImportStar = false;
76410         var hasImportDefault = false;
76411         for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
76412             var node = _a[_i];
76413             switch (node.kind) {
76414                 case 254 /* ImportDeclaration */:
76415                     // import "mod"
76416                     // import x from "mod"
76417                     // import * as x from "mod"
76418                     // import { x, y } from "mod"
76419                     externalImports.push(node);
76420                     if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
76421                         hasImportStar = true;
76422                     }
76423                     if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
76424                         hasImportDefault = true;
76425                     }
76426                     break;
76427                 case 253 /* ImportEqualsDeclaration */:
76428                     if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
76429                         // import x = require("mod")
76430                         externalImports.push(node);
76431                     }
76432                     break;
76433                 case 260 /* ExportDeclaration */:
76434                     if (node.moduleSpecifier) {
76435                         if (!node.exportClause) {
76436                             // export * from "mod"
76437                             externalImports.push(node);
76438                             hasExportStarsToExportValues = true;
76439                         }
76440                         else {
76441                             // export * as ns from "mod"
76442                             // export { x, y } from "mod"
76443                             externalImports.push(node);
76444                         }
76445                     }
76446                     else {
76447                         // export { x, y }
76448                         for (var _b = 0, _c = ts.cast(node.exportClause, ts.isNamedExports).elements; _b < _c.length; _b++) {
76449                             var specifier = _c[_b];
76450                             if (!uniqueExports.get(ts.idText(specifier.name))) {
76451                                 var name = specifier.propertyName || specifier.name;
76452                                 exportSpecifiers.add(ts.idText(name), specifier);
76453                                 var decl = resolver.getReferencedImportDeclaration(name)
76454                                     || resolver.getReferencedValueDeclaration(name);
76455                                 if (decl) {
76456                                     multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
76457                                 }
76458                                 uniqueExports.set(ts.idText(specifier.name), true);
76459                                 exportedNames = ts.append(exportedNames, specifier.name);
76460                             }
76461                         }
76462                     }
76463                     break;
76464                 case 259 /* ExportAssignment */:
76465                     if (node.isExportEquals && !exportEquals) {
76466                         // export = x
76467                         exportEquals = node;
76468                     }
76469                     break;
76470                 case 225 /* VariableStatement */:
76471                     if (ts.hasModifier(node, 1 /* Export */)) {
76472                         for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) {
76473                             var decl = _e[_d];
76474                             exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
76475                         }
76476                     }
76477                     break;
76478                 case 244 /* FunctionDeclaration */:
76479                     if (ts.hasModifier(node, 1 /* Export */)) {
76480                         if (ts.hasModifier(node, 512 /* Default */)) {
76481                             // export default function() { }
76482                             if (!hasExportDefault) {
76483                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76484                                 hasExportDefault = true;
76485                             }
76486                         }
76487                         else {
76488                             // export function x() { }
76489                             var name = node.name;
76490                             if (!uniqueExports.get(ts.idText(name))) {
76491                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76492                                 uniqueExports.set(ts.idText(name), true);
76493                                 exportedNames = ts.append(exportedNames, name);
76494                             }
76495                         }
76496                     }
76497                     break;
76498                 case 245 /* ClassDeclaration */:
76499                     if (ts.hasModifier(node, 1 /* Export */)) {
76500                         if (ts.hasModifier(node, 512 /* Default */)) {
76501                             // export default class { }
76502                             if (!hasExportDefault) {
76503                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76504                                 hasExportDefault = true;
76505                             }
76506                         }
76507                         else {
76508                             // export class x { }
76509                             var name = node.name;
76510                             if (name && !uniqueExports.get(ts.idText(name))) {
76511                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76512                                 uniqueExports.set(ts.idText(name), true);
76513                                 exportedNames = ts.append(exportedNames, name);
76514                             }
76515                         }
76516                     }
76517                     break;
76518             }
76519         }
76520         var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
76521         if (externalHelpersImportDeclaration) {
76522             externalImports.unshift(externalHelpersImportDeclaration);
76523         }
76524         return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
76525     }
76526     ts.collectExternalModuleInfo = collectExternalModuleInfo;
76527     function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
76528         if (ts.isBindingPattern(decl.name)) {
76529             for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
76530                 var element = _a[_i];
76531                 if (!ts.isOmittedExpression(element)) {
76532                     exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
76533                 }
76534             }
76535         }
76536         else if (!ts.isGeneratedIdentifier(decl.name)) {
76537             var text = ts.idText(decl.name);
76538             if (!uniqueExports.get(text)) {
76539                 uniqueExports.set(text, true);
76540                 exportedNames = ts.append(exportedNames, decl.name);
76541             }
76542         }
76543         return exportedNames;
76544     }
76545     /** Use a sparse array as a multi-map. */
76546     function multiMapSparseArrayAdd(map, key, value) {
76547         var values = map[key];
76548         if (values) {
76549             values.push(value);
76550         }
76551         else {
76552             map[key] = values = [value];
76553         }
76554         return values;
76555     }
76556     /**
76557      * Used in the module transformer to check if an expression is reasonably without sideeffect,
76558      *  and thus better to copy into multiple places rather than to cache in a temporary variable
76559      *  - this is mostly subjective beyond the requirement that the expression not be sideeffecting
76560      */
76561     function isSimpleCopiableExpression(expression) {
76562         return ts.isStringLiteralLike(expression) ||
76563             expression.kind === 8 /* NumericLiteral */ ||
76564             ts.isKeyword(expression.kind) ||
76565             ts.isIdentifier(expression);
76566     }
76567     ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
76568     /**
76569      * A simple inlinable expression is an expression which can be copied into multiple locations
76570      * without risk of repeating any sideeffects and whose value could not possibly change between
76571      * any such locations
76572      */
76573     function isSimpleInlineableExpression(expression) {
76574         return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
76575             ts.isWellKnownSymbolSyntactically(expression);
76576     }
76577     ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
76578     function isCompoundAssignment(kind) {
76579         return kind >= 63 /* FirstCompoundAssignment */
76580             && kind <= 74 /* LastCompoundAssignment */;
76581     }
76582     ts.isCompoundAssignment = isCompoundAssignment;
76583     function getNonAssignmentOperatorForCompoundAssignment(kind) {
76584         switch (kind) {
76585             case 63 /* PlusEqualsToken */: return 39 /* PlusToken */;
76586             case 64 /* MinusEqualsToken */: return 40 /* MinusToken */;
76587             case 65 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
76588             case 66 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
76589             case 67 /* SlashEqualsToken */: return 43 /* SlashToken */;
76590             case 68 /* PercentEqualsToken */: return 44 /* PercentToken */;
76591             case 69 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
76592             case 70 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
76593             case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
76594             case 72 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
76595             case 73 /* BarEqualsToken */: return 51 /* BarToken */;
76596             case 74 /* CaretEqualsToken */: return 52 /* CaretToken */;
76597         }
76598     }
76599     ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
76600     /**
76601      * Adds super call and preceding prologue directives into the list of statements.
76602      *
76603      * @param ctor The constructor node.
76604      * @param result The list of statements.
76605      * @param visitor The visitor to apply to each node added to the result array.
76606      * @returns index of the statement that follows super call
76607      */
76608     function addPrologueDirectivesAndInitialSuperCall(ctor, result, visitor) {
76609         if (ctor.body) {
76610             var statements = ctor.body.statements;
76611             // add prologue directives to the list (if any)
76612             var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor);
76613             if (index === statements.length) {
76614                 // list contains nothing but prologue directives (or empty) - exit
76615                 return index;
76616             }
76617             var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
76618             if (superIndex > -1) {
76619                 for (var i = index; i <= superIndex; i++) {
76620                     result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
76621                 }
76622                 return superIndex + 1;
76623             }
76624             return index;
76625         }
76626         return 0;
76627     }
76628     ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
76629     /**
76630      * @param input Template string input strings
76631      * @param args Names which need to be made file-level unique
76632      */
76633     function helperString(input) {
76634         var args = [];
76635         for (var _i = 1; _i < arguments.length; _i++) {
76636             args[_i - 1] = arguments[_i];
76637         }
76638         return function (uniqueName) {
76639             var result = "";
76640             for (var i = 0; i < args.length; i++) {
76641                 result += input[i];
76642                 result += uniqueName(args[i]);
76643             }
76644             result += input[input.length - 1];
76645             return result;
76646         };
76647     }
76648     ts.helperString = helperString;
76649     /**
76650      * Gets all the static or all the instance property declarations of a class
76651      *
76652      * @param node The class node.
76653      * @param isStatic A value indicating whether to get properties from the static or instance side of the class.
76654      */
76655     function getProperties(node, requireInitializer, isStatic) {
76656         return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
76657     }
76658     ts.getProperties = getProperties;
76659     /**
76660      * Is a class element either a static or an instance property declaration with an initializer?
76661      *
76662      * @param member The class element node.
76663      * @param isStatic A value indicating whether the member should be a static or instance member.
76664      */
76665     function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
76666         return ts.isPropertyDeclaration(member)
76667             && (!!member.initializer || !requireInitializer)
76668             && ts.hasStaticModifier(member) === isStatic;
76669     }
76670     /**
76671      * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
76672      *
76673      * @param member The class element node.
76674      * @param isStatic A value indicating whether the member should be a static or instance member.
76675      */
76676     function isInitializedProperty(member) {
76677         return member.kind === 159 /* PropertyDeclaration */
76678             && member.initializer !== undefined;
76679     }
76680     ts.isInitializedProperty = isInitializedProperty;
76681 })(ts || (ts = {}));
76682 /*@internal*/
76683 var ts;
76684 (function (ts) {
76685     var FlattenLevel;
76686     (function (FlattenLevel) {
76687         FlattenLevel[FlattenLevel["All"] = 0] = "All";
76688         FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
76689     })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
76690     /**
76691      * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
76692      *
76693      * @param node The node to flatten.
76694      * @param visitor An optional visitor used to visit initializers.
76695      * @param context The transformation context.
76696      * @param level Indicates the extent to which flattening should occur.
76697      * @param needsValue An optional value indicating whether the value from the right-hand-side of
76698      * the destructuring assignment is needed as part of a larger expression.
76699      * @param createAssignmentCallback An optional callback used to create the assignment expression.
76700      */
76701     function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
76702         var location = node;
76703         var value;
76704         if (ts.isDestructuringAssignment(node)) {
76705             value = node.right;
76706             while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
76707                 if (ts.isDestructuringAssignment(value)) {
76708                     location = node = value;
76709                     value = node.right;
76710                 }
76711                 else {
76712                     return ts.visitNode(value, visitor, ts.isExpression);
76713                 }
76714             }
76715         }
76716         var expressions;
76717         var flattenContext = {
76718             context: context,
76719             level: level,
76720             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76721             hoistTempVariables: true,
76722             emitExpression: emitExpression,
76723             emitBindingOrAssignment: emitBindingOrAssignment,
76724             createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern,
76725             createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern,
76726             createArrayBindingOrAssignmentElement: makeAssignmentElement,
76727             visitor: visitor
76728         };
76729         if (value) {
76730             value = ts.visitNode(value, visitor, ts.isExpression);
76731             if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
76732                 bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
76733                 // If the right-hand value of the assignment is also an assignment target then
76734                 // we need to cache the right-hand value.
76735                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
76736             }
76737             else if (needsValue) {
76738                 // If the right-hand value of the destructuring assignment needs to be preserved (as
76739                 // is the case when the destructuring assignment is part of a larger expression),
76740                 // then we need to cache the right-hand value.
76741                 //
76742                 // The source map location for the assignment should point to the entire binary
76743                 // expression.
76744                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
76745             }
76746             else if (ts.nodeIsSynthesized(node)) {
76747                 // Generally, the source map location for a destructuring assignment is the root
76748                 // expression.
76749                 //
76750                 // However, if the root expression is synthesized (as in the case
76751                 // of the initializer when transforming a ForOfStatement), then the source map
76752                 // location should point to the right-hand value of the expression.
76753                 location = value;
76754             }
76755         }
76756         flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
76757         if (value && needsValue) {
76758             if (!ts.some(expressions)) {
76759                 return value;
76760             }
76761             expressions.push(value);
76762         }
76763         return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression();
76764         function emitExpression(expression) {
76765             ts.aggregateTransformFlags(expression);
76766             expressions = ts.append(expressions, expression);
76767         }
76768         function emitBindingOrAssignment(target, value, location, original) {
76769             ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
76770             var expression = createAssignmentCallback
76771                 ? createAssignmentCallback(target, value, location)
76772                 : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
76773             expression.original = original;
76774             emitExpression(expression);
76775         }
76776     }
76777     ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
76778     function bindingOrAssignmentElementAssignsToName(element, escapedName) {
76779         var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
76780         if (ts.isBindingOrAssignmentPattern(target)) {
76781             return bindingOrAssignmentPatternAssignsToName(target, escapedName);
76782         }
76783         else if (ts.isIdentifier(target)) {
76784             return target.escapedText === escapedName;
76785         }
76786         return false;
76787     }
76788     function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
76789         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76790         for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
76791             var element = elements_3[_i];
76792             if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
76793                 return true;
76794             }
76795         }
76796         return false;
76797     }
76798     function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
76799         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
76800         if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
76801             return true;
76802         }
76803         var target = ts.getTargetOfBindingOrAssignmentElement(element);
76804         return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
76805     }
76806     function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
76807         return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
76808     }
76809     /**
76810      * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
76811      *
76812      * @param node The node to flatten.
76813      * @param visitor An optional visitor used to visit initializers.
76814      * @param context The transformation context.
76815      * @param boundValue The value bound to the declaration.
76816      * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
76817      * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
76818      * @param level Indicates the extent to which flattening should occur.
76819      */
76820     function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
76821         if (hoistTempVariables === void 0) { hoistTempVariables = false; }
76822         var pendingExpressions;
76823         var pendingDeclarations = [];
76824         var declarations = [];
76825         var flattenContext = {
76826             context: context,
76827             level: level,
76828             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76829             hoistTempVariables: hoistTempVariables,
76830             emitExpression: emitExpression,
76831             emitBindingOrAssignment: emitBindingOrAssignment,
76832             createArrayBindingOrAssignmentPattern: makeArrayBindingPattern,
76833             createObjectBindingOrAssignmentPattern: makeObjectBindingPattern,
76834             createArrayBindingOrAssignmentElement: makeBindingElement,
76835             visitor: visitor
76836         };
76837         if (ts.isVariableDeclaration(node)) {
76838             var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
76839             if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
76840                 bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
76841                 // If the right-hand value of the assignment is also an assignment target then
76842                 // we need to cache the right-hand value.
76843                 initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
76844                 node = ts.updateVariableDeclaration(node, node.name, node.type, initializer);
76845             }
76846         }
76847         flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
76848         if (pendingExpressions) {
76849             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
76850             if (hoistTempVariables) {
76851                 var value = ts.inlineExpressions(pendingExpressions);
76852                 pendingExpressions = undefined;
76853                 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
76854             }
76855             else {
76856                 context.hoistVariableDeclaration(temp);
76857                 var pendingDeclaration = ts.last(pendingDeclarations);
76858                 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value));
76859                 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
76860                 pendingDeclaration.value = temp;
76861             }
76862         }
76863         for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
76864             var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
76865             var variable = ts.createVariableDeclaration(name, 
76866             /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
76867             variable.original = original;
76868             ts.setTextRange(variable, location);
76869             ts.aggregateTransformFlags(variable);
76870             declarations.push(variable);
76871         }
76872         return declarations;
76873         function emitExpression(value) {
76874             pendingExpressions = ts.append(pendingExpressions, value);
76875         }
76876         function emitBindingOrAssignment(target, value, location, original) {
76877             ts.Debug.assertNode(target, ts.isBindingName);
76878             if (pendingExpressions) {
76879                 value = ts.inlineExpressions(ts.append(pendingExpressions, value));
76880                 pendingExpressions = undefined;
76881             }
76882             pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
76883         }
76884     }
76885     ts.flattenDestructuringBinding = flattenDestructuringBinding;
76886     /**
76887      * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
76888      *
76889      * @param flattenContext Options used to control flattening.
76890      * @param element The element to flatten.
76891      * @param value The current RHS value to assign to the element.
76892      * @param location The location to use for source maps and comments.
76893      * @param skipInitializer An optional value indicating whether to include the initializer
76894      * for the element.
76895      */
76896     function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
76897         if (!skipInitializer) {
76898             var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
76899             if (initializer) {
76900                 // Combine value and initializer
76901                 value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer;
76902             }
76903             else if (!value) {
76904                 // Use 'void 0' in absence of value and initializer
76905                 value = ts.createVoidZero();
76906             }
76907         }
76908         var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
76909         if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
76910             flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
76911         }
76912         else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
76913             flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
76914         }
76915         else {
76916             flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
76917         }
76918     }
76919     /**
76920      * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
76921      *
76922      * @param flattenContext Options used to control flattening.
76923      * @param parent The parent element of the pattern.
76924      * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
76925      * @param value The current RHS value to assign to the element.
76926      * @param location The location to use for source maps and comments.
76927      */
76928     function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
76929         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76930         var numElements = elements.length;
76931         if (numElements !== 1) {
76932             // For anything other than a single-element destructuring we need to generate a temporary
76933             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
76934             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
76935             // so in that case, we'll intentionally create that temporary.
76936             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
76937             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
76938         }
76939         var bindingElements;
76940         var computedTempVariables;
76941         for (var i = 0; i < numElements; i++) {
76942             var element = elements[i];
76943             if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
76944                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
76945                 if (flattenContext.level >= 1 /* ObjectRest */
76946                     && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
76947                     && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
76948                     && !ts.isComputedPropertyName(propertyName)) {
76949                     bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
76950                 }
76951                 else {
76952                     if (bindingElements) {
76953                         flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76954                         bindingElements = undefined;
76955                     }
76956                     var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
76957                     if (ts.isComputedPropertyName(propertyName)) {
76958                         computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
76959                     }
76960                     flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
76961                 }
76962             }
76963             else if (i === numElements - 1) {
76964                 if (bindingElements) {
76965                     flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76966                     bindingElements = undefined;
76967                 }
76968                 var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217
76969                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
76970             }
76971         }
76972         if (bindingElements) {
76973             flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76974         }
76975     }
76976     /**
76977      * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
76978      *
76979      * @param flattenContext Options used to control flattening.
76980      * @param parent The parent element of the pattern.
76981      * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
76982      * @param value The current RHS value to assign to the element.
76983      * @param location The location to use for source maps and comments.
76984      */
76985     function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
76986         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76987         var numElements = elements.length;
76988         if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
76989             // Read the elements of the iterable into an array
76990             value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
76991                 ? undefined
76992                 : numElements, location), 
76993             /*reuseIdentifierExpressions*/ false, location);
76994         }
76995         else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
76996             || ts.every(elements, ts.isOmittedExpression)) {
76997             // For anything other than a single-element destructuring we need to generate a temporary
76998             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
76999             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
77000             // so in that case, we'll intentionally create that temporary.
77001             // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
77002             // then we will create temporary variable.
77003             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
77004             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
77005         }
77006         var bindingElements;
77007         var restContainingElements;
77008         for (var i = 0; i < numElements; i++) {
77009             var element = elements[i];
77010             if (flattenContext.level >= 1 /* ObjectRest */) {
77011                 // If an array pattern contains an ObjectRest, we must cache the result so that we
77012                 // can perform the ObjectRest destructuring in a different declaration
77013                 if (element.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
77014                     var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77015                     if (flattenContext.hoistTempVariables) {
77016                         flattenContext.context.hoistVariableDeclaration(temp);
77017                     }
77018                     restContainingElements = ts.append(restContainingElements, [temp, element]);
77019                     bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
77020                 }
77021                 else {
77022                     bindingElements = ts.append(bindingElements, element);
77023                 }
77024             }
77025             else if (ts.isOmittedExpression(element)) {
77026                 continue;
77027             }
77028             else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
77029                 var rhsValue = ts.createElementAccess(value, i);
77030                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77031             }
77032             else if (i === numElements - 1) {
77033                 var rhsValue = ts.createArraySlice(value, i);
77034                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77035             }
77036         }
77037         if (bindingElements) {
77038             flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
77039         }
77040         if (restContainingElements) {
77041             for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
77042                 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
77043                 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
77044             }
77045         }
77046     }
77047     /**
77048      * Creates an expression used to provide a default value if a value is `undefined` at runtime.
77049      *
77050      * @param flattenContext Options used to control flattening.
77051      * @param value The RHS value to test.
77052      * @param defaultValue The default value to use if `value` is `undefined` at runtime.
77053      * @param location The location to use for source maps and comments.
77054      */
77055     function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
77056         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
77057         return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value);
77058     }
77059     /**
77060      * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
77061      * right-hand side of a transformed destructuring assignment.
77062      *
77063      * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
77064      *
77065      * @param flattenContext Options used to control flattening.
77066      * @param value The RHS value that is the source of the property.
77067      * @param propertyName The destructuring property name.
77068      */
77069     function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
77070         if (ts.isComputedPropertyName(propertyName)) {
77071             var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
77072             return ts.createElementAccess(value, argumentExpression);
77073         }
77074         else if (ts.isStringOrNumericLiteralLike(propertyName)) {
77075             var argumentExpression = ts.getSynthesizedClone(propertyName);
77076             argumentExpression.text = argumentExpression.text;
77077             return ts.createElementAccess(value, argumentExpression);
77078         }
77079         else {
77080             var name = ts.createIdentifier(ts.idText(propertyName));
77081             return ts.createPropertyAccess(value, name);
77082         }
77083     }
77084     /**
77085      * Ensures that there exists a declared identifier whose value holds the given expression.
77086      * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
77087      * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
77088      *
77089      * @param flattenContext Options used to control flattening.
77090      * @param value the expression whose value needs to be bound.
77091      * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
77092      * false if it is necessary to always emit an identifier.
77093      * @param location The location to use for source maps and comments.
77094      */
77095     function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
77096         if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
77097             return value;
77098         }
77099         else {
77100             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77101             if (flattenContext.hoistTempVariables) {
77102                 flattenContext.context.hoistVariableDeclaration(temp);
77103                 flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location));
77104             }
77105             else {
77106                 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
77107             }
77108             return temp;
77109         }
77110     }
77111     function makeArrayBindingPattern(elements) {
77112         ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
77113         return ts.createArrayBindingPattern(elements);
77114     }
77115     function makeArrayAssignmentPattern(elements) {
77116         return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement));
77117     }
77118     function makeObjectBindingPattern(elements) {
77119         ts.Debug.assertEachNode(elements, ts.isBindingElement);
77120         return ts.createObjectBindingPattern(elements);
77121     }
77122     function makeObjectAssignmentPattern(elements) {
77123         return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement));
77124     }
77125     function makeBindingElement(name) {
77126         return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
77127     }
77128     function makeAssignmentElement(name) {
77129         return name;
77130     }
77131     ts.restHelper = {
77132         name: "typescript:rest",
77133         importName: "__rest",
77134         scoped: false,
77135         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            };"
77136     };
77137     /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
77138      * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
77139      */
77140     function createRestCall(context, value, elements, computedTempVariables, location) {
77141         context.requestEmitHelper(ts.restHelper);
77142         var propertyNames = [];
77143         var computedTempVariableOffset = 0;
77144         for (var i = 0; i < elements.length - 1; i++) {
77145             var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
77146             if (propertyName) {
77147                 if (ts.isComputedPropertyName(propertyName)) {
77148                     var temp = computedTempVariables[computedTempVariableOffset];
77149                     computedTempVariableOffset++;
77150                     // typeof _tmp === "symbol" ? _tmp : _tmp + ""
77151                     propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral(""))));
77152                 }
77153                 else {
77154                     propertyNames.push(ts.createLiteral(propertyName));
77155                 }
77156             }
77157         }
77158         return ts.createCall(ts.getUnscopedHelperName("__rest"), 
77159         /*typeArguments*/ undefined, [
77160             value,
77161             ts.setTextRange(ts.createArrayLiteral(propertyNames), location)
77162         ]);
77163     }
77164 })(ts || (ts = {}));
77165 /*@internal*/
77166 var ts;
77167 (function (ts) {
77168     var ProcessLevel;
77169     (function (ProcessLevel) {
77170         ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction";
77171         ProcessLevel[ProcessLevel["All"] = 1] = "All";
77172     })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {}));
77173     function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
77174         // Visit the tag expression
77175         var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
77176         // Build up the template arguments and the raw and cooked strings for the template.
77177         // We start out with 'undefined' for the first argument and revisit later
77178         // to avoid walking over the template string twice and shifting all our arguments over after the fact.
77179         var templateArguments = [undefined];
77180         var cookedStrings = [];
77181         var rawStrings = [];
77182         var template = node.template;
77183         if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template))
77184             return node;
77185         if (ts.isNoSubstitutionTemplateLiteral(template)) {
77186             cookedStrings.push(createTemplateCooked(template));
77187             rawStrings.push(getRawLiteral(template, currentSourceFile));
77188         }
77189         else {
77190             cookedStrings.push(createTemplateCooked(template.head));
77191             rawStrings.push(getRawLiteral(template.head, currentSourceFile));
77192             for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
77193                 var templateSpan = _a[_i];
77194                 cookedStrings.push(createTemplateCooked(templateSpan.literal));
77195                 rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
77196                 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
77197             }
77198         }
77199         var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings));
77200         // Create a variable to cache the template object if we're in a module.
77201         // Do not do this in the global scope, as any variable we currently generate could conflict with
77202         // variables from outside of the current compilation. In the future, we can revisit this behavior.
77203         if (ts.isExternalModule(currentSourceFile)) {
77204             var tempVar = ts.createUniqueName("templateObject");
77205             recordTaggedTemplateString(tempVar);
77206             templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall));
77207         }
77208         else {
77209             templateArguments[0] = helperCall;
77210         }
77211         return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments);
77212     }
77213     ts.processTaggedTemplateExpression = processTaggedTemplateExpression;
77214     function createTemplateCooked(template) {
77215         return template.templateFlags ? ts.createIdentifier("undefined") : ts.createLiteral(template.text);
77216     }
77217     /**
77218      * Creates an ES5 compatible literal from an ES6 template literal.
77219      *
77220      * @param node The ES6 template literal.
77221      */
77222     function getRawLiteral(node, currentSourceFile) {
77223         // Find original source text, since we need to emit the raw strings of the tagged template.
77224         // The raw strings contain the (escaped) strings of what the user wrote.
77225         // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
77226         var text = node.rawText;
77227         if (text === undefined) {
77228             text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
77229             // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
77230             // thus we need to remove those characters.
77231             // First template piece starts with "`", others with "}"
77232             // Last template piece ends with "`", others with "${"
77233             var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
77234             text = text.substring(1, text.length - (isLast ? 1 : 2));
77235         }
77236         // Newline normalization:
77237         // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
77238         // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
77239         text = text.replace(/\r\n?/g, "\n");
77240         return ts.setTextRange(ts.createLiteral(text), node);
77241     }
77242     function createTemplateObjectHelper(context, cooked, raw) {
77243         context.requestEmitHelper(ts.templateObjectHelper);
77244         return ts.createCall(ts.getUnscopedHelperName("__makeTemplateObject"), 
77245         /*typeArguments*/ undefined, [
77246             cooked,
77247             raw
77248         ]);
77249     }
77250     ts.templateObjectHelper = {
77251         name: "typescript:makeTemplateObject",
77252         importName: "__makeTemplateObject",
77253         scoped: false,
77254         priority: 0,
77255         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            };"
77256     };
77257 })(ts || (ts = {}));
77258 /*@internal*/
77259 var ts;
77260 (function (ts) {
77261     /**
77262      * Indicates whether to emit type metadata in the new format.
77263      */
77264     var USE_NEW_TYPE_METADATA_FORMAT = false;
77265     var TypeScriptSubstitutionFlags;
77266     (function (TypeScriptSubstitutionFlags) {
77267         /** Enables substitutions for decorated classes. */
77268         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
77269         /** Enables substitutions for namespace exports. */
77270         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
77271         /* Enables substitutions for unqualified enum members */
77272         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
77273     })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
77274     var ClassFacts;
77275     (function (ClassFacts) {
77276         ClassFacts[ClassFacts["None"] = 0] = "None";
77277         ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
77278         ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
77279         ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
77280         ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
77281         ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
77282         ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
77283         ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
77284         ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
77285         ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
77286         ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
77287         ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
77288         ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
77289     })(ClassFacts || (ClassFacts = {}));
77290     function transformTypeScript(context) {
77291         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
77292         var resolver = context.getEmitResolver();
77293         var compilerOptions = context.getCompilerOptions();
77294         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
77295         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
77296         var moduleKind = ts.getEmitModuleKind(compilerOptions);
77297         // Save the previous transformation hooks.
77298         var previousOnEmitNode = context.onEmitNode;
77299         var previousOnSubstituteNode = context.onSubstituteNode;
77300         // Set new transformation hooks.
77301         context.onEmitNode = onEmitNode;
77302         context.onSubstituteNode = onSubstituteNode;
77303         // Enable substitution for property/element access to emit const enum values.
77304         context.enableSubstitution(194 /* PropertyAccessExpression */);
77305         context.enableSubstitution(195 /* ElementAccessExpression */);
77306         // These variables contain state that changes as we descend into the tree.
77307         var currentSourceFile;
77308         var currentNamespace;
77309         var currentNamespaceContainerName;
77310         var currentLexicalScope;
77311         var currentNameScope;
77312         var currentScopeFirstDeclarationsOfName;
77313         var currentClassHasParameterProperties;
77314         /**
77315          * Keeps track of whether expression substitution has been enabled for specific edge cases.
77316          * They are persisted between each SourceFile transformation and should not be reset.
77317          */
77318         var enabledSubstitutions;
77319         /**
77320          * A map that keeps track of aliases created for classes with decorators to avoid issues
77321          * with the double-binding behavior of classes.
77322          */
77323         var classAliases;
77324         /**
77325          * Keeps track of whether we are within any containing namespaces when performing
77326          * just-in-time substitution while printing an expression identifier.
77327          */
77328         var applicableSubstitutions;
77329         return transformSourceFileOrBundle;
77330         function transformSourceFileOrBundle(node) {
77331             if (node.kind === 291 /* Bundle */) {
77332                 return transformBundle(node);
77333             }
77334             return transformSourceFile(node);
77335         }
77336         function transformBundle(node) {
77337             return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
77338                 if (prepend.kind === 293 /* InputFiles */) {
77339                     return ts.createUnparsedSourceFile(prepend, "js");
77340                 }
77341                 return prepend;
77342             }));
77343         }
77344         /**
77345          * Transform TypeScript-specific syntax in a SourceFile.
77346          *
77347          * @param node A SourceFile node.
77348          */
77349         function transformSourceFile(node) {
77350             if (node.isDeclarationFile) {
77351                 return node;
77352             }
77353             currentSourceFile = node;
77354             var visited = saveStateAndInvoke(node, visitSourceFile);
77355             ts.addEmitHelpers(visited, context.readEmitHelpers());
77356             currentSourceFile = undefined;
77357             return visited;
77358         }
77359         /**
77360          * Visits a node, saving and restoring state variables on the stack.
77361          *
77362          * @param node The node to visit.
77363          */
77364         function saveStateAndInvoke(node, f) {
77365             // Save state
77366             var savedCurrentScope = currentLexicalScope;
77367             var savedCurrentNameScope = currentNameScope;
77368             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
77369             var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
77370             // Handle state changes before visiting a node.
77371             onBeforeVisitNode(node);
77372             var visited = f(node);
77373             // Restore state
77374             if (currentLexicalScope !== savedCurrentScope) {
77375                 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
77376             }
77377             currentLexicalScope = savedCurrentScope;
77378             currentNameScope = savedCurrentNameScope;
77379             currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
77380             return visited;
77381         }
77382         /**
77383          * Performs actions that should always occur immediately before visiting a node.
77384          *
77385          * @param node The node to visit.
77386          */
77387         function onBeforeVisitNode(node) {
77388             switch (node.kind) {
77389                 case 290 /* SourceFile */:
77390                 case 251 /* CaseBlock */:
77391                 case 250 /* ModuleBlock */:
77392                 case 223 /* Block */:
77393                     currentLexicalScope = node;
77394                     currentNameScope = undefined;
77395                     currentScopeFirstDeclarationsOfName = undefined;
77396                     break;
77397                 case 245 /* ClassDeclaration */:
77398                 case 244 /* FunctionDeclaration */:
77399                     if (ts.hasModifier(node, 2 /* Ambient */)) {
77400                         break;
77401                     }
77402                     // Record these declarations provided that they have a name.
77403                     if (node.name) {
77404                         recordEmittedDeclarationInScope(node);
77405                     }
77406                     else {
77407                         // These nodes should always have names unless they are default-exports;
77408                         // however, class declaration parsing allows for undefined names, so syntactically invalid
77409                         // programs may also have an undefined name.
77410                         ts.Debug.assert(node.kind === 245 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */));
77411                     }
77412                     if (ts.isClassDeclaration(node)) {
77413                         // XXX: should probably also cover interfaces and type aliases that can have type variables?
77414                         currentNameScope = node;
77415                     }
77416                     break;
77417             }
77418         }
77419         /**
77420          * General-purpose node visitor.
77421          *
77422          * @param node The node to visit.
77423          */
77424         function visitor(node) {
77425             return saveStateAndInvoke(node, visitorWorker);
77426         }
77427         /**
77428          * Visits and possibly transforms any node.
77429          *
77430          * @param node The node to visit.
77431          */
77432         function visitorWorker(node) {
77433             if (node.transformFlags & 1 /* ContainsTypeScript */) {
77434                 return visitTypeScript(node);
77435             }
77436             return node;
77437         }
77438         /**
77439          * Specialized visitor that visits the immediate children of a SourceFile.
77440          *
77441          * @param node The node to visit.
77442          */
77443         function sourceElementVisitor(node) {
77444             return saveStateAndInvoke(node, sourceElementVisitorWorker);
77445         }
77446         /**
77447          * Specialized visitor that visits the immediate children of a SourceFile.
77448          *
77449          * @param node The node to visit.
77450          */
77451         function sourceElementVisitorWorker(node) {
77452             switch (node.kind) {
77453                 case 254 /* ImportDeclaration */:
77454                 case 253 /* ImportEqualsDeclaration */:
77455                 case 259 /* ExportAssignment */:
77456                 case 260 /* ExportDeclaration */:
77457                     return visitEllidableStatement(node);
77458                 default:
77459                     return visitorWorker(node);
77460             }
77461         }
77462         function visitEllidableStatement(node) {
77463             var parsed = ts.getParseTreeNode(node);
77464             if (parsed !== node) {
77465                 // If the node has been transformed by a `before` transformer, perform no ellision on it
77466                 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
77467                 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
77468                 // and will trigger debug failures when debug verbosity is turned up
77469                 if (node.transformFlags & 1 /* ContainsTypeScript */) {
77470                     // This node contains TypeScript, so we should visit its children.
77471                     return ts.visitEachChild(node, visitor, context);
77472                 }
77473                 // Otherwise, we can just return the node
77474                 return node;
77475             }
77476             switch (node.kind) {
77477                 case 254 /* ImportDeclaration */:
77478                     return visitImportDeclaration(node);
77479                 case 253 /* ImportEqualsDeclaration */:
77480                     return visitImportEqualsDeclaration(node);
77481                 case 259 /* ExportAssignment */:
77482                     return visitExportAssignment(node);
77483                 case 260 /* ExportDeclaration */:
77484                     return visitExportDeclaration(node);
77485                 default:
77486                     ts.Debug.fail("Unhandled ellided statement");
77487             }
77488         }
77489         /**
77490          * Specialized visitor that visits the immediate children of a namespace.
77491          *
77492          * @param node The node to visit.
77493          */
77494         function namespaceElementVisitor(node) {
77495             return saveStateAndInvoke(node, namespaceElementVisitorWorker);
77496         }
77497         /**
77498          * Specialized visitor that visits the immediate children of a namespace.
77499          *
77500          * @param node The node to visit.
77501          */
77502         function namespaceElementVisitorWorker(node) {
77503             if (node.kind === 260 /* ExportDeclaration */ ||
77504                 node.kind === 254 /* ImportDeclaration */ ||
77505                 node.kind === 255 /* ImportClause */ ||
77506                 (node.kind === 253 /* ImportEqualsDeclaration */ &&
77507                     node.moduleReference.kind === 265 /* ExternalModuleReference */)) {
77508                 // do not emit ES6 imports and exports since they are illegal inside a namespace
77509                 return undefined;
77510             }
77511             else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
77512                 return visitTypeScript(node);
77513             }
77514             return node;
77515         }
77516         /**
77517          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77518          *
77519          * @param node The node to visit.
77520          */
77521         function classElementVisitor(node) {
77522             return saveStateAndInvoke(node, classElementVisitorWorker);
77523         }
77524         /**
77525          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77526          *
77527          * @param node The node to visit.
77528          */
77529         function classElementVisitorWorker(node) {
77530             switch (node.kind) {
77531                 case 162 /* Constructor */:
77532                     return visitConstructor(node);
77533                 case 159 /* PropertyDeclaration */:
77534                     // Property declarations are not TypeScript syntax, but they must be visited
77535                     // for the decorator transformation.
77536                     return visitPropertyDeclaration(node);
77537                 case 167 /* IndexSignature */:
77538                 case 163 /* GetAccessor */:
77539                 case 164 /* SetAccessor */:
77540                 case 161 /* MethodDeclaration */:
77541                     // Fallback to the default visit behavior.
77542                     return visitorWorker(node);
77543                 case 222 /* SemicolonClassElement */:
77544                     return node;
77545                 default:
77546                     return ts.Debug.failBadSyntaxKind(node);
77547             }
77548         }
77549         function modifierVisitor(node) {
77550             if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
77551                 return undefined;
77552             }
77553             else if (currentNamespace && node.kind === 89 /* ExportKeyword */) {
77554                 return undefined;
77555             }
77556             return node;
77557         }
77558         /**
77559          * Branching visitor, visits a TypeScript syntax node.
77560          *
77561          * @param node The node to visit.
77562          */
77563         function visitTypeScript(node) {
77564             if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
77565                 // TypeScript ambient declarations are elided, but some comments may be preserved.
77566                 // See the implementation of `getLeadingComments` in comments.ts for more details.
77567                 return ts.createNotEmittedStatement(node);
77568             }
77569             switch (node.kind) {
77570                 case 89 /* ExportKeyword */:
77571                 case 84 /* DefaultKeyword */:
77572                     // ES6 export and default modifiers are elided when inside a namespace.
77573                     return currentNamespace ? undefined : node;
77574                 case 119 /* PublicKeyword */:
77575                 case 117 /* PrivateKeyword */:
77576                 case 118 /* ProtectedKeyword */:
77577                 case 122 /* AbstractKeyword */:
77578                 case 81 /* ConstKeyword */:
77579                 case 130 /* DeclareKeyword */:
77580                 case 138 /* ReadonlyKeyword */:
77581                 // TypeScript accessibility and readonly modifiers are elided
77582                 // falls through
77583                 case 174 /* ArrayType */:
77584                 case 175 /* TupleType */:
77585                 case 176 /* OptionalType */:
77586                 case 177 /* RestType */:
77587                 case 173 /* TypeLiteral */:
77588                 case 168 /* TypePredicate */:
77589                 case 155 /* TypeParameter */:
77590                 case 125 /* AnyKeyword */:
77591                 case 148 /* UnknownKeyword */:
77592                 case 128 /* BooleanKeyword */:
77593                 case 143 /* StringKeyword */:
77594                 case 140 /* NumberKeyword */:
77595                 case 137 /* NeverKeyword */:
77596                 case 110 /* VoidKeyword */:
77597                 case 144 /* SymbolKeyword */:
77598                 case 171 /* ConstructorType */:
77599                 case 170 /* FunctionType */:
77600                 case 172 /* TypeQuery */:
77601                 case 169 /* TypeReference */:
77602                 case 178 /* UnionType */:
77603                 case 179 /* IntersectionType */:
77604                 case 180 /* ConditionalType */:
77605                 case 182 /* ParenthesizedType */:
77606                 case 183 /* ThisType */:
77607                 case 184 /* TypeOperator */:
77608                 case 185 /* IndexedAccessType */:
77609                 case 186 /* MappedType */:
77610                 case 187 /* LiteralType */:
77611                 // TypeScript type nodes are elided.
77612                 // falls through
77613                 case 167 /* IndexSignature */:
77614                 // TypeScript index signatures are elided.
77615                 // falls through
77616                 case 157 /* Decorator */:
77617                 // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
77618                 // falls through
77619                 case 247 /* TypeAliasDeclaration */:
77620                     // TypeScript type-only declarations are elided.
77621                     return undefined;
77622                 case 159 /* PropertyDeclaration */:
77623                     // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
77624                     return visitPropertyDeclaration(node);
77625                 case 252 /* NamespaceExportDeclaration */:
77626                     // TypeScript namespace export declarations are elided.
77627                     return undefined;
77628                 case 162 /* Constructor */:
77629                     return visitConstructor(node);
77630                 case 246 /* InterfaceDeclaration */:
77631                     // TypeScript interfaces are elided, but some comments may be preserved.
77632                     // See the implementation of `getLeadingComments` in comments.ts for more details.
77633                     return ts.createNotEmittedStatement(node);
77634                 case 245 /* ClassDeclaration */:
77635                     // This may be a class declaration with TypeScript syntax extensions.
77636                     //
77637                     // TypeScript class syntax extensions include:
77638                     // - decorators
77639                     // - optional `implements` heritage clause
77640                     // - parameter property assignments in the constructor
77641                     // - index signatures
77642                     // - method overload signatures
77643                     return visitClassDeclaration(node);
77644                 case 214 /* ClassExpression */:
77645                     // This may be a class expression with TypeScript syntax extensions.
77646                     //
77647                     // TypeScript class syntax extensions include:
77648                     // - decorators
77649                     // - optional `implements` heritage clause
77650                     // - parameter property assignments in the constructor
77651                     // - index signatures
77652                     // - method overload signatures
77653                     return visitClassExpression(node);
77654                 case 279 /* HeritageClause */:
77655                     // This may be a heritage clause with TypeScript syntax extensions.
77656                     //
77657                     // TypeScript heritage clause extensions include:
77658                     // - `implements` clause
77659                     return visitHeritageClause(node);
77660                 case 216 /* ExpressionWithTypeArguments */:
77661                     // TypeScript supports type arguments on an expression in an `extends` heritage clause.
77662                     return visitExpressionWithTypeArguments(node);
77663                 case 161 /* MethodDeclaration */:
77664                     // TypeScript method declarations may have decorators, modifiers
77665                     // or type annotations.
77666                     return visitMethodDeclaration(node);
77667                 case 163 /* GetAccessor */:
77668                     // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
77669                     return visitGetAccessor(node);
77670                 case 164 /* SetAccessor */:
77671                     // Set Accessors can have TypeScript modifiers and type annotations.
77672                     return visitSetAccessor(node);
77673                 case 244 /* FunctionDeclaration */:
77674                     // Typescript function declarations can have modifiers, decorators, and type annotations.
77675                     return visitFunctionDeclaration(node);
77676                 case 201 /* FunctionExpression */:
77677                     // TypeScript function expressions can have modifiers and type annotations.
77678                     return visitFunctionExpression(node);
77679                 case 202 /* ArrowFunction */:
77680                     // TypeScript arrow functions can have modifiers and type annotations.
77681                     return visitArrowFunction(node);
77682                 case 156 /* Parameter */:
77683                     // This may be a parameter declaration with TypeScript syntax extensions.
77684                     //
77685                     // TypeScript parameter declaration syntax extensions include:
77686                     // - decorators
77687                     // - accessibility modifiers
77688                     // - the question mark (?) token for optional parameters
77689                     // - type annotations
77690                     // - this parameters
77691                     return visitParameter(node);
77692                 case 200 /* ParenthesizedExpression */:
77693                     // ParenthesizedExpressions are TypeScript if their expression is a
77694                     // TypeAssertion or AsExpression
77695                     return visitParenthesizedExpression(node);
77696                 case 199 /* TypeAssertionExpression */:
77697                 case 217 /* AsExpression */:
77698                     // TypeScript type assertions are removed, but their subtrees are preserved.
77699                     return visitAssertionExpression(node);
77700                 case 196 /* CallExpression */:
77701                     return visitCallExpression(node);
77702                 case 197 /* NewExpression */:
77703                     return visitNewExpression(node);
77704                 case 198 /* TaggedTemplateExpression */:
77705                     return visitTaggedTemplateExpression(node);
77706                 case 218 /* NonNullExpression */:
77707                     // TypeScript non-null expressions are removed, but their subtrees are preserved.
77708                     return visitNonNullExpression(node);
77709                 case 248 /* EnumDeclaration */:
77710                     // TypeScript enum declarations do not exist in ES6 and must be rewritten.
77711                     return visitEnumDeclaration(node);
77712                 case 225 /* VariableStatement */:
77713                     // TypeScript namespace exports for variable statements must be transformed.
77714                     return visitVariableStatement(node);
77715                 case 242 /* VariableDeclaration */:
77716                     return visitVariableDeclaration(node);
77717                 case 249 /* ModuleDeclaration */:
77718                     // TypeScript namespace declarations must be transformed.
77719                     return visitModuleDeclaration(node);
77720                 case 253 /* ImportEqualsDeclaration */:
77721                     // TypeScript namespace or external module import.
77722                     return visitImportEqualsDeclaration(node);
77723                 case 267 /* JsxSelfClosingElement */:
77724                     return visitJsxSelfClosingElement(node);
77725                 case 268 /* JsxOpeningElement */:
77726                     return visitJsxJsxOpeningElement(node);
77727                 default:
77728                     // node contains some other TypeScript syntax
77729                     return ts.visitEachChild(node, visitor, context);
77730             }
77731         }
77732         function visitSourceFile(node) {
77733             var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
77734                 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
77735                 !ts.isJsonSourceFile(node);
77736             return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
77737         }
77738         /**
77739          * Tests whether we should emit a __decorate call for a class declaration.
77740          */
77741         function shouldEmitDecorateCallForClass(node) {
77742             if (node.decorators && node.decorators.length > 0) {
77743                 return true;
77744             }
77745             var constructor = ts.getFirstConstructorWithBody(node);
77746             if (constructor) {
77747                 return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
77748             }
77749             return false;
77750         }
77751         /**
77752          * Tests whether we should emit a __decorate call for a parameter declaration.
77753          */
77754         function shouldEmitDecorateCallForParameter(parameter) {
77755             return parameter.decorators !== undefined && parameter.decorators.length > 0;
77756         }
77757         function getClassFacts(node, staticProperties) {
77758             var facts = 0 /* None */;
77759             if (ts.some(staticProperties))
77760                 facts |= 1 /* HasStaticInitializedProperties */;
77761             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
77762             if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */)
77763                 facts |= 64 /* IsDerivedClass */;
77764             if (shouldEmitDecorateCallForClass(node))
77765                 facts |= 2 /* HasConstructorDecorators */;
77766             if (ts.childIsDecorated(node))
77767                 facts |= 4 /* HasMemberDecorators */;
77768             if (isExportOfNamespace(node))
77769                 facts |= 8 /* IsExportOfNamespace */;
77770             else if (isDefaultExternalModuleExport(node))
77771                 facts |= 32 /* IsDefaultExternalExport */;
77772             else if (isNamedExternalModuleExport(node))
77773                 facts |= 16 /* IsNamedExternalExport */;
77774             if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
77775                 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
77776             return facts;
77777         }
77778         function hasTypeScriptClassSyntax(node) {
77779             return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */);
77780         }
77781         function isClassLikeDeclarationWithTypeScriptSyntax(node) {
77782             return ts.some(node.decorators)
77783                 || ts.some(node.typeParameters)
77784                 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
77785                 || ts.some(node.members, hasTypeScriptClassSyntax);
77786         }
77787         function visitClassDeclaration(node) {
77788             if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
77789                 return ts.visitEachChild(node, visitor, context);
77790             }
77791             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
77792             var facts = getClassFacts(node, staticProperties);
77793             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77794                 context.startLexicalEnvironment();
77795             }
77796             var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined);
77797             var classStatement = facts & 2 /* HasConstructorDecorators */
77798                 ? createClassDeclarationHeadWithDecorators(node, name)
77799                 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
77800             var statements = [classStatement];
77801             // Write any decorators of the node.
77802             addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
77803             addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
77804             addConstructorDecorationStatement(statements, node);
77805             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77806                 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
77807                 // 'es2015' transformer can properly nest static initializers and decorators. The result
77808                 // looks something like:
77809                 //
77810                 //  var C = function () {
77811                 //      class C {
77812                 //      }
77813                 //      C.static_prop = 1;
77814                 //      return C;
77815                 //  }();
77816                 //
77817                 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
77818                 var localName = ts.getInternalName(node);
77819                 // The following partially-emitted expression exists purely to align our sourcemap
77820                 // emit with the original emitter.
77821                 var outer = ts.createPartiallyEmittedExpression(localName);
77822                 outer.end = closingBraceLocation.end;
77823                 ts.setEmitFlags(outer, 1536 /* NoComments */);
77824                 var statement = ts.createReturn(outer);
77825                 statement.pos = closingBraceLocation.pos;
77826                 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
77827                 statements.push(statement);
77828                 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
77829                 var iife = ts.createImmediatelyInvokedArrowFunction(statements);
77830                 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
77831                 var varStatement = ts.createVariableStatement(
77832                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
77833                     ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), 
77834                     /*type*/ undefined, iife)
77835                 ]));
77836                 ts.setOriginalNode(varStatement, node);
77837                 ts.setCommentRange(varStatement, node);
77838                 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
77839                 ts.startOnNewLine(varStatement);
77840                 statements = [varStatement];
77841             }
77842             // If the class is exported as part of a TypeScript namespace, emit the namespace export.
77843             // Otherwise, if the class was exported at the top level and was decorated, emit an export
77844             // declaration or export default for the class.
77845             if (facts & 8 /* IsExportOfNamespace */) {
77846                 addExportMemberAssignment(statements, node);
77847             }
77848             else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
77849                 if (facts & 32 /* IsDefaultExternalExport */) {
77850                     statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
77851                 }
77852                 else if (facts & 16 /* IsNamedExternalExport */) {
77853                     statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
77854                 }
77855             }
77856             if (statements.length > 1) {
77857                 // Add a DeclarationMarker as a marker for the end of the declaration
77858                 statements.push(ts.createEndOfDeclarationMarker(node));
77859                 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
77860             }
77861             return ts.singleOrMany(statements);
77862         }
77863         /**
77864          * Transforms a non-decorated class declaration and appends the resulting statements.
77865          *
77866          * @param node A ClassDeclaration node.
77867          * @param name The name of the class.
77868          * @param facts Precomputed facts about the class.
77869          */
77870         function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
77871             //  ${modifiers} class ${name} ${heritageClauses} {
77872             //      ${members}
77873             //  }
77874             // we do not emit modifiers on the declaration if we are emitting an IIFE
77875             var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
77876                 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
77877                 : undefined;
77878             var classDeclaration = ts.createClassDeclaration(
77879             /*decorators*/ undefined, modifiers, name, 
77880             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
77881             // To better align with the old emitter, we should not emit a trailing source map
77882             // entry if the class has static properties.
77883             var emitFlags = ts.getEmitFlags(node);
77884             if (facts & 1 /* HasStaticInitializedProperties */) {
77885                 emitFlags |= 32 /* NoTrailingSourceMap */;
77886             }
77887             ts.aggregateTransformFlags(classDeclaration);
77888             ts.setTextRange(classDeclaration, node);
77889             ts.setOriginalNode(classDeclaration, node);
77890             ts.setEmitFlags(classDeclaration, emitFlags);
77891             return classDeclaration;
77892         }
77893         /**
77894          * Transforms a decorated class declaration and appends the resulting statements. If
77895          * the class requires an alias to avoid issues with double-binding, the alias is returned.
77896          */
77897         function createClassDeclarationHeadWithDecorators(node, name) {
77898             // When we emit an ES6 class that has a class decorator, we must tailor the
77899             // emit to certain specific cases.
77900             //
77901             // In the simplest case, we emit the class declaration as a let declaration, and
77902             // evaluate decorators after the close of the class body:
77903             //
77904             //  [Example 1]
77905             //  ---------------------------------------------------------------------
77906             //  TypeScript                      | Javascript
77907             //  ---------------------------------------------------------------------
77908             //  @dec                            | let C = class C {
77909             //  class C {                       | }
77910             //  }                               | C = __decorate([dec], C);
77911             //  ---------------------------------------------------------------------
77912             //  @dec                            | let C = class C {
77913             //  export class C {                | }
77914             //  }                               | C = __decorate([dec], C);
77915             //                                  | export { C };
77916             //  ---------------------------------------------------------------------
77917             //
77918             // If a class declaration contains a reference to itself *inside* of the class body,
77919             // this introduces two bindings to the class: One outside of the class body, and one
77920             // inside of the class body. If we apply decorators as in [Example 1] above, there
77921             // is the possibility that the decorator `dec` will return a new value for the
77922             // constructor, which would result in the binding inside of the class no longer
77923             // pointing to the same reference as the binding outside of the class.
77924             //
77925             // As a result, we must instead rewrite all references to the class *inside* of the
77926             // class body to instead point to a local temporary alias for the class:
77927             //
77928             //  [Example 2]
77929             //  ---------------------------------------------------------------------
77930             //  TypeScript                      | Javascript
77931             //  ---------------------------------------------------------------------
77932             //  @dec                            | let C = C_1 = class C {
77933             //  class C {                       |   static x() { return C_1.y; }
77934             //    static x() { return C.y; }    | }
77935             //    static y = 1;                 | C.y = 1;
77936             //  }                               | C = C_1 = __decorate([dec], C);
77937             //                                  | var C_1;
77938             //  ---------------------------------------------------------------------
77939             //  @dec                            | let C = class C {
77940             //  export class C {                |   static x() { return C_1.y; }
77941             //    static x() { return C.y; }    | }
77942             //    static y = 1;                 | C.y = 1;
77943             //  }                               | C = C_1 = __decorate([dec], C);
77944             //                                  | export { C };
77945             //                                  | var C_1;
77946             //  ---------------------------------------------------------------------
77947             //
77948             // If a class declaration is the default export of a module, we instead emit
77949             // the export after the decorated declaration:
77950             //
77951             //  [Example 3]
77952             //  ---------------------------------------------------------------------
77953             //  TypeScript                      | Javascript
77954             //  ---------------------------------------------------------------------
77955             //  @dec                            | let default_1 = class {
77956             //  export default class {          | }
77957             //  }                               | default_1 = __decorate([dec], default_1);
77958             //                                  | export default default_1;
77959             //  ---------------------------------------------------------------------
77960             //  @dec                            | let C = class C {
77961             //  export default class C {        | }
77962             //  }                               | C = __decorate([dec], C);
77963             //                                  | export default C;
77964             //  ---------------------------------------------------------------------
77965             //
77966             // If the class declaration is the default export and a reference to itself
77967             // inside of the class body, we must emit both an alias for the class *and*
77968             // move the export after the declaration:
77969             //
77970             //  [Example 4]
77971             //  ---------------------------------------------------------------------
77972             //  TypeScript                      | Javascript
77973             //  ---------------------------------------------------------------------
77974             //  @dec                            | let C = class C {
77975             //  export default class C {        |   static x() { return C_1.y; }
77976             //    static x() { return C.y; }    | }
77977             //    static y = 1;                 | C.y = 1;
77978             //  }                               | C = C_1 = __decorate([dec], C);
77979             //                                  | export default C;
77980             //                                  | var C_1;
77981             //  ---------------------------------------------------------------------
77982             //
77983             var location = ts.moveRangePastDecorators(node);
77984             var classAlias = getClassAliasIfNeeded(node);
77985             var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
77986             //  ... = class ${name} ${heritageClauses} {
77987             //      ${members}
77988             //  }
77989             var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
77990             var members = transformClassMembers(node);
77991             var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
77992             ts.aggregateTransformFlags(classExpression);
77993             ts.setOriginalNode(classExpression, node);
77994             ts.setTextRange(classExpression, location);
77995             //  let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
77996             //                                         or decoratedClassAlias if the class contain self-reference.
77997             var statement = ts.createVariableStatement(
77998             /*modifiers*/ undefined, ts.createVariableDeclarationList([
77999                 ts.createVariableDeclaration(declName, 
78000                 /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression)
78001             ], 1 /* Let */));
78002             ts.setOriginalNode(statement, node);
78003             ts.setTextRange(statement, location);
78004             ts.setCommentRange(statement, node);
78005             return statement;
78006         }
78007         function visitClassExpression(node) {
78008             if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
78009                 return ts.visitEachChild(node, visitor, context);
78010             }
78011             var classExpression = ts.createClassExpression(
78012             /*modifiers*/ undefined, node.name, 
78013             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
78014             ts.aggregateTransformFlags(classExpression);
78015             ts.setOriginalNode(classExpression, node);
78016             ts.setTextRange(classExpression, node);
78017             return classExpression;
78018         }
78019         /**
78020          * Transforms the members of a class.
78021          *
78022          * @param node The current class.
78023          */
78024         function transformClassMembers(node) {
78025             var members = [];
78026             var constructor = ts.getFirstConstructorWithBody(node);
78027             var parametersWithPropertyAssignments = constructor &&
78028                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
78029             if (parametersWithPropertyAssignments) {
78030                 for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
78031                     var parameter = parametersWithPropertyAssignments_1[_i];
78032                     if (ts.isIdentifier(parameter.name)) {
78033                         members.push(ts.setOriginalNode(ts.aggregateTransformFlags(ts.createProperty(
78034                         /*decorators*/ undefined, 
78035                         /*modifiers*/ undefined, parameter.name, 
78036                         /*questionOrExclamationToken*/ undefined, 
78037                         /*type*/ undefined, 
78038                         /*initializer*/ undefined)), parameter));
78039                     }
78040                 }
78041             }
78042             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
78043             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
78044         }
78045         /**
78046          * Gets either the static or instance members of a class that are decorated, or have
78047          * parameters that are decorated.
78048          *
78049          * @param node The class containing the member.
78050          * @param isStatic A value indicating whether to retrieve static or instance members of
78051          *                 the class.
78052          */
78053         function getDecoratedClassElements(node, isStatic) {
78054             return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
78055         }
78056         /**
78057          * Determines whether a class member is a static member of a class that is decorated, or
78058          * has parameters that are decorated.
78059          *
78060          * @param member The class member.
78061          */
78062         function isStaticDecoratedClassElement(member, parent) {
78063             return isDecoratedClassElement(member, /*isStatic*/ true, parent);
78064         }
78065         /**
78066          * Determines whether a class member is an instance member of a class that is decorated,
78067          * or has parameters that are decorated.
78068          *
78069          * @param member The class member.
78070          */
78071         function isInstanceDecoratedClassElement(member, parent) {
78072             return isDecoratedClassElement(member, /*isStatic*/ false, parent);
78073         }
78074         /**
78075          * Determines whether a class member is either a static or an instance member of a class
78076          * that is decorated, or has parameters that are decorated.
78077          *
78078          * @param member The class member.
78079          */
78080         function isDecoratedClassElement(member, isStatic, parent) {
78081             return ts.nodeOrChildIsDecorated(member, parent)
78082                 && isStatic === ts.hasModifier(member, 32 /* Static */);
78083         }
78084         /**
78085          * Gets an array of arrays of decorators for the parameters of a function-like node.
78086          * The offset into the result array should correspond to the offset of the parameter.
78087          *
78088          * @param node The function-like node.
78089          */
78090         function getDecoratorsOfParameters(node) {
78091             var decorators;
78092             if (node) {
78093                 var parameters = node.parameters;
78094                 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
78095                 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
78096                 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
78097                 for (var i = 0; i < numParameters; i++) {
78098                     var parameter = parameters[i + firstParameterOffset];
78099                     if (decorators || parameter.decorators) {
78100                         if (!decorators) {
78101                             decorators = new Array(numParameters);
78102                         }
78103                         decorators[i] = parameter.decorators;
78104                     }
78105                 }
78106             }
78107             return decorators;
78108         }
78109         /**
78110          * Gets an AllDecorators object containing the decorators for the class and the decorators for the
78111          * parameters of the constructor of the class.
78112          *
78113          * @param node The class node.
78114          */
78115         function getAllDecoratorsOfConstructor(node) {
78116             var decorators = node.decorators;
78117             var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
78118             if (!decorators && !parameters) {
78119                 return undefined;
78120             }
78121             return {
78122                 decorators: decorators,
78123                 parameters: parameters
78124             };
78125         }
78126         /**
78127          * Gets an AllDecorators object containing the decorators for the member and its parameters.
78128          *
78129          * @param node The class node that contains the member.
78130          * @param member The class member.
78131          */
78132         function getAllDecoratorsOfClassElement(node, member) {
78133             switch (member.kind) {
78134                 case 163 /* GetAccessor */:
78135                 case 164 /* SetAccessor */:
78136                     return getAllDecoratorsOfAccessors(node, member);
78137                 case 161 /* MethodDeclaration */:
78138                     return getAllDecoratorsOfMethod(member);
78139                 case 159 /* PropertyDeclaration */:
78140                     return getAllDecoratorsOfProperty(member);
78141                 default:
78142                     return undefined;
78143             }
78144         }
78145         /**
78146          * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
78147          *
78148          * @param node The class node that contains the accessor.
78149          * @param accessor The class accessor member.
78150          */
78151         function getAllDecoratorsOfAccessors(node, accessor) {
78152             if (!accessor.body) {
78153                 return undefined;
78154             }
78155             var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
78156             var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
78157             if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
78158                 return undefined;
78159             }
78160             var decorators = firstAccessorWithDecorators.decorators;
78161             var parameters = getDecoratorsOfParameters(setAccessor);
78162             if (!decorators && !parameters) {
78163                 return undefined;
78164             }
78165             return { decorators: decorators, parameters: parameters };
78166         }
78167         /**
78168          * Gets an AllDecorators object containing the decorators for the method and its parameters.
78169          *
78170          * @param method The class method member.
78171          */
78172         function getAllDecoratorsOfMethod(method) {
78173             if (!method.body) {
78174                 return undefined;
78175             }
78176             var decorators = method.decorators;
78177             var parameters = getDecoratorsOfParameters(method);
78178             if (!decorators && !parameters) {
78179                 return undefined;
78180             }
78181             return { decorators: decorators, parameters: parameters };
78182         }
78183         /**
78184          * Gets an AllDecorators object containing the decorators for the property.
78185          *
78186          * @param property The class property member.
78187          */
78188         function getAllDecoratorsOfProperty(property) {
78189             var decorators = property.decorators;
78190             if (!decorators) {
78191                 return undefined;
78192             }
78193             return { decorators: decorators };
78194         }
78195         /**
78196          * Transforms all of the decorators for a declaration into an array of expressions.
78197          *
78198          * @param node The declaration node.
78199          * @param allDecorators An object containing all of the decorators for the declaration.
78200          */
78201         function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
78202             if (!allDecorators) {
78203                 return undefined;
78204             }
78205             var decoratorExpressions = [];
78206             ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
78207             ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
78208             addTypeMetadata(node, container, decoratorExpressions);
78209             return decoratorExpressions;
78210         }
78211         /**
78212          * Generates statements used to apply decorators to either the static or instance members
78213          * of a class.
78214          *
78215          * @param node The class node.
78216          * @param isStatic A value indicating whether to generate statements for static or
78217          *                 instance members.
78218          */
78219         function addClassElementDecorationStatements(statements, node, isStatic) {
78220             ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
78221         }
78222         /**
78223          * Generates expressions used to apply decorators to either the static or instance members
78224          * of a class.
78225          *
78226          * @param node The class node.
78227          * @param isStatic A value indicating whether to generate expressions for static or
78228          *                 instance members.
78229          */
78230         function generateClassElementDecorationExpressions(node, isStatic) {
78231             var members = getDecoratedClassElements(node, isStatic);
78232             var expressions;
78233             for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
78234                 var member = members_6[_i];
78235                 var expression = generateClassElementDecorationExpression(node, member);
78236                 if (expression) {
78237                     if (!expressions) {
78238                         expressions = [expression];
78239                     }
78240                     else {
78241                         expressions.push(expression);
78242                     }
78243                 }
78244             }
78245             return expressions;
78246         }
78247         /**
78248          * Generates an expression used to evaluate class element decorators at runtime.
78249          *
78250          * @param node The class node that contains the member.
78251          * @param member The class member.
78252          */
78253         function generateClassElementDecorationExpression(node, member) {
78254             var allDecorators = getAllDecoratorsOfClassElement(node, member);
78255             var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
78256             if (!decoratorExpressions) {
78257                 return undefined;
78258             }
78259             // Emit the call to __decorate. Given the following:
78260             //
78261             //   class C {
78262             //     @dec method(@dec2 x) {}
78263             //     @dec get accessor() {}
78264             //     @dec prop;
78265             //   }
78266             //
78267             // The emit for a method is:
78268             //
78269             //   __decorate([
78270             //       dec,
78271             //       __param(0, dec2),
78272             //       __metadata("design:type", Function),
78273             //       __metadata("design:paramtypes", [Object]),
78274             //       __metadata("design:returntype", void 0)
78275             //   ], C.prototype, "method", null);
78276             //
78277             // The emit for an accessor is:
78278             //
78279             //   __decorate([
78280             //       dec
78281             //   ], C.prototype, "accessor", null);
78282             //
78283             // The emit for a property is:
78284             //
78285             //   __decorate([
78286             //       dec
78287             //   ], C.prototype, "prop");
78288             //
78289             var prefix = getClassMemberPrefix(node, member);
78290             var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
78291             var descriptor = languageVersion > 0 /* ES3 */
78292                 ? member.kind === 159 /* PropertyDeclaration */
78293                     // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
78294                     // should not invoke `Object.getOwnPropertyDescriptor`.
78295                     ? ts.createVoidZero()
78296                     // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
78297                     // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
78298                     : ts.createNull()
78299                 : undefined;
78300             var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member));
78301             ts.setEmitFlags(helper, 1536 /* NoComments */);
78302             return helper;
78303         }
78304         /**
78305          * Generates a __decorate helper call for a class constructor.
78306          *
78307          * @param node The class node.
78308          */
78309         function addConstructorDecorationStatement(statements, node) {
78310             var expression = generateConstructorDecorationExpression(node);
78311             if (expression) {
78312                 statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node));
78313             }
78314         }
78315         /**
78316          * Generates a __decorate helper call for a class constructor.
78317          *
78318          * @param node The class node.
78319          */
78320         function generateConstructorDecorationExpression(node) {
78321             var allDecorators = getAllDecoratorsOfConstructor(node);
78322             var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
78323             if (!decoratorExpressions) {
78324                 return undefined;
78325             }
78326             var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
78327             var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
78328             var decorate = createDecorateHelper(context, decoratorExpressions, localName);
78329             var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate);
78330             ts.setEmitFlags(expression, 1536 /* NoComments */);
78331             ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
78332             return expression;
78333         }
78334         /**
78335          * Transforms a decorator into an expression.
78336          *
78337          * @param decorator The decorator node.
78338          */
78339         function transformDecorator(decorator) {
78340             return ts.visitNode(decorator.expression, visitor, ts.isExpression);
78341         }
78342         /**
78343          * Transforms the decorators of a parameter.
78344          *
78345          * @param decorators The decorators for the parameter at the provided offset.
78346          * @param parameterOffset The offset of the parameter.
78347          */
78348         function transformDecoratorsOfParameter(decorators, parameterOffset) {
78349             var expressions;
78350             if (decorators) {
78351                 expressions = [];
78352                 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
78353                     var decorator = decorators_1[_i];
78354                     var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, 
78355                     /*location*/ decorator.expression);
78356                     ts.setEmitFlags(helper, 1536 /* NoComments */);
78357                     expressions.push(helper);
78358                 }
78359             }
78360             return expressions;
78361         }
78362         /**
78363          * Adds optional type metadata for a declaration.
78364          *
78365          * @param node The declaration node.
78366          * @param decoratorExpressions The destination array to which to add new decorator expressions.
78367          */
78368         function addTypeMetadata(node, container, decoratorExpressions) {
78369             if (USE_NEW_TYPE_METADATA_FORMAT) {
78370                 addNewTypeMetadata(node, container, decoratorExpressions);
78371             }
78372             else {
78373                 addOldTypeMetadata(node, container, decoratorExpressions);
78374             }
78375         }
78376         function addOldTypeMetadata(node, container, decoratorExpressions) {
78377             if (compilerOptions.emitDecoratorMetadata) {
78378                 if (shouldAddTypeMetadata(node)) {
78379                     decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node)));
78380                 }
78381                 if (shouldAddParamTypesMetadata(node)) {
78382                     decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container)));
78383                 }
78384                 if (shouldAddReturnTypeMetadata(node)) {
78385                     decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node)));
78386                 }
78387             }
78388         }
78389         function addNewTypeMetadata(node, container, decoratorExpressions) {
78390             if (compilerOptions.emitDecoratorMetadata) {
78391                 var properties = void 0;
78392                 if (shouldAddTypeMetadata(node)) {
78393                     (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
78394                 }
78395                 if (shouldAddParamTypesMetadata(node)) {
78396                     (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
78397                 }
78398                 if (shouldAddReturnTypeMetadata(node)) {
78399                     (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
78400                 }
78401                 if (properties) {
78402                     decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true)));
78403                 }
78404             }
78405         }
78406         /**
78407          * Determines whether to emit the "design:type" metadata based on the node's kind.
78408          * The caller should have already tested whether the node has decorators and whether the
78409          * emitDecoratorMetadata compiler option is set.
78410          *
78411          * @param node The node to test.
78412          */
78413         function shouldAddTypeMetadata(node) {
78414             var kind = node.kind;
78415             return kind === 161 /* MethodDeclaration */
78416                 || kind === 163 /* GetAccessor */
78417                 || kind === 164 /* SetAccessor */
78418                 || kind === 159 /* PropertyDeclaration */;
78419         }
78420         /**
78421          * Determines whether to emit the "design:returntype" metadata based on the node's kind.
78422          * The caller should have already tested whether the node has decorators and whether the
78423          * emitDecoratorMetadata compiler option is set.
78424          *
78425          * @param node The node to test.
78426          */
78427         function shouldAddReturnTypeMetadata(node) {
78428             return node.kind === 161 /* MethodDeclaration */;
78429         }
78430         /**
78431          * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
78432          * The caller should have already tested whether the node has decorators and whether the
78433          * emitDecoratorMetadata compiler option is set.
78434          *
78435          * @param node The node to test.
78436          */
78437         function shouldAddParamTypesMetadata(node) {
78438             switch (node.kind) {
78439                 case 245 /* ClassDeclaration */:
78440                 case 214 /* ClassExpression */:
78441                     return ts.getFirstConstructorWithBody(node) !== undefined;
78442                 case 161 /* MethodDeclaration */:
78443                 case 163 /* GetAccessor */:
78444                 case 164 /* SetAccessor */:
78445                     return true;
78446             }
78447             return false;
78448         }
78449         function getAccessorTypeNode(node) {
78450             var accessors = resolver.getAllAccessorDeclarations(node);
78451             return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
78452                 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
78453         }
78454         /**
78455          * Serializes the type of a node for use with decorator type metadata.
78456          *
78457          * @param node The node that should have its type serialized.
78458          */
78459         function serializeTypeOfNode(node) {
78460             switch (node.kind) {
78461                 case 159 /* PropertyDeclaration */:
78462                 case 156 /* Parameter */:
78463                     return serializeTypeNode(node.type);
78464                 case 164 /* SetAccessor */:
78465                 case 163 /* GetAccessor */:
78466                     return serializeTypeNode(getAccessorTypeNode(node));
78467                 case 245 /* ClassDeclaration */:
78468                 case 214 /* ClassExpression */:
78469                 case 161 /* MethodDeclaration */:
78470                     return ts.createIdentifier("Function");
78471                 default:
78472                     return ts.createVoidZero();
78473             }
78474         }
78475         /**
78476          * Serializes the types of the parameters of a node for use with decorator type metadata.
78477          *
78478          * @param node The node that should have its parameter types serialized.
78479          */
78480         function serializeParameterTypesOfNode(node, container) {
78481             var valueDeclaration = ts.isClassLike(node)
78482                 ? ts.getFirstConstructorWithBody(node)
78483                 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
78484                     ? node
78485                     : undefined;
78486             var expressions = [];
78487             if (valueDeclaration) {
78488                 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
78489                 var numParameters = parameters.length;
78490                 for (var i = 0; i < numParameters; i++) {
78491                     var parameter = parameters[i];
78492                     if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
78493                         continue;
78494                     }
78495                     if (parameter.dotDotDotToken) {
78496                         expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
78497                     }
78498                     else {
78499                         expressions.push(serializeTypeOfNode(parameter));
78500                     }
78501                 }
78502             }
78503             return ts.createArrayLiteral(expressions);
78504         }
78505         function getParametersOfDecoratedDeclaration(node, container) {
78506             if (container && node.kind === 163 /* GetAccessor */) {
78507                 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
78508                 if (setAccessor) {
78509                     return setAccessor.parameters;
78510                 }
78511             }
78512             return node.parameters;
78513         }
78514         /**
78515          * Serializes the return type of a node for use with decorator type metadata.
78516          *
78517          * @param node The node that should have its return type serialized.
78518          */
78519         function serializeReturnTypeOfNode(node) {
78520             if (ts.isFunctionLike(node) && node.type) {
78521                 return serializeTypeNode(node.type);
78522             }
78523             else if (ts.isAsyncFunction(node)) {
78524                 return ts.createIdentifier("Promise");
78525             }
78526             return ts.createVoidZero();
78527         }
78528         /**
78529          * Serializes a type node for use with decorator type metadata.
78530          *
78531          * Types are serialized in the following fashion:
78532          * - Void types point to "undefined" (e.g. "void 0")
78533          * - Function and Constructor types point to the global "Function" constructor.
78534          * - Interface types with a call or construct signature types point to the global
78535          *   "Function" constructor.
78536          * - Array and Tuple types point to the global "Array" constructor.
78537          * - Type predicates and booleans point to the global "Boolean" constructor.
78538          * - String literal types and strings point to the global "String" constructor.
78539          * - Enum and number types point to the global "Number" constructor.
78540          * - Symbol types point to the global "Symbol" constructor.
78541          * - Type references to classes (or class-like variables) point to the constructor for the class.
78542          * - Anything else points to the global "Object" constructor.
78543          *
78544          * @param node The type node to serialize.
78545          */
78546         function serializeTypeNode(node) {
78547             if (node === undefined) {
78548                 return ts.createIdentifier("Object");
78549             }
78550             switch (node.kind) {
78551                 case 110 /* VoidKeyword */:
78552                 case 146 /* UndefinedKeyword */:
78553                 case 100 /* NullKeyword */:
78554                 case 137 /* NeverKeyword */:
78555                     return ts.createVoidZero();
78556                 case 182 /* ParenthesizedType */:
78557                     return serializeTypeNode(node.type);
78558                 case 170 /* FunctionType */:
78559                 case 171 /* ConstructorType */:
78560                     return ts.createIdentifier("Function");
78561                 case 174 /* ArrayType */:
78562                 case 175 /* TupleType */:
78563                     return ts.createIdentifier("Array");
78564                 case 168 /* TypePredicate */:
78565                 case 128 /* BooleanKeyword */:
78566                     return ts.createIdentifier("Boolean");
78567                 case 143 /* StringKeyword */:
78568                     return ts.createIdentifier("String");
78569                 case 141 /* ObjectKeyword */:
78570                     return ts.createIdentifier("Object");
78571                 case 187 /* LiteralType */:
78572                     switch (node.literal.kind) {
78573                         case 10 /* StringLiteral */:
78574                             return ts.createIdentifier("String");
78575                         case 207 /* PrefixUnaryExpression */:
78576                         case 8 /* NumericLiteral */:
78577                             return ts.createIdentifier("Number");
78578                         case 9 /* BigIntLiteral */:
78579                             return getGlobalBigIntNameWithFallback();
78580                         case 106 /* TrueKeyword */:
78581                         case 91 /* FalseKeyword */:
78582                             return ts.createIdentifier("Boolean");
78583                         default:
78584                             return ts.Debug.failBadSyntaxKind(node.literal);
78585                     }
78586                 case 140 /* NumberKeyword */:
78587                     return ts.createIdentifier("Number");
78588                 case 151 /* BigIntKeyword */:
78589                     return getGlobalBigIntNameWithFallback();
78590                 case 144 /* SymbolKeyword */:
78591                     return languageVersion < 2 /* ES2015 */
78592                         ? getGlobalSymbolNameWithFallback()
78593                         : ts.createIdentifier("Symbol");
78594                 case 169 /* TypeReference */:
78595                     return serializeTypeReferenceNode(node);
78596                 case 179 /* IntersectionType */:
78597                 case 178 /* UnionType */:
78598                     return serializeTypeList(node.types);
78599                 case 180 /* ConditionalType */:
78600                     return serializeTypeList([node.trueType, node.falseType]);
78601                 case 184 /* TypeOperator */:
78602                     if (node.operator === 138 /* ReadonlyKeyword */) {
78603                         return serializeTypeNode(node.type);
78604                     }
78605                     break;
78606                 case 172 /* TypeQuery */:
78607                 case 185 /* IndexedAccessType */:
78608                 case 186 /* MappedType */:
78609                 case 173 /* TypeLiteral */:
78610                 case 125 /* AnyKeyword */:
78611                 case 148 /* UnknownKeyword */:
78612                 case 183 /* ThisType */:
78613                 case 188 /* ImportType */:
78614                     break;
78615                 // handle JSDoc types from an invalid parse
78616                 case 295 /* JSDocAllType */:
78617                 case 296 /* JSDocUnknownType */:
78618                 case 300 /* JSDocFunctionType */:
78619                 case 301 /* JSDocVariadicType */:
78620                 case 302 /* JSDocNamepathType */:
78621                     break;
78622                 case 297 /* JSDocNullableType */:
78623                 case 298 /* JSDocNonNullableType */:
78624                 case 299 /* JSDocOptionalType */:
78625                     return serializeTypeNode(node.type);
78626                 default:
78627                     return ts.Debug.failBadSyntaxKind(node);
78628             }
78629             return ts.createIdentifier("Object");
78630         }
78631         function serializeTypeList(types) {
78632             // Note when updating logic here also update getEntityNameForDecoratorMetadata
78633             // so that aliases can be marked as referenced
78634             var serializedUnion;
78635             for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
78636                 var typeNode = types_21[_i];
78637                 while (typeNode.kind === 182 /* ParenthesizedType */) {
78638                     typeNode = typeNode.type; // Skip parens if need be
78639                 }
78640                 if (typeNode.kind === 137 /* NeverKeyword */) {
78641                     continue; // Always elide `never` from the union/intersection if possible
78642                 }
78643                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
78644                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
78645                 }
78646                 var serializedIndividual = serializeTypeNode(typeNode);
78647                 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
78648                     // One of the individual is global object, return immediately
78649                     return serializedIndividual;
78650                 }
78651                 // If there exists union that is not void 0 expression, check if the the common type is identifier.
78652                 // anything more complex and we will just default to Object
78653                 else if (serializedUnion) {
78654                     // Different types
78655                     if (!ts.isIdentifier(serializedUnion) ||
78656                         !ts.isIdentifier(serializedIndividual) ||
78657                         serializedUnion.escapedText !== serializedIndividual.escapedText) {
78658                         return ts.createIdentifier("Object");
78659                     }
78660                 }
78661                 else {
78662                     // Initialize the union type
78663                     serializedUnion = serializedIndividual;
78664                 }
78665             }
78666             // If we were able to find common type, use it
78667             return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
78668         }
78669         /**
78670          * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
78671          * decorator type metadata.
78672          *
78673          * @param node The type reference node.
78674          */
78675         function serializeTypeReferenceNode(node) {
78676             var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
78677             switch (kind) {
78678                 case ts.TypeReferenceSerializationKind.Unknown:
78679                     // From conditional type type reference that cannot be resolved is Similar to any or unknown
78680                     if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
78681                         return ts.createIdentifier("Object");
78682                     }
78683                     var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
78684                     var temp = ts.createTempVariable(hoistVariableDeclaration);
78685                     return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object"));
78686                 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
78687                     return serializeEntityNameAsExpression(node.typeName);
78688                 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
78689                     return ts.createVoidZero();
78690                 case ts.TypeReferenceSerializationKind.BigIntLikeType:
78691                     return getGlobalBigIntNameWithFallback();
78692                 case ts.TypeReferenceSerializationKind.BooleanType:
78693                     return ts.createIdentifier("Boolean");
78694                 case ts.TypeReferenceSerializationKind.NumberLikeType:
78695                     return ts.createIdentifier("Number");
78696                 case ts.TypeReferenceSerializationKind.StringLikeType:
78697                     return ts.createIdentifier("String");
78698                 case ts.TypeReferenceSerializationKind.ArrayLikeType:
78699                     return ts.createIdentifier("Array");
78700                 case ts.TypeReferenceSerializationKind.ESSymbolType:
78701                     return languageVersion < 2 /* ES2015 */
78702                         ? getGlobalSymbolNameWithFallback()
78703                         : ts.createIdentifier("Symbol");
78704                 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
78705                     return ts.createIdentifier("Function");
78706                 case ts.TypeReferenceSerializationKind.Promise:
78707                     return ts.createIdentifier("Promise");
78708                 case ts.TypeReferenceSerializationKind.ObjectType:
78709                     return ts.createIdentifier("Object");
78710                 default:
78711                     return ts.Debug.assertNever(kind);
78712             }
78713         }
78714         function createCheckedValue(left, right) {
78715             return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right);
78716         }
78717         /**
78718          * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
78719          *
78720          * @param node The entity name to serialize.
78721          */
78722         function serializeEntityNameAsExpressionFallback(node) {
78723             if (node.kind === 75 /* Identifier */) {
78724                 // A -> typeof A !== undefined && A
78725                 var copied = serializeEntityNameAsExpression(node);
78726                 return createCheckedValue(copied, copied);
78727             }
78728             if (node.left.kind === 75 /* Identifier */) {
78729                 // A.B -> typeof A !== undefined && A.B
78730                 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
78731             }
78732             // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
78733             var left = serializeEntityNameAsExpressionFallback(node.left);
78734             var temp = ts.createTempVariable(hoistVariableDeclaration);
78735             return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right));
78736         }
78737         /**
78738          * Serializes an entity name as an expression for decorator type metadata.
78739          *
78740          * @param node The entity name to serialize.
78741          */
78742         function serializeEntityNameAsExpression(node) {
78743             switch (node.kind) {
78744                 case 75 /* Identifier */:
78745                     // Create a clone of the name with a new parent, and treat it as if it were
78746                     // a source tree node for the purposes of the checker.
78747                     var name = ts.getMutableClone(node);
78748                     name.flags &= ~8 /* Synthesized */;
78749                     name.original = undefined;
78750                     name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node.
78751                     return name;
78752                 case 153 /* QualifiedName */:
78753                     return serializeQualifiedNameAsExpression(node);
78754             }
78755         }
78756         /**
78757          * Serializes an qualified name as an expression for decorator type metadata.
78758          *
78759          * @param node The qualified name to serialize.
78760          * @param useFallback A value indicating whether to use logical operators to test for the
78761          *                    qualified name at runtime.
78762          */
78763         function serializeQualifiedNameAsExpression(node) {
78764             return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right);
78765         }
78766         /**
78767          * Gets an expression that points to the global "Symbol" constructor at runtime if it is
78768          * available.
78769          */
78770         function getGlobalSymbolNameWithFallback() {
78771             return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object"));
78772         }
78773         /**
78774          * Gets an expression that points to the global "BigInt" constructor at runtime if it is
78775          * available.
78776          */
78777         function getGlobalBigIntNameWithFallback() {
78778             return languageVersion < 99 /* ESNext */
78779                 ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
78780                 : ts.createIdentifier("BigInt");
78781         }
78782         /**
78783          * Gets an expression that represents a property name (for decorated properties or enums).
78784          * For a computed property, a name is generated for the node.
78785          *
78786          * @param member The member whose name should be converted into an expression.
78787          */
78788         function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
78789             var name = member.name;
78790             if (ts.isPrivateIdentifier(name)) {
78791                 return ts.createIdentifier("");
78792             }
78793             else if (ts.isComputedPropertyName(name)) {
78794                 return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
78795                     ? ts.getGeneratedNameForNode(name)
78796                     : name.expression;
78797             }
78798             else if (ts.isIdentifier(name)) {
78799                 return ts.createLiteral(ts.idText(name));
78800             }
78801             else {
78802                 return ts.getSynthesizedClone(name);
78803             }
78804         }
78805         /**
78806          * Visits the property name of a class element, for use when emitting property
78807          * initializers. For a computed property on a node with decorators, a temporary
78808          * value is stored for later use.
78809          *
78810          * @param member The member whose name should be visited.
78811          */
78812         function visitPropertyNameOfClassElement(member) {
78813             var name = member.name;
78814             // Computed property names need to be transformed into a hoisted variable when they are used more than once.
78815             // The names are used more than once when:
78816             //   - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
78817             //   - the property has a decorator.
78818             if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
78819                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
78820                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
78821                 if (!ts.isSimpleInlineableExpression(innerExpression)) {
78822                     var generatedName = ts.getGeneratedNameForNode(name);
78823                     hoistVariableDeclaration(generatedName);
78824                     return ts.updateComputedPropertyName(name, ts.createAssignment(generatedName, expression));
78825                 }
78826             }
78827             return ts.visitNode(name, visitor, ts.isPropertyName);
78828         }
78829         /**
78830          * Transforms a HeritageClause with TypeScript syntax.
78831          *
78832          * This function will only be called when one of the following conditions are met:
78833          * - The node is a non-`extends` heritage clause that should be elided.
78834          * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
78835          *
78836          * @param node The HeritageClause to transform.
78837          */
78838         function visitHeritageClause(node) {
78839             if (node.token === 113 /* ImplementsKeyword */) {
78840                 // implements clauses are elided
78841                 return undefined;
78842             }
78843             return ts.visitEachChild(node, visitor, context);
78844         }
78845         /**
78846          * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
78847          *
78848          * This function will only be called when one of the following conditions are met:
78849          * - The node contains type arguments that should be elided.
78850          *
78851          * @param node The ExpressionWithTypeArguments to transform.
78852          */
78853         function visitExpressionWithTypeArguments(node) {
78854             return ts.updateExpressionWithTypeArguments(node, 
78855             /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
78856         }
78857         /**
78858          * Determines whether to emit a function-like declaration. We should not emit the
78859          * declaration if it does not have a body.
78860          *
78861          * @param node The declaration node.
78862          */
78863         function shouldEmitFunctionLikeDeclaration(node) {
78864             return !ts.nodeIsMissing(node.body);
78865         }
78866         function visitPropertyDeclaration(node) {
78867             if (node.flags & 8388608 /* Ambient */) {
78868                 return undefined;
78869             }
78870             var updated = ts.updateProperty(node, 
78871             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), 
78872             /*questionOrExclamationToken*/ undefined, 
78873             /*type*/ undefined, ts.visitNode(node.initializer, visitor));
78874             if (updated !== node) {
78875                 // While we emit the source map for the node after skipping decorators and modifiers,
78876                 // we need to emit the comments for the original range.
78877                 ts.setCommentRange(updated, node);
78878                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78879             }
78880             return updated;
78881         }
78882         function visitConstructor(node) {
78883             if (!shouldEmitFunctionLikeDeclaration(node)) {
78884                 return undefined;
78885             }
78886             return ts.updateConstructor(node, 
78887             /*decorators*/ undefined, 
78888             /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
78889         }
78890         function transformConstructorBody(body, constructor) {
78891             var parametersWithPropertyAssignments = constructor &&
78892                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
78893             if (!ts.some(parametersWithPropertyAssignments)) {
78894                 return ts.visitFunctionBody(body, visitor, context);
78895             }
78896             var statements = [];
78897             var indexOfFirstStatement = 0;
78898             resumeLexicalEnvironment();
78899             indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
78900             // Add parameters with property assignments. Transforms this:
78901             //
78902             //  constructor (public x, public y) {
78903             //  }
78904             //
78905             // Into this:
78906             //
78907             //  constructor (x, y) {
78908             //      this.x = x;
78909             //      this.y = y;
78910             //  }
78911             //
78912             ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
78913             // Add the existing statements, skipping the initial super call.
78914             ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
78915             // End the lexical environment.
78916             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
78917             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), body.statements), /*multiLine*/ true);
78918             ts.setTextRange(block, /*location*/ body);
78919             ts.setOriginalNode(block, body);
78920             return block;
78921         }
78922         /**
78923          * Transforms a parameter into a property assignment statement.
78924          *
78925          * @param node The parameter declaration.
78926          */
78927         function transformParameterWithPropertyAssignment(node) {
78928             var name = node.name;
78929             if (!ts.isIdentifier(name)) {
78930                 return undefined;
78931             }
78932             var propertyName = ts.getMutableClone(name);
78933             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
78934             var localName = ts.getMutableClone(name);
78935             ts.setEmitFlags(localName, 1536 /* NoComments */);
78936             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))));
78937         }
78938         function visitMethodDeclaration(node) {
78939             if (!shouldEmitFunctionLikeDeclaration(node)) {
78940                 return undefined;
78941             }
78942             var updated = ts.updateMethod(node, 
78943             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), 
78944             /*questionToken*/ undefined, 
78945             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
78946             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
78947             if (updated !== node) {
78948                 // While we emit the source map for the node after skipping decorators and modifiers,
78949                 // we need to emit the comments for the original range.
78950                 ts.setCommentRange(updated, node);
78951                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78952             }
78953             return updated;
78954         }
78955         /**
78956          * Determines whether to emit an accessor declaration. We should not emit the
78957          * declaration if it does not have a body and is abstract.
78958          *
78959          * @param node The declaration node.
78960          */
78961         function shouldEmitAccessorDeclaration(node) {
78962             return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
78963         }
78964         function visitGetAccessor(node) {
78965             if (!shouldEmitAccessorDeclaration(node)) {
78966                 return undefined;
78967             }
78968             var updated = ts.updateGetAccessor(node, 
78969             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), 
78970             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
78971             if (updated !== node) {
78972                 // While we emit the source map for the node after skipping decorators and modifiers,
78973                 // we need to emit the comments for the original range.
78974                 ts.setCommentRange(updated, node);
78975                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78976             }
78977             return updated;
78978         }
78979         function visitSetAccessor(node) {
78980             if (!shouldEmitAccessorDeclaration(node)) {
78981                 return undefined;
78982             }
78983             var updated = ts.updateSetAccessor(node, 
78984             /*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([]));
78985             if (updated !== node) {
78986                 // While we emit the source map for the node after skipping decorators and modifiers,
78987                 // we need to emit the comments for the original range.
78988                 ts.setCommentRange(updated, node);
78989                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78990             }
78991             return updated;
78992         }
78993         function visitFunctionDeclaration(node) {
78994             if (!shouldEmitFunctionLikeDeclaration(node)) {
78995                 return ts.createNotEmittedStatement(node);
78996             }
78997             var updated = ts.updateFunctionDeclaration(node, 
78998             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
78999             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79000             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
79001             if (isExportOfNamespace(node)) {
79002                 var statements = [updated];
79003                 addExportMemberAssignment(statements, node);
79004                 return statements;
79005             }
79006             return updated;
79007         }
79008         function visitFunctionExpression(node) {
79009             if (!shouldEmitFunctionLikeDeclaration(node)) {
79010                 return ts.createOmittedExpression();
79011             }
79012             var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
79013             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79014             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
79015             return updated;
79016         }
79017         function visitArrowFunction(node) {
79018             var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), 
79019             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79020             /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
79021             return updated;
79022         }
79023         function visitParameter(node) {
79024             if (ts.parameterIsThisKeyword(node)) {
79025                 return undefined;
79026             }
79027             var updated = ts.updateParameter(node, 
79028             /*decorators*/ undefined, 
79029             /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), 
79030             /*questionToken*/ undefined, 
79031             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79032             if (updated !== node) {
79033                 // While we emit the source map for the node after skipping decorators and modifiers,
79034                 // we need to emit the comments for the original range.
79035                 ts.setCommentRange(updated, node);
79036                 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
79037                 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
79038                 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
79039             }
79040             return updated;
79041         }
79042         function visitVariableStatement(node) {
79043             if (isExportOfNamespace(node)) {
79044                 var variables = ts.getInitializedVariables(node.declarationList);
79045                 if (variables.length === 0) {
79046                     // elide statement if there are no initialized variables.
79047                     return undefined;
79048                 }
79049                 return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
79050             }
79051             else {
79052                 return ts.visitEachChild(node, visitor, context);
79053             }
79054         }
79055         function transformInitializedVariable(node) {
79056             var name = node.name;
79057             if (ts.isBindingPattern(name)) {
79058                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
79059                 /*needsValue*/ false, createNamespaceExportExpression);
79060             }
79061             else {
79062                 return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), 
79063                 /*location*/ node);
79064             }
79065         }
79066         function visitVariableDeclaration(node) {
79067             return ts.updateTypeScriptVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), 
79068             /*exclaimationToken*/ undefined, 
79069             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79070         }
79071         function visitParenthesizedExpression(node) {
79072             var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */);
79073             if (ts.isAssertionExpression(innerExpression)) {
79074                 // Make sure we consider all nested cast expressions, e.g.:
79075                 // (<any><number><any>-A).x;
79076                 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79077                 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
79078                 // is really not desirable. We would like to emit the subexpression as-is. Omitting
79079                 // the parentheses, however, could cause change in the semantics of the generated
79080                 // code if the casted expression has a lower precedence than the rest of the
79081                 // expression.
79082                 //
79083                 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
79084                 // preserve the position information of the original expression.
79085                 //
79086                 // Due to the auto-parenthesization rules used by the visitor and factory functions
79087                 // we can safely elide the parentheses here, as a new synthetic
79088                 // ParenthesizedExpression will be inserted if we remove parentheses too
79089                 // aggressively.
79090                 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
79091                 // correctly for return and throw, we must keep the parenthesis
79092                 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
79093                     return ts.updateParen(node, expression);
79094                 }
79095                 return ts.createPartiallyEmittedExpression(expression, node);
79096             }
79097             return ts.visitEachChild(node, visitor, context);
79098         }
79099         function visitAssertionExpression(node) {
79100             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79101             return ts.createPartiallyEmittedExpression(expression, node);
79102         }
79103         function visitNonNullExpression(node) {
79104             var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
79105             return ts.createPartiallyEmittedExpression(expression, node);
79106         }
79107         function visitCallExpression(node) {
79108             return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79109             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79110         }
79111         function visitNewExpression(node) {
79112             return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79113             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79114         }
79115         function visitTaggedTemplateExpression(node) {
79116             return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), 
79117             /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
79118         }
79119         function visitJsxSelfClosingElement(node) {
79120             return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79121             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79122         }
79123         function visitJsxJsxOpeningElement(node) {
79124             return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79125             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79126         }
79127         /**
79128          * Determines whether to emit an enum declaration.
79129          *
79130          * @param node The enum declaration node.
79131          */
79132         function shouldEmitEnumDeclaration(node) {
79133             return !ts.isEnumConst(node)
79134                 || compilerOptions.preserveConstEnums
79135                 || compilerOptions.isolatedModules;
79136         }
79137         /**
79138          * Visits an enum declaration.
79139          *
79140          * This function will be called any time a TypeScript enum is encountered.
79141          *
79142          * @param node The enum declaration node.
79143          */
79144         function visitEnumDeclaration(node) {
79145             if (!shouldEmitEnumDeclaration(node)) {
79146                 return ts.createNotEmittedStatement(node);
79147             }
79148             var statements = [];
79149             // We request to be advised when the printer is about to print this node. This allows
79150             // us to set up the correct state for later substitutions.
79151             var emitFlags = 2 /* AdviseOnEmitNode */;
79152             // If needed, we should emit a variable declaration for the enum. If we emit
79153             // a leading variable declaration, we should not emit leading comments for the
79154             // enum body.
79155             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79156             if (varAdded) {
79157                 // We should still emit the comments if we are emitting a system module.
79158                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79159                     emitFlags |= 512 /* NoLeadingComments */;
79160                 }
79161             }
79162             // `parameterName` is the declaration name used inside of the enum.
79163             var parameterName = getNamespaceParameterName(node);
79164             // `containerName` is the expression used inside of the enum for assignments.
79165             var containerName = getNamespaceContainerName(node);
79166             // `exportName` is the expression used within this node's container for any exported references.
79167             var exportName = ts.hasModifier(node, 1 /* Export */)
79168                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79169                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79170             //  x || (x = {})
79171             //  exports.x || (exports.x = {})
79172             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79173             if (hasNamespaceQualifiedExportName(node)) {
79174                 // `localName` is the expression used within this node's containing scope for any local references.
79175                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79176                 //  x = (exports.x || (exports.x = {}))
79177                 moduleArg = ts.createAssignment(localName, moduleArg);
79178             }
79179             //  (function (x) {
79180             //      x[x["y"] = 0] = "y";
79181             //      ...
79182             //  })(x || (x = {}));
79183             var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79184             /*modifiers*/ undefined, 
79185             /*asteriskToken*/ undefined, 
79186             /*name*/ undefined, 
79187             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79188             /*type*/ undefined, transformEnumBody(node, containerName)), 
79189             /*typeArguments*/ undefined, [moduleArg]));
79190             ts.setOriginalNode(enumStatement, node);
79191             if (varAdded) {
79192                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79193                 ts.setSyntheticLeadingComments(enumStatement, undefined);
79194                 ts.setSyntheticTrailingComments(enumStatement, undefined);
79195             }
79196             ts.setTextRange(enumStatement, node);
79197             ts.addEmitFlags(enumStatement, emitFlags);
79198             statements.push(enumStatement);
79199             // Add a DeclarationMarker for the enum to preserve trailing comments and mark
79200             // the end of the declaration.
79201             statements.push(ts.createEndOfDeclarationMarker(node));
79202             return statements;
79203         }
79204         /**
79205          * Transforms the body of an enum declaration.
79206          *
79207          * @param node The enum declaration node.
79208          */
79209         function transformEnumBody(node, localName) {
79210             var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
79211             currentNamespaceContainerName = localName;
79212             var statements = [];
79213             startLexicalEnvironment();
79214             var members = ts.map(node.members, transformEnumMember);
79215             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79216             ts.addRange(statements, members);
79217             currentNamespaceContainerName = savedCurrentNamespaceLocalName;
79218             return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), 
79219             /*multiLine*/ true);
79220         }
79221         /**
79222          * Transforms an enum member into a statement.
79223          *
79224          * @param member The enum member node.
79225          */
79226         function transformEnumMember(member) {
79227             // enums don't support computed properties
79228             // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
79229             // old emitter always generate 'expression' part of the name as-is.
79230             var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
79231             var valueExpression = transformEnumMemberDeclarationValue(member);
79232             var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression);
79233             var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
79234                 innerAssignment :
79235                 ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name);
79236             return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
79237         }
79238         /**
79239          * Transforms the value of an enum member.
79240          *
79241          * @param member The enum member node.
79242          */
79243         function transformEnumMemberDeclarationValue(member) {
79244             var value = resolver.getConstantValue(member);
79245             if (value !== undefined) {
79246                 return ts.createLiteral(value);
79247             }
79248             else {
79249                 enableSubstitutionForNonQualifiedEnumMembers();
79250                 if (member.initializer) {
79251                     return ts.visitNode(member.initializer, visitor, ts.isExpression);
79252                 }
79253                 else {
79254                     return ts.createVoidZero();
79255                 }
79256             }
79257         }
79258         /**
79259          * Determines whether to elide a module declaration.
79260          *
79261          * @param node The module declaration node.
79262          */
79263         function shouldEmitModuleDeclaration(nodeIn) {
79264             var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
79265             if (!node) {
79266                 // If we can't find a parse tree node, assume the node is instantiated.
79267                 return true;
79268             }
79269             return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
79270         }
79271         /**
79272          * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
79273          * or `exports.x`).
79274          */
79275         function hasNamespaceQualifiedExportName(node) {
79276             return isExportOfNamespace(node)
79277                 || (isExternalModuleExport(node)
79278                     && moduleKind !== ts.ModuleKind.ES2015
79279                     && moduleKind !== ts.ModuleKind.ES2020
79280                     && moduleKind !== ts.ModuleKind.ESNext
79281                     && moduleKind !== ts.ModuleKind.System);
79282         }
79283         /**
79284          * Records that a declaration was emitted in the current scope, if it was the first
79285          * declaration for the provided symbol.
79286          */
79287         function recordEmittedDeclarationInScope(node) {
79288             if (!currentScopeFirstDeclarationsOfName) {
79289                 currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap();
79290             }
79291             var name = declaredNameInScope(node);
79292             if (!currentScopeFirstDeclarationsOfName.has(name)) {
79293                 currentScopeFirstDeclarationsOfName.set(name, node);
79294             }
79295         }
79296         /**
79297          * Determines whether a declaration is the first declaration with
79298          * the same name emitted in the current scope.
79299          */
79300         function isFirstEmittedDeclarationInScope(node) {
79301             if (currentScopeFirstDeclarationsOfName) {
79302                 var name = declaredNameInScope(node);
79303                 return currentScopeFirstDeclarationsOfName.get(name) === node;
79304             }
79305             return true;
79306         }
79307         function declaredNameInScope(node) {
79308             ts.Debug.assertNode(node.name, ts.isIdentifier);
79309             return node.name.escapedText;
79310         }
79311         /**
79312          * Adds a leading VariableStatement for a enum or module declaration.
79313          */
79314         function addVarForEnumOrModuleDeclaration(statements, node) {
79315             // Emit a variable statement for the module. We emit top-level enums as a `var`
79316             // declaration to avoid static errors in global scripts scripts due to redeclaration.
79317             // enums in any other scope are emitted as a `let` declaration.
79318             var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79319                 ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
79320             ], currentLexicalScope.kind === 290 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
79321             ts.setOriginalNode(statement, node);
79322             recordEmittedDeclarationInScope(node);
79323             if (isFirstEmittedDeclarationInScope(node)) {
79324                 // Adjust the source map emit to match the old emitter.
79325                 if (node.kind === 248 /* EnumDeclaration */) {
79326                     ts.setSourceMapRange(statement.declarationList, node);
79327                 }
79328                 else {
79329                     ts.setSourceMapRange(statement, node);
79330                 }
79331                 // Trailing comments for module declaration should be emitted after the function closure
79332                 // instead of the variable statement:
79333                 //
79334                 //     /** Module comment*/
79335                 //     module m1 {
79336                 //         function foo4Export() {
79337                 //         }
79338                 //     } // trailing comment module
79339                 //
79340                 // Should emit:
79341                 //
79342                 //     /** Module comment*/
79343                 //     var m1;
79344                 //     (function (m1) {
79345                 //         function foo4Export() {
79346                 //         }
79347                 //     })(m1 || (m1 = {})); // trailing comment module
79348                 //
79349                 ts.setCommentRange(statement, node);
79350                 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79351                 statements.push(statement);
79352                 return true;
79353             }
79354             else {
79355                 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
79356                 // declaration we do not emit a leading variable declaration. To preserve the
79357                 // begin/end semantics of the declararation and to properly handle exports
79358                 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
79359                 var mergeMarker = ts.createMergeDeclarationMarker(statement);
79360                 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79361                 statements.push(mergeMarker);
79362                 return false;
79363             }
79364         }
79365         /**
79366          * Visits a module declaration node.
79367          *
79368          * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
79369          *
79370          * @param node The module declaration node.
79371          */
79372         function visitModuleDeclaration(node) {
79373             if (!shouldEmitModuleDeclaration(node)) {
79374                 return ts.createNotEmittedStatement(node);
79375             }
79376             ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
79377             enableSubstitutionForNamespaceExports();
79378             var statements = [];
79379             // We request to be advised when the printer is about to print this node. This allows
79380             // us to set up the correct state for later substitutions.
79381             var emitFlags = 2 /* AdviseOnEmitNode */;
79382             // If needed, we should emit a variable declaration for the module. If we emit
79383             // a leading variable declaration, we should not emit leading comments for the
79384             // module body.
79385             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79386             if (varAdded) {
79387                 // We should still emit the comments if we are emitting a system module.
79388                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79389                     emitFlags |= 512 /* NoLeadingComments */;
79390                 }
79391             }
79392             // `parameterName` is the declaration name used inside of the namespace.
79393             var parameterName = getNamespaceParameterName(node);
79394             // `containerName` is the expression used inside of the namespace for exports.
79395             var containerName = getNamespaceContainerName(node);
79396             // `exportName` is the expression used within this node's container for any exported references.
79397             var exportName = ts.hasModifier(node, 1 /* Export */)
79398                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79399                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79400             //  x || (x = {})
79401             //  exports.x || (exports.x = {})
79402             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79403             if (hasNamespaceQualifiedExportName(node)) {
79404                 // `localName` is the expression used within this node's containing scope for any local references.
79405                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79406                 //  x = (exports.x || (exports.x = {}))
79407                 moduleArg = ts.createAssignment(localName, moduleArg);
79408             }
79409             //  (function (x_1) {
79410             //      x_1.y = ...;
79411             //  })(x || (x = {}));
79412             var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79413             /*modifiers*/ undefined, 
79414             /*asteriskToken*/ undefined, 
79415             /*name*/ undefined, 
79416             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79417             /*type*/ undefined, transformModuleBody(node, containerName)), 
79418             /*typeArguments*/ undefined, [moduleArg]));
79419             ts.setOriginalNode(moduleStatement, node);
79420             if (varAdded) {
79421                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79422                 ts.setSyntheticLeadingComments(moduleStatement, undefined);
79423                 ts.setSyntheticTrailingComments(moduleStatement, undefined);
79424             }
79425             ts.setTextRange(moduleStatement, node);
79426             ts.addEmitFlags(moduleStatement, emitFlags);
79427             statements.push(moduleStatement);
79428             // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
79429             // the end of the declaration.
79430             statements.push(ts.createEndOfDeclarationMarker(node));
79431             return statements;
79432         }
79433         /**
79434          * Transforms the body of a module declaration.
79435          *
79436          * @param node The module declaration node.
79437          */
79438         function transformModuleBody(node, namespaceLocalName) {
79439             var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
79440             var savedCurrentNamespace = currentNamespace;
79441             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
79442             currentNamespaceContainerName = namespaceLocalName;
79443             currentNamespace = node;
79444             currentScopeFirstDeclarationsOfName = undefined;
79445             var statements = [];
79446             startLexicalEnvironment();
79447             var statementsLocation;
79448             var blockLocation;
79449             if (node.body) {
79450                 if (node.body.kind === 250 /* ModuleBlock */) {
79451                     saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
79452                     statementsLocation = node.body.statements;
79453                     blockLocation = node.body;
79454                 }
79455                 else {
79456                     var result = visitModuleDeclaration(node.body);
79457                     if (result) {
79458                         if (ts.isArray(result)) {
79459                             ts.addRange(statements, result);
79460                         }
79461                         else {
79462                             statements.push(result);
79463                         }
79464                     }
79465                     var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
79466                     statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
79467                 }
79468             }
79469             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79470             currentNamespaceContainerName = savedCurrentNamespaceContainerName;
79471             currentNamespace = savedCurrentNamespace;
79472             currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
79473             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
79474             /*location*/ statementsLocation), 
79475             /*multiLine*/ true);
79476             ts.setTextRange(block, blockLocation);
79477             // namespace hello.hi.world {
79478             //      function foo() {}
79479             //
79480             //      // TODO, blah
79481             // }
79482             //
79483             // should be emitted as
79484             //
79485             // var hello;
79486             // (function (hello) {
79487             //     var hi;
79488             //     (function (hi) {
79489             //         var world;
79490             //         (function (world) {
79491             //             function foo() { }
79492             //             // TODO, blah
79493             //         })(world = hi.world || (hi.world = {}));
79494             //     })(hi = hello.hi || (hello.hi = {}));
79495             // })(hello || (hello = {}));
79496             // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
79497             if (!node.body || node.body.kind !== 250 /* ModuleBlock */) {
79498                 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
79499             }
79500             return block;
79501         }
79502         function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
79503             if (moduleDeclaration.body.kind === 249 /* ModuleDeclaration */) {
79504                 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
79505                 return recursiveInnerModule || moduleDeclaration.body;
79506             }
79507         }
79508         /**
79509          * Visits an import declaration, eliding it if it is not referenced and `importsNotUsedAsValues` is not 'preserve'.
79510          *
79511          * @param node The import declaration node.
79512          */
79513         function visitImportDeclaration(node) {
79514             if (!node.importClause) {
79515                 // Do not elide a side-effect only import declaration.
79516                 //  import "foo";
79517                 return node;
79518             }
79519             if (node.importClause.isTypeOnly) {
79520                 // Always elide type-only imports
79521                 return undefined;
79522             }
79523             // Elide the declaration if the import clause was elided.
79524             var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
79525             return importClause ||
79526                 compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
79527                 compilerOptions.importsNotUsedAsValues === 2 /* Error */
79528                 ? ts.updateImportDeclaration(node, 
79529                 /*decorators*/ undefined, 
79530                 /*modifiers*/ undefined, importClause, node.moduleSpecifier)
79531                 : undefined;
79532         }
79533         /**
79534          * Visits an import clause, eliding it if it is not referenced.
79535          *
79536          * @param node The import clause node.
79537          */
79538         function visitImportClause(node) {
79539             if (node.isTypeOnly) {
79540                 return undefined;
79541             }
79542             // Elide the import clause if we elide both its name and its named bindings.
79543             var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
79544             var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
79545             return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings, /*isTypeOnly*/ false) : undefined;
79546         }
79547         /**
79548          * Visits named import bindings, eliding it if it is not referenced.
79549          *
79550          * @param node The named import bindings node.
79551          */
79552         function visitNamedImportBindings(node) {
79553             if (node.kind === 256 /* NamespaceImport */) {
79554                 // Elide a namespace import if it is not referenced.
79555                 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79556             }
79557             else {
79558                 // Elide named imports if all of its import specifiers are elided.
79559                 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
79560                 return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined;
79561             }
79562         }
79563         /**
79564          * Visits an import specifier, eliding it if it is not referenced.
79565          *
79566          * @param node The import specifier node.
79567          */
79568         function visitImportSpecifier(node) {
79569             // Elide an import specifier if it is not referenced.
79570             return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79571         }
79572         /**
79573          * Visits an export assignment, eliding it if it does not contain a clause that resolves
79574          * to a value.
79575          *
79576          * @param node The export assignment node.
79577          */
79578         function visitExportAssignment(node) {
79579             // Elide the export assignment if it does not reference a value.
79580             return resolver.isValueAliasDeclaration(node)
79581                 ? ts.visitEachChild(node, visitor, context)
79582                 : undefined;
79583         }
79584         /**
79585          * Visits an export declaration, eliding it if it does not contain a clause that resolves
79586          * to a value.
79587          *
79588          * @param node The export declaration node.
79589          */
79590         function visitExportDeclaration(node) {
79591             if (node.isTypeOnly) {
79592                 return undefined;
79593             }
79594             if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
79595                 // never elide `export <whatever> from <whereever>` declarations -
79596                 // they should be kept for sideffects/untyped exports, even when the
79597                 // type checker doesn't know about any exports
79598                 return node;
79599             }
79600             if (!resolver.isValueAliasDeclaration(node)) {
79601                 // Elide the export declaration if it does not export a value.
79602                 return undefined;
79603             }
79604             // Elide the export declaration if all of its named exports are elided.
79605             var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedExportBindings);
79606             return exportClause
79607                 ? ts.updateExportDeclaration(node, 
79608                 /*decorators*/ undefined, 
79609                 /*modifiers*/ undefined, exportClause, node.moduleSpecifier, node.isTypeOnly)
79610                 : undefined;
79611         }
79612         /**
79613          * Visits named exports, eliding it if it does not contain an export specifier that
79614          * resolves to a value.
79615          *
79616          * @param node The named exports node.
79617          */
79618         function visitNamedExports(node) {
79619             // Elide the named exports if all of its export specifiers were elided.
79620             var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
79621             return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined;
79622         }
79623         function visitNamespaceExports(node) {
79624             return ts.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
79625         }
79626         function visitNamedExportBindings(node) {
79627             return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
79628         }
79629         /**
79630          * Visits an export specifier, eliding it if it does not resolve to a value.
79631          *
79632          * @param node The export specifier node.
79633          */
79634         function visitExportSpecifier(node) {
79635             // Elide an export specifier if it does not reference a value.
79636             return resolver.isValueAliasDeclaration(node) ? node : undefined;
79637         }
79638         /**
79639          * Determines whether to emit an import equals declaration.
79640          *
79641          * @param node The import equals declaration node.
79642          */
79643         function shouldEmitImportEqualsDeclaration(node) {
79644             // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
79645             // - current file is not external module
79646             // - import declaration is top level and target is value imported by entity name
79647             return resolver.isReferencedAliasDeclaration(node)
79648                 || (!ts.isExternalModule(currentSourceFile)
79649                     && resolver.isTopLevelValueImportEqualsWithEntityName(node));
79650         }
79651         /**
79652          * Visits an import equals declaration.
79653          *
79654          * @param node The import equals declaration node.
79655          */
79656         function visitImportEqualsDeclaration(node) {
79657             if (ts.isExternalModuleImportEqualsDeclaration(node)) {
79658                 var isReferenced = resolver.isReferencedAliasDeclaration(node);
79659                 // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
79660                 if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
79661                     return ts.setOriginalNode(ts.setTextRange(ts.createImportDeclaration(
79662                     /*decorators*/ undefined, 
79663                     /*modifiers*/ undefined, 
79664                     /*importClause*/ undefined, node.moduleReference.expression), node), node);
79665                 }
79666                 return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
79667             }
79668             if (!shouldEmitImportEqualsDeclaration(node)) {
79669                 return undefined;
79670             }
79671             var moduleReference = ts.createExpressionFromEntityName(node.moduleReference);
79672             ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
79673             if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
79674                 //  export var ${name} = ${moduleReference};
79675                 //  var ${name} = ${moduleReference};
79676                 return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79677                     ts.setOriginalNode(ts.createVariableDeclaration(node.name, 
79678                     /*type*/ undefined, moduleReference), node)
79679                 ])), node), node);
79680             }
79681             else {
79682                 // exports.${name} = ${moduleReference};
79683                 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
79684             }
79685         }
79686         /**
79687          * Gets a value indicating whether the node is exported from a namespace.
79688          *
79689          * @param node The node to test.
79690          */
79691         function isExportOfNamespace(node) {
79692             return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */);
79693         }
79694         /**
79695          * Gets a value indicating whether the node is exported from an external module.
79696          *
79697          * @param node The node to test.
79698          */
79699         function isExternalModuleExport(node) {
79700             return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */);
79701         }
79702         /**
79703          * Gets a value indicating whether the node is a named export from an external module.
79704          *
79705          * @param node The node to test.
79706          */
79707         function isNamedExternalModuleExport(node) {
79708             return isExternalModuleExport(node)
79709                 && !ts.hasModifier(node, 512 /* Default */);
79710         }
79711         /**
79712          * Gets a value indicating whether the node is the default export of an external module.
79713          *
79714          * @param node The node to test.
79715          */
79716         function isDefaultExternalModuleExport(node) {
79717             return isExternalModuleExport(node)
79718                 && ts.hasModifier(node, 512 /* Default */);
79719         }
79720         /**
79721          * Creates a statement for the provided expression. This is used in calls to `map`.
79722          */
79723         function expressionToStatement(expression) {
79724             return ts.createExpressionStatement(expression);
79725         }
79726         function addExportMemberAssignment(statements, node) {
79727             var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node));
79728             ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
79729             var statement = ts.createExpressionStatement(expression);
79730             ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
79731             statements.push(statement);
79732         }
79733         function createNamespaceExport(exportName, exportValue, location) {
79734             return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
79735         }
79736         function createNamespaceExportExpression(exportName, exportValue, location) {
79737             return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
79738         }
79739         function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
79740             return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
79741         }
79742         /**
79743          * Gets the declaration name used inside of a namespace or enum.
79744          */
79745         function getNamespaceParameterName(node) {
79746             var name = ts.getGeneratedNameForNode(node);
79747             ts.setSourceMapRange(name, node.name);
79748             return name;
79749         }
79750         /**
79751          * Gets the expression used to refer to a namespace or enum within the body
79752          * of its declaration.
79753          */
79754         function getNamespaceContainerName(node) {
79755             return ts.getGeneratedNameForNode(node);
79756         }
79757         /**
79758          * Gets a local alias for a class declaration if it is a decorated class with an internal
79759          * reference to the static side of the class. This is necessary to avoid issues with
79760          * double-binding semantics for the class name.
79761          */
79762         function getClassAliasIfNeeded(node) {
79763             if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
79764                 enableSubstitutionForClassAliases();
79765                 var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
79766                 classAliases[ts.getOriginalNodeId(node)] = classAlias;
79767                 hoistVariableDeclaration(classAlias);
79768                 return classAlias;
79769             }
79770         }
79771         function getClassPrototype(node) {
79772             return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype");
79773         }
79774         function getClassMemberPrefix(node, member) {
79775             return ts.hasModifier(member, 32 /* Static */)
79776                 ? ts.getDeclarationName(node)
79777                 : getClassPrototype(node);
79778         }
79779         function enableSubstitutionForNonQualifiedEnumMembers() {
79780             if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
79781                 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79782                 context.enableSubstitution(75 /* Identifier */);
79783             }
79784         }
79785         function enableSubstitutionForClassAliases() {
79786             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
79787                 enabledSubstitutions |= 1 /* ClassAliases */;
79788                 // We need to enable substitutions for identifiers. This allows us to
79789                 // substitute class names inside of a class declaration.
79790                 context.enableSubstitution(75 /* Identifier */);
79791                 // Keep track of class aliases.
79792                 classAliases = [];
79793             }
79794         }
79795         function enableSubstitutionForNamespaceExports() {
79796             if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
79797                 enabledSubstitutions |= 2 /* NamespaceExports */;
79798                 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
79799                 // substitute the names of exported members of a namespace.
79800                 context.enableSubstitution(75 /* Identifier */);
79801                 context.enableSubstitution(282 /* ShorthandPropertyAssignment */);
79802                 // We need to be notified when entering and exiting namespaces.
79803                 context.enableEmitNotification(249 /* ModuleDeclaration */);
79804             }
79805         }
79806         function isTransformedModuleDeclaration(node) {
79807             return ts.getOriginalNode(node).kind === 249 /* ModuleDeclaration */;
79808         }
79809         function isTransformedEnumDeclaration(node) {
79810             return ts.getOriginalNode(node).kind === 248 /* EnumDeclaration */;
79811         }
79812         /**
79813          * Hook for node emit.
79814          *
79815          * @param hint A hint as to the intended usage of the node.
79816          * @param node The node to emit.
79817          * @param emit A callback used to emit the node in the printer.
79818          */
79819         function onEmitNode(hint, node, emitCallback) {
79820             var savedApplicableSubstitutions = applicableSubstitutions;
79821             var savedCurrentSourceFile = currentSourceFile;
79822             if (ts.isSourceFile(node)) {
79823                 currentSourceFile = node;
79824             }
79825             if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
79826                 applicableSubstitutions |= 2 /* NamespaceExports */;
79827             }
79828             if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
79829                 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79830             }
79831             previousOnEmitNode(hint, node, emitCallback);
79832             applicableSubstitutions = savedApplicableSubstitutions;
79833             currentSourceFile = savedCurrentSourceFile;
79834         }
79835         /**
79836          * Hooks node substitutions.
79837          *
79838          * @param hint A hint as to the intended usage of the node.
79839          * @param node The node to substitute.
79840          */
79841         function onSubstituteNode(hint, node) {
79842             node = previousOnSubstituteNode(hint, node);
79843             if (hint === 1 /* Expression */) {
79844                 return substituteExpression(node);
79845             }
79846             else if (ts.isShorthandPropertyAssignment(node)) {
79847                 return substituteShorthandPropertyAssignment(node);
79848             }
79849             return node;
79850         }
79851         function substituteShorthandPropertyAssignment(node) {
79852             if (enabledSubstitutions & 2 /* NamespaceExports */) {
79853                 var name = node.name;
79854                 var exportedName = trySubstituteNamespaceExportedName(name);
79855                 if (exportedName) {
79856                     // A shorthand property with an assignment initializer is probably part of a
79857                     // destructuring assignment
79858                     if (node.objectAssignmentInitializer) {
79859                         var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
79860                         return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
79861                     }
79862                     return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node);
79863                 }
79864             }
79865             return node;
79866         }
79867         function substituteExpression(node) {
79868             switch (node.kind) {
79869                 case 75 /* Identifier */:
79870                     return substituteExpressionIdentifier(node);
79871                 case 194 /* PropertyAccessExpression */:
79872                     return substitutePropertyAccessExpression(node);
79873                 case 195 /* ElementAccessExpression */:
79874                     return substituteElementAccessExpression(node);
79875             }
79876             return node;
79877         }
79878         function substituteExpressionIdentifier(node) {
79879             return trySubstituteClassAlias(node)
79880                 || trySubstituteNamespaceExportedName(node)
79881                 || node;
79882         }
79883         function trySubstituteClassAlias(node) {
79884             if (enabledSubstitutions & 1 /* ClassAliases */) {
79885                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
79886                     // Due to the emit for class decorators, any reference to the class from inside of the class body
79887                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
79888                     // behavior of class names in ES6.
79889                     // Also, when emitting statics for class expressions, we must substitute a class alias for
79890                     // constructor references in static property initializers.
79891                     var declaration = resolver.getReferencedValueDeclaration(node);
79892                     if (declaration) {
79893                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
79894                         if (classAlias) {
79895                             var clone_1 = ts.getSynthesizedClone(classAlias);
79896                             ts.setSourceMapRange(clone_1, node);
79897                             ts.setCommentRange(clone_1, node);
79898                             return clone_1;
79899                         }
79900                     }
79901                 }
79902             }
79903             return undefined;
79904         }
79905         function trySubstituteNamespaceExportedName(node) {
79906             // If this is explicitly a local name, do not substitute.
79907             if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
79908                 // If we are nested within a namespace declaration, we may need to qualifiy
79909                 // an identifier that is exported from a merged namespace.
79910                 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
79911                 if (container && container.kind !== 290 /* SourceFile */) {
79912                     var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 249 /* ModuleDeclaration */) ||
79913                         (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 248 /* EnumDeclaration */);
79914                     if (substitute) {
79915                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), 
79916                         /*location*/ node);
79917                     }
79918                 }
79919             }
79920             return undefined;
79921         }
79922         function substitutePropertyAccessExpression(node) {
79923             return substituteConstantValue(node);
79924         }
79925         function substituteElementAccessExpression(node) {
79926             return substituteConstantValue(node);
79927         }
79928         function substituteConstantValue(node) {
79929             var constantValue = tryGetConstEnumValue(node);
79930             if (constantValue !== undefined) {
79931                 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
79932                 ts.setConstantValue(node, constantValue);
79933                 var substitute = ts.createLiteral(constantValue);
79934                 if (!compilerOptions.removeComments) {
79935                     var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
79936                     var propertyName = ts.isPropertyAccessExpression(originalNode)
79937                         ? ts.declarationNameToString(originalNode.name)
79938                         : ts.getTextOfNode(originalNode.argumentExpression);
79939                     ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
79940                 }
79941                 return substitute;
79942             }
79943             return node;
79944         }
79945         function tryGetConstEnumValue(node) {
79946             if (compilerOptions.isolatedModules) {
79947                 return undefined;
79948             }
79949             return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
79950         }
79951     }
79952     ts.transformTypeScript = transformTypeScript;
79953     function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) {
79954         var argumentsArray = [];
79955         argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true));
79956         argumentsArray.push(target);
79957         if (memberName) {
79958             argumentsArray.push(memberName);
79959             if (descriptor) {
79960                 argumentsArray.push(descriptor);
79961             }
79962         }
79963         context.requestEmitHelper(ts.decorateHelper);
79964         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__decorate"), 
79965         /*typeArguments*/ undefined, argumentsArray), location);
79966     }
79967     ts.decorateHelper = {
79968         name: "typescript:decorate",
79969         importName: "__decorate",
79970         scoped: false,
79971         priority: 2,
79972         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            };"
79973     };
79974     function createMetadataHelper(context, metadataKey, metadataValue) {
79975         context.requestEmitHelper(ts.metadataHelper);
79976         return ts.createCall(ts.getUnscopedHelperName("__metadata"), 
79977         /*typeArguments*/ undefined, [
79978             ts.createLiteral(metadataKey),
79979             metadataValue
79980         ]);
79981     }
79982     ts.metadataHelper = {
79983         name: "typescript:metadata",
79984         importName: "__metadata",
79985         scoped: false,
79986         priority: 3,
79987         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            };"
79988     };
79989     function createParamHelper(context, expression, parameterOffset, location) {
79990         context.requestEmitHelper(ts.paramHelper);
79991         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__param"), 
79992         /*typeArguments*/ undefined, [
79993             ts.createLiteral(parameterOffset),
79994             expression
79995         ]), location);
79996     }
79997     ts.paramHelper = {
79998         name: "typescript:param",
79999         importName: "__param",
80000         scoped: false,
80001         priority: 4,
80002         text: "\n            var __param = (this && this.__param) || function (paramIndex, decorator) {\n                return function (target, key) { decorator(target, key, paramIndex); }\n            };"
80003     };
80004 })(ts || (ts = {}));
80005 /*@internal*/
80006 var ts;
80007 (function (ts) {
80008     var ClassPropertySubstitutionFlags;
80009     (function (ClassPropertySubstitutionFlags) {
80010         /**
80011          * Enables substitutions for class expressions with static fields
80012          * which have initializers that reference the class name.
80013          */
80014         ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
80015     })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
80016     var PrivateIdentifierPlacement;
80017     (function (PrivateIdentifierPlacement) {
80018         PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField";
80019     })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {}));
80020     /**
80021      * Transforms ECMAScript Class Syntax.
80022      * TypeScript parameter property syntax is transformed in the TypeScript transformer.
80023      * For now, this transforms public field declarations using TypeScript class semantics,
80024      * where declarations are elided and initializers are transformed as assignments in the constructor.
80025      * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
80026      */
80027     function transformClassFields(context) {
80028         var hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment;
80029         var resolver = context.getEmitResolver();
80030         var compilerOptions = context.getCompilerOptions();
80031         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80032         var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */;
80033         var previousOnSubstituteNode = context.onSubstituteNode;
80034         context.onSubstituteNode = onSubstituteNode;
80035         var enabledSubstitutions;
80036         var classAliases;
80037         /**
80038          * Tracks what computed name expressions originating from elided names must be inlined
80039          * at the next execution site, in document order
80040          */
80041         var pendingExpressions;
80042         /**
80043          * Tracks what computed name expression statements and static property initializers must be
80044          * emitted at the next execution site, in document order (for decorated classes).
80045          */
80046         var pendingStatements;
80047         var privateIdentifierEnvironmentStack = [];
80048         var currentPrivateIdentifierEnvironment;
80049         return ts.chainBundle(transformSourceFile);
80050         function transformSourceFile(node) {
80051             var options = context.getCompilerOptions();
80052             if (node.isDeclarationFile
80053                 || options.useDefineForClassFields && options.target === 99 /* ESNext */) {
80054                 return node;
80055             }
80056             var visited = ts.visitEachChild(node, visitor, context);
80057             ts.addEmitHelpers(visited, context.readEmitHelpers());
80058             return visited;
80059         }
80060         function visitor(node) {
80061             if (!(node.transformFlags & 4194304 /* ContainsClassFields */))
80062                 return node;
80063             switch (node.kind) {
80064                 case 214 /* ClassExpression */:
80065                 case 245 /* ClassDeclaration */:
80066                     return visitClassLike(node);
80067                 case 159 /* PropertyDeclaration */:
80068                     return visitPropertyDeclaration(node);
80069                 case 225 /* VariableStatement */:
80070                     return visitVariableStatement(node);
80071                 case 154 /* ComputedPropertyName */:
80072                     return visitComputedPropertyName(node);
80073                 case 194 /* PropertyAccessExpression */:
80074                     return visitPropertyAccessExpression(node);
80075                 case 207 /* PrefixUnaryExpression */:
80076                     return visitPrefixUnaryExpression(node);
80077                 case 208 /* PostfixUnaryExpression */:
80078                     return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false);
80079                 case 196 /* CallExpression */:
80080                     return visitCallExpression(node);
80081                 case 209 /* BinaryExpression */:
80082                     return visitBinaryExpression(node);
80083                 case 76 /* PrivateIdentifier */:
80084                     return visitPrivateIdentifier(node);
80085                 case 226 /* ExpressionStatement */:
80086                     return visitExpressionStatement(node);
80087                 case 230 /* ForStatement */:
80088                     return visitForStatement(node);
80089                 case 198 /* TaggedTemplateExpression */:
80090                     return visitTaggedTemplateExpression(node);
80091             }
80092             return ts.visitEachChild(node, visitor, context);
80093         }
80094         function visitorDestructuringTarget(node) {
80095             switch (node.kind) {
80096                 case 193 /* ObjectLiteralExpression */:
80097                 case 192 /* ArrayLiteralExpression */:
80098                     return visitAssignmentPattern(node);
80099                 default:
80100                     return visitor(node);
80101             }
80102         }
80103         /**
80104          * If we visit a private name, this means it is an undeclared private name.
80105          * Replace it with an empty identifier to indicate a problem with the code.
80106          */
80107         function visitPrivateIdentifier(node) {
80108             if (!shouldTransformPrivateFields) {
80109                 return node;
80110             }
80111             return ts.setOriginalNode(ts.createIdentifier(""), node);
80112         }
80113         /**
80114          * Visits the members of a class that has fields.
80115          *
80116          * @param node The node to visit.
80117          */
80118         function classElementVisitor(node) {
80119             switch (node.kind) {
80120                 case 162 /* Constructor */:
80121                     // Constructors for classes using class fields are transformed in
80122                     // `visitClassDeclaration` or `visitClassExpression`.
80123                     return undefined;
80124                 case 163 /* GetAccessor */:
80125                 case 164 /* SetAccessor */:
80126                 case 161 /* MethodDeclaration */:
80127                     // Visit the name of the member (if it's a computed property name).
80128                     return ts.visitEachChild(node, classElementVisitor, context);
80129                 case 159 /* PropertyDeclaration */:
80130                     return visitPropertyDeclaration(node);
80131                 case 154 /* ComputedPropertyName */:
80132                     return visitComputedPropertyName(node);
80133                 case 222 /* SemicolonClassElement */:
80134                     return node;
80135                 default:
80136                     return visitor(node);
80137             }
80138         }
80139         function visitVariableStatement(node) {
80140             var savedPendingStatements = pendingStatements;
80141             pendingStatements = [];
80142             var visitedNode = ts.visitEachChild(node, visitor, context);
80143             var statement = ts.some(pendingStatements) ? __spreadArrays([visitedNode], pendingStatements) :
80144                 visitedNode;
80145             pendingStatements = savedPendingStatements;
80146             return statement;
80147         }
80148         function visitComputedPropertyName(name) {
80149             var node = ts.visitEachChild(name, visitor, context);
80150             if (ts.some(pendingExpressions)) {
80151                 var expressions = pendingExpressions;
80152                 expressions.push(name.expression);
80153                 pendingExpressions = [];
80154                 node = ts.updateComputedPropertyName(node, ts.inlineExpressions(expressions));
80155             }
80156             return node;
80157         }
80158         function visitPropertyDeclaration(node) {
80159             ts.Debug.assert(!ts.some(node.decorators));
80160             if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80161                 // Initializer is elided as the field is initialized in transformConstructor.
80162                 return ts.updateProperty(node, 
80163                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, 
80164                 /*questionOrExclamationToken*/ undefined, 
80165                 /*type*/ undefined, 
80166                 /*initializer*/ undefined);
80167             }
80168             // Create a temporary variable to store a computed property name (if necessary).
80169             // If it's not inlineable, then we emit an expression after the class which assigns
80170             // the property name to the temporary variable.
80171             var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
80172             if (expr && !ts.isSimpleInlineableExpression(expr)) {
80173                 (pendingExpressions || (pendingExpressions = [])).push(expr);
80174             }
80175             return undefined;
80176         }
80177         function createPrivateIdentifierAccess(info, receiver) {
80178             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80179             switch (info.placement) {
80180                 case 0 /* InstanceField */:
80181                     return createClassPrivateFieldGetHelper(context, ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver), info.weakMapName);
80182                 default: return ts.Debug.fail("Unexpected private identifier placement");
80183             }
80184         }
80185         function visitPropertyAccessExpression(node) {
80186             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80187                 var privateIdentifierInfo = accessPrivateIdentifier(node.name);
80188                 if (privateIdentifierInfo) {
80189                     return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node);
80190                 }
80191             }
80192             return ts.visitEachChild(node, visitor, context);
80193         }
80194         function visitPrefixUnaryExpression(node) {
80195             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80196                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80197                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80198                     40 /* MinusToken */ : undefined;
80199                 var info = void 0;
80200                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80201                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80202                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80203                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80204                     return ts.setOriginalNode(createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */), node);
80205                 }
80206             }
80207             return ts.visitEachChild(node, visitor, context);
80208         }
80209         function visitPostfixUnaryExpression(node, valueIsDiscarded) {
80210             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80211                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80212                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80213                     40 /* MinusToken */ : undefined;
80214                 var info = void 0;
80215                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80216                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80217                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80218                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80219                     // Create a temporary variable to store the value returned by the expression.
80220                     var returnValue = valueIsDiscarded ? undefined : ts.createTempVariable(hoistVariableDeclaration);
80221                     return ts.setOriginalNode(ts.inlineExpressions(ts.compact([
80222                         createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(returnValue ? ts.createAssignment(returnValue, existingValue) : existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */),
80223                         returnValue
80224                     ])), node);
80225                 }
80226             }
80227             return ts.visitEachChild(node, visitor, context);
80228         }
80229         function visitForStatement(node) {
80230             if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) {
80231                 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));
80232             }
80233             return ts.visitEachChild(node, visitor, context);
80234         }
80235         function visitExpressionStatement(node) {
80236             if (ts.isPostfixUnaryExpression(node.expression)) {
80237                 return ts.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
80238             }
80239             return ts.visitEachChild(node, visitor, context);
80240         }
80241         function createCopiableReceiverExpr(receiver) {
80242             var clone = ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver);
80243             if (ts.isSimpleInlineableExpression(receiver)) {
80244                 return { readExpression: clone, initializeExpression: undefined };
80245             }
80246             var readExpression = ts.createTempVariable(hoistVariableDeclaration);
80247             var initializeExpression = ts.createAssignment(readExpression, clone);
80248             return { readExpression: readExpression, initializeExpression: initializeExpression };
80249         }
80250         function visitCallExpression(node) {
80251             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
80252                 // Transform call expressions of private names to properly bind the `this` parameter.
80253                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80254                 return ts.updateCall(node, ts.createPropertyAccess(ts.visitNode(target, visitor), "call"), 
80255                 /*typeArguments*/ undefined, __spreadArrays([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
80256             }
80257             return ts.visitEachChild(node, visitor, context);
80258         }
80259         function visitTaggedTemplateExpression(node) {
80260             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
80261                 // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
80262                 var _a = ts.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80263                 return ts.updateTaggedTemplate(node, ts.createCall(ts.createPropertyAccess(ts.visitNode(target, visitor), "bind"), 
80264                 /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
80265             }
80266             return ts.visitEachChild(node, visitor, context);
80267         }
80268         function visitBinaryExpression(node) {
80269             if (shouldTransformPrivateFields) {
80270                 if (ts.isDestructuringAssignment(node)) {
80271                     var savedPendingExpressions = pendingExpressions;
80272                     pendingExpressions = undefined;
80273                     node = ts.updateBinary(node, ts.visitNode(node.left, visitorDestructuringTarget), ts.visitNode(node.right, visitor), node.operatorToken);
80274                     var expr = ts.some(pendingExpressions) ?
80275                         ts.inlineExpressions(ts.compact(__spreadArrays(pendingExpressions, [node]))) :
80276                         node;
80277                     pendingExpressions = savedPendingExpressions;
80278                     return expr;
80279                 }
80280                 if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
80281                     var info = accessPrivateIdentifier(node.left.name);
80282                     if (info) {
80283                         return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node);
80284                     }
80285                 }
80286             }
80287             return ts.visitEachChild(node, visitor, context);
80288         }
80289         function createPrivateIdentifierAssignment(info, receiver, right, operator) {
80290             switch (info.placement) {
80291                 case 0 /* InstanceField */: {
80292                     return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator);
80293                 }
80294                 default: return ts.Debug.fail("Unexpected private identifier placement");
80295             }
80296         }
80297         function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) {
80298             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80299             right = ts.visitNode(right, visitor, ts.isExpression);
80300             if (ts.isCompoundAssignment(operator)) {
80301                 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80302                 return createClassPrivateFieldSetHelper(context, initializeExpression || readExpression, info.weakMapName, ts.createBinary(createClassPrivateFieldGetHelper(context, readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right));
80303             }
80304             else {
80305                 return createClassPrivateFieldSetHelper(context, receiver, info.weakMapName, right);
80306             }
80307         }
80308         /**
80309          * Set up the environment for a class.
80310          */
80311         function visitClassLike(node) {
80312             var savedPendingExpressions = pendingExpressions;
80313             pendingExpressions = undefined;
80314             if (shouldTransformPrivateFields) {
80315                 startPrivateIdentifierEnvironment();
80316             }
80317             var result = ts.isClassDeclaration(node) ?
80318                 visitClassDeclaration(node) :
80319                 visitClassExpression(node);
80320             if (shouldTransformPrivateFields) {
80321                 endPrivateIdentifierEnvironment();
80322             }
80323             pendingExpressions = savedPendingExpressions;
80324             return result;
80325         }
80326         function doesClassElementNeedTransform(node) {
80327             return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name));
80328         }
80329         function visitClassDeclaration(node) {
80330             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80331                 return ts.visitEachChild(node, visitor, context);
80332             }
80333             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80334             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80335             var statements = [
80336                 ts.updateClassDeclaration(node, 
80337                 /*decorators*/ undefined, node.modifiers, node.name, 
80338                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
80339             ];
80340             // Write any pending expressions from elided or moved computed property names
80341             if (ts.some(pendingExpressions)) {
80342                 statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80343             }
80344             // Emit static property assignment. Because classDeclaration is lexically evaluated,
80345             // it is safe to emit static property assignment after classDeclaration
80346             // From ES6 specification:
80347             //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
80348             //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
80349             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80350             if (ts.some(staticProperties)) {
80351                 addPropertyStatements(statements, staticProperties, ts.getInternalName(node));
80352             }
80353             return statements;
80354         }
80355         function visitClassExpression(node) {
80356             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80357                 return ts.visitEachChild(node, visitor, context);
80358             }
80359             // If this class expression is a transformation of a decorated class declaration,
80360             // then we want to output the pendingExpressions as statements, not as inlined
80361             // expressions with the class statement.
80362             //
80363             // In this case, we use pendingStatements to produce the same output as the
80364             // class declaration transformation. The VariableStatement visitor will insert
80365             // these statements after the class expression variable statement.
80366             var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node));
80367             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80368             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80369             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80370             var classExpression = ts.updateClassExpression(node, node.modifiers, node.name, 
80371             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
80372             if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
80373                 if (isDecoratedClassDeclaration) {
80374                     ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
80375                     // Write any pending expressions from elided or moved computed property names
80376                     if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
80377                         pendingStatements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80378                     }
80379                     if (pendingStatements && ts.some(staticProperties)) {
80380                         addPropertyStatements(pendingStatements, staticProperties, ts.getInternalName(node));
80381                     }
80382                     return classExpression;
80383                 }
80384                 else {
80385                     var expressions = [];
80386                     var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
80387                     var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
80388                     if (isClassWithConstructorReference) {
80389                         // record an alias as the class name is not in scope for statics.
80390                         enableSubstitutionForClassAliases();
80391                         var alias = ts.getSynthesizedClone(temp);
80392                         alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
80393                         classAliases[ts.getOriginalNodeId(node)] = alias;
80394                     }
80395                     // To preserve the behavior of the old emitter, we explicitly indent
80396                     // the body of a class with static initializers.
80397                     ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
80398                     expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression)));
80399                     // Add any pending expressions leftover from elided or relocated computed property names
80400                     ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
80401                     ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
80402                     expressions.push(ts.startOnNewLine(temp));
80403                     return ts.inlineExpressions(expressions);
80404                 }
80405             }
80406             return classExpression;
80407         }
80408         function transformClassMembers(node, isDerivedClass) {
80409             if (shouldTransformPrivateFields) {
80410                 // Declare private names.
80411                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
80412                     var member = _a[_i];
80413                     if (ts.isPrivateIdentifierPropertyDeclaration(member)) {
80414                         addPrivateIdentifierToEnvironment(member.name);
80415                     }
80416                 }
80417             }
80418             var members = [];
80419             var constructor = transformConstructor(node, isDerivedClass);
80420             if (constructor) {
80421                 members.push(constructor);
80422             }
80423             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
80424             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
80425         }
80426         function isPropertyDeclarationThatRequiresConstructorStatement(member) {
80427             if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member)) {
80428                 return false;
80429             }
80430             if (context.getCompilerOptions().useDefineForClassFields) {
80431                 // If we are using define semantics and targeting ESNext or higher,
80432                 // then we don't need to transform any class properties.
80433                 return languageVersion < 99 /* ESNext */;
80434             }
80435             return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member);
80436         }
80437         function transformConstructor(node, isDerivedClass) {
80438             var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
80439             var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement);
80440             if (!ts.some(properties)) {
80441                 return constructor;
80442             }
80443             var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
80444             var body = transformConstructorBody(node, constructor, isDerivedClass);
80445             if (!body) {
80446                 return undefined;
80447             }
80448             return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(
80449             /*decorators*/ undefined, 
80450             /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor));
80451         }
80452         function transformConstructorBody(node, constructor, isDerivedClass) {
80453             var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields;
80454             var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
80455             if (!useDefineForClassFields) {
80456                 properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
80457             }
80458             // Only generate synthetic constructor when there are property initializers to move.
80459             if (!constructor && !ts.some(properties)) {
80460                 return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
80461             }
80462             resumeLexicalEnvironment();
80463             var indexOfFirstStatement = 0;
80464             var statements = [];
80465             if (!constructor && isDerivedClass) {
80466                 // Add a synthetic `super` call:
80467                 //
80468                 //  super(...arguments);
80469                 //
80470                 statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), 
80471                 /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))])));
80472             }
80473             if (constructor) {
80474                 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
80475             }
80476             // Add the property initializers. Transforms this:
80477             //
80478             //  public x = 1;
80479             //
80480             // Into this:
80481             //
80482             //  constructor() {
80483             //      this.x = 1;
80484             //  }
80485             //
80486             if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
80487                 var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
80488                 if (afterParameterProperties === -1) {
80489                     afterParameterProperties = constructor.body.statements.length;
80490                 }
80491                 if (afterParameterProperties > indexOfFirstStatement) {
80492                     if (!useDefineForClassFields) {
80493                         ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
80494                     }
80495                     indexOfFirstStatement = afterParameterProperties;
80496                 }
80497             }
80498             addPropertyStatements(statements, properties, ts.createThis());
80499             // Add existing statements, skipping the initial super call.
80500             if (constructor) {
80501                 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
80502             }
80503             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
80504             return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
80505             /*location*/ constructor ? constructor.body.statements : node.members), 
80506             /*multiLine*/ true), 
80507             /*location*/ constructor ? constructor.body : undefined);
80508         }
80509         /**
80510          * Generates assignment statements for property initializers.
80511          *
80512          * @param properties An array of property declarations to transform.
80513          * @param receiver The receiver on which each property should be assigned.
80514          */
80515         function addPropertyStatements(statements, properties, receiver) {
80516             for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
80517                 var property = properties_8[_i];
80518                 var expression = transformProperty(property, receiver);
80519                 if (!expression) {
80520                     continue;
80521                 }
80522                 var statement = ts.createExpressionStatement(expression);
80523                 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
80524                 ts.setCommentRange(statement, property);
80525                 ts.setOriginalNode(statement, property);
80526                 statements.push(statement);
80527             }
80528         }
80529         /**
80530          * Generates assignment expressions for property initializers.
80531          *
80532          * @param properties An array of property declarations to transform.
80533          * @param receiver The receiver on which each property should be assigned.
80534          */
80535         function generateInitializedPropertyExpressions(properties, receiver) {
80536             var expressions = [];
80537             for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
80538                 var property = properties_9[_i];
80539                 var expression = transformProperty(property, receiver);
80540                 if (!expression) {
80541                     continue;
80542                 }
80543                 ts.startOnNewLine(expression);
80544                 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
80545                 ts.setCommentRange(expression, property);
80546                 ts.setOriginalNode(expression, property);
80547                 expressions.push(expression);
80548             }
80549             return expressions;
80550         }
80551         /**
80552          * Transforms a property initializer into an assignment statement.
80553          *
80554          * @param property The property declaration.
80555          * @param receiver The object receiving the property assignment.
80556          */
80557         function transformProperty(property, receiver) {
80558             // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
80559             var emitAssignment = !context.getCompilerOptions().useDefineForClassFields;
80560             var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
80561                 ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
80562                 : property.name;
80563             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) {
80564                 var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
80565                 if (privateIdentifierInfo) {
80566                     switch (privateIdentifierInfo.placement) {
80567                         case 0 /* InstanceField */: {
80568                             return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName);
80569                         }
80570                     }
80571                 }
80572                 else {
80573                     ts.Debug.fail("Undeclared private name for property declaration.");
80574                 }
80575             }
80576             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80577                 return undefined;
80578             }
80579             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80580                 return undefined;
80581             }
80582             var propertyOriginalNode = ts.getOriginalNode(property);
80583             var initializer = property.initializer || emitAssignment ? ts.visitNode(property.initializer, visitor, ts.isExpression)
80584                 : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
80585                     : ts.createVoidZero();
80586             if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
80587                 var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
80588                 return ts.createAssignment(memberAccess, initializer);
80589             }
80590             else {
80591                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
80592                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
80593                         : propertyName;
80594                 var descriptor = ts.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
80595                 return ts.createObjectDefinePropertyCall(receiver, name, descriptor);
80596             }
80597         }
80598         function enableSubstitutionForClassAliases() {
80599             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
80600                 enabledSubstitutions |= 1 /* ClassAliases */;
80601                 // We need to enable substitutions for identifiers. This allows us to
80602                 // substitute class names inside of a class declaration.
80603                 context.enableSubstitution(75 /* Identifier */);
80604                 // Keep track of class aliases.
80605                 classAliases = [];
80606             }
80607         }
80608         /**
80609          * Hooks node substitutions.
80610          *
80611          * @param hint The context for the emitter.
80612          * @param node The node to substitute.
80613          */
80614         function onSubstituteNode(hint, node) {
80615             node = previousOnSubstituteNode(hint, node);
80616             if (hint === 1 /* Expression */) {
80617                 return substituteExpression(node);
80618             }
80619             return node;
80620         }
80621         function substituteExpression(node) {
80622             switch (node.kind) {
80623                 case 75 /* Identifier */:
80624                     return substituteExpressionIdentifier(node);
80625             }
80626             return node;
80627         }
80628         function substituteExpressionIdentifier(node) {
80629             return trySubstituteClassAlias(node) || node;
80630         }
80631         function trySubstituteClassAlias(node) {
80632             if (enabledSubstitutions & 1 /* ClassAliases */) {
80633                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
80634                     // Due to the emit for class decorators, any reference to the class from inside of the class body
80635                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
80636                     // behavior of class names in ES6.
80637                     // Also, when emitting statics for class expressions, we must substitute a class alias for
80638                     // constructor references in static property initializers.
80639                     var declaration = resolver.getReferencedValueDeclaration(node);
80640                     if (declaration) {
80641                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
80642                         if (classAlias) {
80643                             var clone_2 = ts.getSynthesizedClone(classAlias);
80644                             ts.setSourceMapRange(clone_2, node);
80645                             ts.setCommentRange(clone_2, node);
80646                             return clone_2;
80647                         }
80648                     }
80649                 }
80650             }
80651             return undefined;
80652         }
80653         /**
80654          * If the name is a computed property, this function transforms it, then either returns an expression which caches the
80655          * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
80656          * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
80657          */
80658         function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
80659             if (ts.isComputedPropertyName(name)) {
80660                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
80661                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
80662                 var inlinable = ts.isSimpleInlineableExpression(innerExpression);
80663                 var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
80664                 if (!alreadyTransformed && !inlinable && shouldHoist) {
80665                     var generatedName = ts.getGeneratedNameForNode(name);
80666                     hoistVariableDeclaration(generatedName);
80667                     return ts.createAssignment(generatedName, expression);
80668                 }
80669                 return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
80670             }
80671         }
80672         function startPrivateIdentifierEnvironment() {
80673             privateIdentifierEnvironmentStack.push(currentPrivateIdentifierEnvironment);
80674             currentPrivateIdentifierEnvironment = undefined;
80675         }
80676         function endPrivateIdentifierEnvironment() {
80677             currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop();
80678         }
80679         function addPrivateIdentifierToEnvironment(name) {
80680             var text = ts.getTextOfPropertyName(name);
80681             var weakMapName = ts.createOptimisticUniqueName("_" + text.substring(1));
80682             weakMapName.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80683             hoistVariableDeclaration(weakMapName);
80684             (currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = ts.createUnderscoreEscapedMap()))
80685                 .set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName });
80686             (pendingExpressions || (pendingExpressions = [])).push(ts.createAssignment(weakMapName, ts.createNew(ts.createIdentifier("WeakMap"), 
80687             /*typeArguments*/ undefined, [])));
80688         }
80689         function accessPrivateIdentifier(name) {
80690             if (currentPrivateIdentifierEnvironment) {
80691                 var info = currentPrivateIdentifierEnvironment.get(name.escapedText);
80692                 if (info) {
80693                     return info;
80694                 }
80695             }
80696             for (var i = privateIdentifierEnvironmentStack.length - 1; i >= 0; --i) {
80697                 var env = privateIdentifierEnvironmentStack[i];
80698                 if (!env) {
80699                     continue;
80700                 }
80701                 var info = env.get(name.escapedText);
80702                 if (info) {
80703                     return info;
80704                 }
80705             }
80706             return undefined;
80707         }
80708         function wrapPrivateIdentifierForDestructuringTarget(node) {
80709             var parameter = ts.getGeneratedNameForNode(node);
80710             var info = accessPrivateIdentifier(node.name);
80711             if (!info) {
80712                 return ts.visitEachChild(node, visitor, context);
80713             }
80714             var receiver = node.expression;
80715             // We cannot copy `this` or `super` into the function because they will be bound
80716             // differently inside the function.
80717             if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
80718                 receiver = ts.createTempVariable(hoistVariableDeclaration);
80719                 receiver.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80720                 (pendingExpressions || (pendingExpressions = [])).push(ts.createBinary(receiver, 62 /* EqualsToken */, node.expression));
80721             }
80722             return ts.createPropertyAccess(
80723             // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
80724             ts.createParen(ts.createObjectLiteral([
80725                 ts.createSetAccessor(
80726                 /*decorators*/ undefined, 
80727                 /*modifiers*/ undefined, "value", [ts.createParameter(
80728                     /*decorators*/ undefined, 
80729                     /*modifiers*/ undefined, 
80730                     /*dotDotDotToken*/ undefined, parameter, 
80731                     /*questionToken*/ undefined, 
80732                     /*type*/ undefined, 
80733                     /*initializer*/ undefined)], ts.createBlock([ts.createExpressionStatement(createPrivateIdentifierAssignment(info, receiver, parameter, 62 /* EqualsToken */))]))
80734             ])), "value");
80735         }
80736         function visitArrayAssignmentTarget(node) {
80737             var target = ts.getTargetOfBindingOrAssignmentElement(node);
80738             if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80739                 var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80740                 if (ts.isAssignmentExpression(node)) {
80741                     return ts.updateBinary(node, wrapped, ts.visitNode(node.right, visitor, ts.isExpression), node.operatorToken);
80742                 }
80743                 else if (ts.isSpreadElement(node)) {
80744                     return ts.updateSpread(node, wrapped);
80745                 }
80746                 else {
80747                     return wrapped;
80748                 }
80749             }
80750             return ts.visitNode(node, visitorDestructuringTarget);
80751         }
80752         function visitObjectAssignmentTarget(node) {
80753             if (ts.isPropertyAssignment(node)) {
80754                 var target = ts.getTargetOfBindingOrAssignmentElement(node);
80755                 if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80756                     var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
80757                     var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80758                     return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), initializer ? ts.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped);
80759                 }
80760                 return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), ts.visitNode(node.initializer, visitorDestructuringTarget));
80761             }
80762             return ts.visitNode(node, visitor);
80763         }
80764         function visitAssignmentPattern(node) {
80765             if (ts.isArrayLiteralExpression(node)) {
80766                 // Transforms private names in destructuring assignment array bindings.
80767                 //
80768                 // Source:
80769                 // ([ this.#myProp ] = [ "hello" ]);
80770                 //
80771                 // Transformation:
80772                 // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
80773                 return ts.updateArrayLiteral(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
80774             }
80775             else {
80776                 // Transforms private names in destructuring assignment object bindings.
80777                 //
80778                 // Source:
80779                 // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
80780                 //
80781                 // Transformation:
80782                 // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
80783                 return ts.updateObjectLiteral(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
80784             }
80785         }
80786     }
80787     ts.transformClassFields = transformClassFields;
80788     function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
80789         return ts.createCall(ts.createPropertyAccess(weakMapName, "set"), 
80790         /*typeArguments*/ undefined, [receiver, initializer || ts.createVoidZero()]);
80791     }
80792     ts.classPrivateFieldGetHelper = {
80793         name: "typescript:classPrivateFieldGet",
80794         scoped: false,
80795         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            };"
80796     };
80797     function createClassPrivateFieldGetHelper(context, receiver, privateField) {
80798         context.requestEmitHelper(ts.classPrivateFieldGetHelper);
80799         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldGet"), /* typeArguments */ undefined, [receiver, privateField]);
80800     }
80801     ts.classPrivateFieldSetHelper = {
80802         name: "typescript:classPrivateFieldSet",
80803         scoped: false,
80804         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            };"
80805     };
80806     function createClassPrivateFieldSetHelper(context, receiver, privateField, value) {
80807         context.requestEmitHelper(ts.classPrivateFieldSetHelper);
80808         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldSet"), /* typeArguments */ undefined, [receiver, privateField, value]);
80809     }
80810 })(ts || (ts = {}));
80811 /*@internal*/
80812 var ts;
80813 (function (ts) {
80814     var ES2017SubstitutionFlags;
80815     (function (ES2017SubstitutionFlags) {
80816         /** Enables substitutions for async methods with `super` calls. */
80817         ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
80818     })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
80819     var ContextFlags;
80820     (function (ContextFlags) {
80821         ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
80822         ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
80823     })(ContextFlags || (ContextFlags = {}));
80824     function transformES2017(context) {
80825         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
80826         var resolver = context.getEmitResolver();
80827         var compilerOptions = context.getCompilerOptions();
80828         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80829         /**
80830          * Keeps track of whether expression substitution has been enabled for specific edge cases.
80831          * They are persisted between each SourceFile transformation and should not be reset.
80832          */
80833         var enabledSubstitutions;
80834         /**
80835          * This keeps track of containers where `super` is valid, for use with
80836          * just-in-time substitution for `super` expressions inside of async methods.
80837          */
80838         var enclosingSuperContainerFlags = 0;
80839         var enclosingFunctionParameterNames;
80840         /**
80841          * Keeps track of property names accessed on super (`super.x`) within async functions.
80842          */
80843         var capturedSuperProperties;
80844         /** Whether the async function contains an element access on super (`super[x]`). */
80845         var hasSuperElementAccess;
80846         /** A set of node IDs for generated super accessors (variable statements). */
80847         var substitutedSuperAccessors = [];
80848         var contextFlags = 0;
80849         // Save the previous transformation hooks.
80850         var previousOnEmitNode = context.onEmitNode;
80851         var previousOnSubstituteNode = context.onSubstituteNode;
80852         // Set new transformation hooks.
80853         context.onEmitNode = onEmitNode;
80854         context.onSubstituteNode = onSubstituteNode;
80855         return ts.chainBundle(transformSourceFile);
80856         function transformSourceFile(node) {
80857             if (node.isDeclarationFile) {
80858                 return node;
80859             }
80860             setContextFlag(1 /* NonTopLevel */, false);
80861             setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
80862             var visited = ts.visitEachChild(node, visitor, context);
80863             ts.addEmitHelpers(visited, context.readEmitHelpers());
80864             return visited;
80865         }
80866         function setContextFlag(flag, val) {
80867             contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
80868         }
80869         function inContext(flags) {
80870             return (contextFlags & flags) !== 0;
80871         }
80872         function inTopLevelContext() {
80873             return !inContext(1 /* NonTopLevel */);
80874         }
80875         function inHasLexicalThisContext() {
80876             return inContext(2 /* HasLexicalThis */);
80877         }
80878         function doWithContext(flags, cb, value) {
80879             var contextFlagsToSet = flags & ~contextFlags;
80880             if (contextFlagsToSet) {
80881                 setContextFlag(contextFlagsToSet, /*val*/ true);
80882                 var result = cb(value);
80883                 setContextFlag(contextFlagsToSet, /*val*/ false);
80884                 return result;
80885             }
80886             return cb(value);
80887         }
80888         function visitDefault(node) {
80889             return ts.visitEachChild(node, visitor, context);
80890         }
80891         function visitor(node) {
80892             if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) {
80893                 return node;
80894             }
80895             switch (node.kind) {
80896                 case 126 /* AsyncKeyword */:
80897                     // ES2017 async modifier should be elided for targets < ES2017
80898                     return undefined;
80899                 case 206 /* AwaitExpression */:
80900                     return visitAwaitExpression(node);
80901                 case 161 /* MethodDeclaration */:
80902                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
80903                 case 244 /* FunctionDeclaration */:
80904                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
80905                 case 201 /* FunctionExpression */:
80906                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
80907                 case 202 /* ArrowFunction */:
80908                     return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
80909                 case 194 /* PropertyAccessExpression */:
80910                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
80911                         capturedSuperProperties.set(node.name.escapedText, true);
80912                     }
80913                     return ts.visitEachChild(node, visitor, context);
80914                 case 195 /* ElementAccessExpression */:
80915                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
80916                         hasSuperElementAccess = true;
80917                     }
80918                     return ts.visitEachChild(node, visitor, context);
80919                 case 163 /* GetAccessor */:
80920                 case 164 /* SetAccessor */:
80921                 case 162 /* Constructor */:
80922                 case 245 /* ClassDeclaration */:
80923                 case 214 /* ClassExpression */:
80924                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
80925                 default:
80926                     return ts.visitEachChild(node, visitor, context);
80927             }
80928         }
80929         function asyncBodyVisitor(node) {
80930             if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
80931                 switch (node.kind) {
80932                     case 225 /* VariableStatement */:
80933                         return visitVariableStatementInAsyncBody(node);
80934                     case 230 /* ForStatement */:
80935                         return visitForStatementInAsyncBody(node);
80936                     case 231 /* ForInStatement */:
80937                         return visitForInStatementInAsyncBody(node);
80938                     case 232 /* ForOfStatement */:
80939                         return visitForOfStatementInAsyncBody(node);
80940                     case 280 /* CatchClause */:
80941                         return visitCatchClauseInAsyncBody(node);
80942                     case 223 /* Block */:
80943                     case 237 /* SwitchStatement */:
80944                     case 251 /* CaseBlock */:
80945                     case 277 /* CaseClause */:
80946                     case 278 /* DefaultClause */:
80947                     case 240 /* TryStatement */:
80948                     case 228 /* DoStatement */:
80949                     case 229 /* WhileStatement */:
80950                     case 227 /* IfStatement */:
80951                     case 236 /* WithStatement */:
80952                     case 238 /* LabeledStatement */:
80953                         return ts.visitEachChild(node, asyncBodyVisitor, context);
80954                     default:
80955                         return ts.Debug.assertNever(node, "Unhandled node.");
80956                 }
80957             }
80958             return visitor(node);
80959         }
80960         function visitCatchClauseInAsyncBody(node) {
80961             var catchClauseNames = ts.createUnderscoreEscapedMap();
80962             recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
80963             // names declared in a catch variable are block scoped
80964             var catchClauseUnshadowedNames;
80965             catchClauseNames.forEach(function (_, escapedName) {
80966                 if (enclosingFunctionParameterNames.has(escapedName)) {
80967                     if (!catchClauseUnshadowedNames) {
80968                         catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames);
80969                     }
80970                     catchClauseUnshadowedNames.delete(escapedName);
80971                 }
80972             });
80973             if (catchClauseUnshadowedNames) {
80974                 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
80975                 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
80976                 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
80977                 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
80978                 return result;
80979             }
80980             else {
80981                 return ts.visitEachChild(node, asyncBodyVisitor, context);
80982             }
80983         }
80984         function visitVariableStatementInAsyncBody(node) {
80985             if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
80986                 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
80987                 return expression ? ts.createExpressionStatement(expression) : undefined;
80988             }
80989             return ts.visitEachChild(node, visitor, context);
80990         }
80991         function visitForInStatementInAsyncBody(node) {
80992             return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer)
80993                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
80994                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
80995         }
80996         function visitForOfStatementInAsyncBody(node) {
80997             return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
80998                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
80999                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
81000         }
81001         function visitForStatementInAsyncBody(node) {
81002             var initializer = node.initializer; // TODO: GH#18217
81003             return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer)
81004                 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
81005                 : 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));
81006         }
81007         /**
81008          * Visits an AwaitExpression node.
81009          *
81010          * This function will be called any time a ES2017 await expression is encountered.
81011          *
81012          * @param node The node to visit.
81013          */
81014         function visitAwaitExpression(node) {
81015             // do not downlevel a top-level await as it is module syntax...
81016             if (inTopLevelContext()) {
81017                 return ts.visitEachChild(node, visitor, context);
81018             }
81019             return ts.setOriginalNode(ts.setTextRange(ts.createYield(
81020             /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
81021         }
81022         /**
81023          * Visits a MethodDeclaration node.
81024          *
81025          * This function will be called when one of the following conditions are met:
81026          * - The node is marked as async
81027          *
81028          * @param node The node to visit.
81029          */
81030         function visitMethodDeclaration(node) {
81031             return ts.updateMethod(node, 
81032             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81033             /*questionToken*/ undefined, 
81034             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81035             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81036                 ? transformAsyncFunctionBody(node)
81037                 : ts.visitFunctionBody(node.body, visitor, context));
81038         }
81039         /**
81040          * Visits a FunctionDeclaration node.
81041          *
81042          * This function will be called when one of the following conditions are met:
81043          * - The node is marked async
81044          *
81045          * @param node The node to visit.
81046          */
81047         function visitFunctionDeclaration(node) {
81048             return ts.updateFunctionDeclaration(node, 
81049             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81050             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81051             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81052                 ? transformAsyncFunctionBody(node)
81053                 : ts.visitFunctionBody(node.body, visitor, context));
81054         }
81055         /**
81056          * Visits a FunctionExpression node.
81057          *
81058          * This function will be called when one of the following conditions are met:
81059          * - The node is marked async
81060          *
81061          * @param node The node to visit.
81062          */
81063         function visitFunctionExpression(node) {
81064             return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81065             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81066             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81067                 ? transformAsyncFunctionBody(node)
81068                 : ts.visitFunctionBody(node.body, visitor, context));
81069         }
81070         /**
81071          * Visits an ArrowFunction.
81072          *
81073          * This function will be called when one of the following conditions are met:
81074          * - The node is marked async
81075          *
81076          * @param node The node to visit.
81077          */
81078         function visitArrowFunction(node) {
81079             return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), 
81080             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81081             /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
81082                 ? transformAsyncFunctionBody(node)
81083                 : ts.visitFunctionBody(node.body, visitor, context));
81084         }
81085         function recordDeclarationName(_a, names) {
81086             var name = _a.name;
81087             if (ts.isIdentifier(name)) {
81088                 names.set(name.escapedText, true);
81089             }
81090             else {
81091                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81092                     var element = _b[_i];
81093                     if (!ts.isOmittedExpression(element)) {
81094                         recordDeclarationName(element, names);
81095                     }
81096                 }
81097             }
81098         }
81099         function isVariableDeclarationListWithCollidingName(node) {
81100             return !!node
81101                 && ts.isVariableDeclarationList(node)
81102                 && !(node.flags & 3 /* BlockScoped */)
81103                 && node.declarations.some(collidesWithParameterName);
81104         }
81105         function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
81106             hoistVariableDeclarationList(node);
81107             var variables = ts.getInitializedVariables(node);
81108             if (variables.length === 0) {
81109                 if (hasReceiver) {
81110                     return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
81111                 }
81112                 return undefined;
81113             }
81114             return ts.inlineExpressions(ts.map(variables, transformInitializedVariable));
81115         }
81116         function hoistVariableDeclarationList(node) {
81117             ts.forEach(node.declarations, hoistVariable);
81118         }
81119         function hoistVariable(_a) {
81120             var name = _a.name;
81121             if (ts.isIdentifier(name)) {
81122                 hoistVariableDeclaration(name);
81123             }
81124             else {
81125                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81126                     var element = _b[_i];
81127                     if (!ts.isOmittedExpression(element)) {
81128                         hoistVariable(element);
81129                     }
81130                 }
81131             }
81132         }
81133         function transformInitializedVariable(node) {
81134             var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node);
81135             return ts.visitNode(converted, visitor, ts.isExpression);
81136         }
81137         function collidesWithParameterName(_a) {
81138             var name = _a.name;
81139             if (ts.isIdentifier(name)) {
81140                 return enclosingFunctionParameterNames.has(name.escapedText);
81141             }
81142             else {
81143                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81144                     var element = _b[_i];
81145                     if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
81146                         return true;
81147                     }
81148                 }
81149             }
81150             return false;
81151         }
81152         function transformAsyncFunctionBody(node) {
81153             resumeLexicalEnvironment();
81154             var original = ts.getOriginalNode(node, ts.isFunctionLike);
81155             var nodeType = original.type;
81156             var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
81157             var isArrowFunction = node.kind === 202 /* ArrowFunction */;
81158             var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
81159             // An async function is emit as an outer function that calls an inner
81160             // generator function. To preserve lexical bindings, we pass the current
81161             // `this` and `arguments` objects to `__awaiter`. The generator function
81162             // passed to `__awaiter` is executed inside of the callback to the
81163             // promise constructor.
81164             var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
81165             enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap();
81166             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
81167                 var parameter = _a[_i];
81168                 recordDeclarationName(parameter, enclosingFunctionParameterNames);
81169             }
81170             var savedCapturedSuperProperties = capturedSuperProperties;
81171             var savedHasSuperElementAccess = hasSuperElementAccess;
81172             if (!isArrowFunction) {
81173                 capturedSuperProperties = ts.createUnderscoreEscapedMap();
81174                 hasSuperElementAccess = false;
81175             }
81176             var result;
81177             if (!isArrowFunction) {
81178                 var statements = [];
81179                 var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
81180                 statements.push(ts.createReturn(createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
81181                 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
81182                 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
81183                 // This step isn't needed if we eventually transform this to ES5.
81184                 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
81185                 if (emitSuperHelpers) {
81186                     enableSubstitutionForAsyncMethodsWithSuper();
81187                     if (ts.hasEntries(capturedSuperProperties)) {
81188                         var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
81189                         substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
81190                         ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
81191                     }
81192                 }
81193                 var block = ts.createBlock(statements, /*multiLine*/ true);
81194                 ts.setTextRange(block, node.body);
81195                 if (emitSuperHelpers && hasSuperElementAccess) {
81196                     // Emit helpers for super element access expressions (`super[x]`).
81197                     if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
81198                         ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
81199                     }
81200                     else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
81201                         ts.addEmitHelper(block, ts.asyncSuperHelper);
81202                     }
81203                 }
81204                 result = block;
81205             }
81206             else {
81207                 var expression = createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
81208                 var declarations = endLexicalEnvironment();
81209                 if (ts.some(declarations)) {
81210                     var block = ts.convertToFunctionBody(expression);
81211                     result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
81212                 }
81213                 else {
81214                     result = expression;
81215                 }
81216             }
81217             enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
81218             if (!isArrowFunction) {
81219                 capturedSuperProperties = savedCapturedSuperProperties;
81220                 hasSuperElementAccess = savedHasSuperElementAccess;
81221             }
81222             return result;
81223         }
81224         function transformAsyncFunctionBodyWorker(body, start) {
81225             if (ts.isBlock(body)) {
81226                 return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
81227             }
81228             else {
81229                 return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
81230             }
81231         }
81232         function getPromiseConstructor(type) {
81233             var typeName = type && ts.getEntityNameFromTypeNode(type);
81234             if (typeName && ts.isEntityName(typeName)) {
81235                 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
81236                 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
81237                     || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
81238                     return typeName;
81239                 }
81240             }
81241             return undefined;
81242         }
81243         function enableSubstitutionForAsyncMethodsWithSuper() {
81244             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
81245                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
81246                 // We need to enable substitutions for call, property access, and element access
81247                 // if we need to rewrite super calls.
81248                 context.enableSubstitution(196 /* CallExpression */);
81249                 context.enableSubstitution(194 /* PropertyAccessExpression */);
81250                 context.enableSubstitution(195 /* ElementAccessExpression */);
81251                 // We need to be notified when entering and exiting declarations that bind super.
81252                 context.enableEmitNotification(245 /* ClassDeclaration */);
81253                 context.enableEmitNotification(161 /* MethodDeclaration */);
81254                 context.enableEmitNotification(163 /* GetAccessor */);
81255                 context.enableEmitNotification(164 /* SetAccessor */);
81256                 context.enableEmitNotification(162 /* Constructor */);
81257                 // We need to be notified when entering the generated accessor arrow functions.
81258                 context.enableEmitNotification(225 /* VariableStatement */);
81259             }
81260         }
81261         /**
81262          * Hook for node emit.
81263          *
81264          * @param hint A hint as to the intended usage of the node.
81265          * @param node The node to emit.
81266          * @param emit A callback used to emit the node in the printer.
81267          */
81268         function onEmitNode(hint, node, emitCallback) {
81269             // If we need to support substitutions for `super` in an async method,
81270             // we should track it here.
81271             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
81272                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
81273                 if (superContainerFlags !== enclosingSuperContainerFlags) {
81274                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81275                     enclosingSuperContainerFlags = superContainerFlags;
81276                     previousOnEmitNode(hint, node, emitCallback);
81277                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81278                     return;
81279                 }
81280             }
81281             // Disable substitution in the generated super accessor itself.
81282             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
81283                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81284                 enclosingSuperContainerFlags = 0;
81285                 previousOnEmitNode(hint, node, emitCallback);
81286                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81287                 return;
81288             }
81289             previousOnEmitNode(hint, node, emitCallback);
81290         }
81291         /**
81292          * Hooks node substitutions.
81293          *
81294          * @param hint A hint as to the intended usage of the node.
81295          * @param node The node to substitute.
81296          */
81297         function onSubstituteNode(hint, node) {
81298             node = previousOnSubstituteNode(hint, node);
81299             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
81300                 return substituteExpression(node);
81301             }
81302             return node;
81303         }
81304         function substituteExpression(node) {
81305             switch (node.kind) {
81306                 case 194 /* PropertyAccessExpression */:
81307                     return substitutePropertyAccessExpression(node);
81308                 case 195 /* ElementAccessExpression */:
81309                     return substituteElementAccessExpression(node);
81310                 case 196 /* CallExpression */:
81311                     return substituteCallExpression(node);
81312             }
81313             return node;
81314         }
81315         function substitutePropertyAccessExpression(node) {
81316             if (node.expression.kind === 102 /* SuperKeyword */) {
81317                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
81318             }
81319             return node;
81320         }
81321         function substituteElementAccessExpression(node) {
81322             if (node.expression.kind === 102 /* SuperKeyword */) {
81323                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
81324             }
81325             return node;
81326         }
81327         function substituteCallExpression(node) {
81328             var expression = node.expression;
81329             if (ts.isSuperProperty(expression)) {
81330                 var argumentExpression = ts.isPropertyAccessExpression(expression)
81331                     ? substitutePropertyAccessExpression(expression)
81332                     : substituteElementAccessExpression(expression);
81333                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
81334                 /*typeArguments*/ undefined, __spreadArrays([
81335                     ts.createThis()
81336                 ], node.arguments));
81337             }
81338             return node;
81339         }
81340         function isSuperContainer(node) {
81341             var kind = node.kind;
81342             return kind === 245 /* ClassDeclaration */
81343                 || kind === 162 /* Constructor */
81344                 || kind === 161 /* MethodDeclaration */
81345                 || kind === 163 /* GetAccessor */
81346                 || kind === 164 /* SetAccessor */;
81347         }
81348         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
81349             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
81350                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81351                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
81352             }
81353             else {
81354                 return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81355                 /*typeArguments*/ undefined, [argumentExpression]), location);
81356             }
81357         }
81358     }
81359     ts.transformES2017 = transformES2017;
81360     /** Creates a variable named `_super` with accessor properties for the given property names. */
81361     function createSuperAccessVariableStatement(resolver, node, names) {
81362         // Create a variable declaration with a getter/setter (if binding) definition for each name:
81363         //   const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
81364         var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
81365         var accessors = [];
81366         names.forEach(function (_, key) {
81367             var name = ts.unescapeLeadingUnderscores(key);
81368             var getterAndSetter = [];
81369             getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(
81370             /* modifiers */ undefined, 
81371             /* typeParameters */ undefined, 
81372             /* parameters */ [], 
81373             /* type */ undefined, 
81374             /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
81375             if (hasBinding) {
81376                 getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
81377                 /* modifiers */ undefined, 
81378                 /* typeParameters */ undefined, 
81379                 /* parameters */ [
81380                     ts.createParameter(
81381                     /* decorators */ undefined, 
81382                     /* modifiers */ undefined, 
81383                     /* dotDotDotToken */ undefined, "v", 
81384                     /* questionToken */ undefined, 
81385                     /* type */ undefined, 
81386                     /* initializer */ undefined)
81387                 ], 
81388                 /* type */ undefined, 
81389                 /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
81390             }
81391             accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
81392         });
81393         return ts.createVariableStatement(
81394         /* modifiers */ undefined, ts.createVariableDeclarationList([
81395             ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), 
81396             /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), 
81397             /* typeArguments */ undefined, [
81398                 ts.createNull(),
81399                 ts.createObjectLiteral(accessors, /* multiline */ true)
81400             ]))
81401         ], 2 /* Const */));
81402     }
81403     ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
81404     ts.awaiterHelper = {
81405         name: "typescript:awaiter",
81406         importName: "__awaiter",
81407         scoped: false,
81408         priority: 5,
81409         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            };"
81410     };
81411     function createAwaiterHelper(context, hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
81412         context.requestEmitHelper(ts.awaiterHelper);
81413         var generatorFunc = ts.createFunctionExpression(
81414         /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), 
81415         /*name*/ undefined, 
81416         /*typeParameters*/ undefined, 
81417         /*parameters*/ [], 
81418         /*type*/ undefined, body);
81419         // Mark this node as originally an async function
81420         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
81421         return ts.createCall(ts.getUnscopedHelperName("__awaiter"), 
81422         /*typeArguments*/ undefined, [
81423             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
81424             hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(),
81425             promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(),
81426             generatorFunc
81427         ]);
81428     }
81429     ts.asyncSuperHelper = {
81430         name: "typescript:async-super",
81431         scoped: true,
81432         text: ts.helperString(__makeTemplateObject(["\n            const ", " = name => super[name];"], ["\n            const ", " = name => super[name];"]), "_superIndex")
81433     };
81434     ts.advancedAsyncSuperHelper = {
81435         name: "typescript:advanced-async-super",
81436         scoped: true,
81437         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")
81438     };
81439 })(ts || (ts = {}));
81440 /*@internal*/
81441 var ts;
81442 (function (ts) {
81443     var ESNextSubstitutionFlags;
81444     (function (ESNextSubstitutionFlags) {
81445         /** Enables substitutions for async methods with `super` calls. */
81446         ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
81447     })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
81448     // Facts we track as we traverse the tree
81449     var HierarchyFacts;
81450     (function (HierarchyFacts) {
81451         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
81452         //
81453         // Ancestor facts
81454         //
81455         HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis";
81456         HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer";
81457         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
81458         //
81459         // Ancestor masks
81460         //
81461         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask";
81462         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes";
81463         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes";
81464         HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes";
81465         HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes";
81466         HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes";
81467         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes";
81468         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes";
81469         HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes";
81470         HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes";
81471     })(HierarchyFacts || (HierarchyFacts = {}));
81472     function transformES2018(context) {
81473         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
81474         var resolver = context.getEmitResolver();
81475         var compilerOptions = context.getCompilerOptions();
81476         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
81477         var previousOnEmitNode = context.onEmitNode;
81478         context.onEmitNode = onEmitNode;
81479         var previousOnSubstituteNode = context.onSubstituteNode;
81480         context.onSubstituteNode = onSubstituteNode;
81481         var exportedVariableStatement = false;
81482         var enabledSubstitutions;
81483         var enclosingFunctionFlags;
81484         var enclosingSuperContainerFlags = 0;
81485         var hierarchyFacts = 0;
81486         var currentSourceFile;
81487         var taggedTemplateStringDeclarations;
81488         /** Keeps track of property names accessed on super (`super.x`) within async functions. */
81489         var capturedSuperProperties;
81490         /** Whether the async function contains an element access on super (`super[x]`). */
81491         var hasSuperElementAccess;
81492         /** A set of node IDs for generated super accessors. */
81493         var substitutedSuperAccessors = [];
81494         return ts.chainBundle(transformSourceFile);
81495         function affectsSubtree(excludeFacts, includeFacts) {
81496             return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
81497         }
81498         /**
81499          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
81500          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
81501          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
81502          */
81503         function enterSubtree(excludeFacts, includeFacts) {
81504             var ancestorFacts = hierarchyFacts;
81505             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
81506             return ancestorFacts;
81507         }
81508         /**
81509          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
81510          * subtree.
81511          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
81512          */
81513         function exitSubtree(ancestorFacts) {
81514             hierarchyFacts = ancestorFacts;
81515         }
81516         function recordTaggedTemplateString(temp) {
81517             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
81518         }
81519         function transformSourceFile(node) {
81520             if (node.isDeclarationFile) {
81521                 return node;
81522             }
81523             currentSourceFile = node;
81524             var visited = visitSourceFile(node);
81525             ts.addEmitHelpers(visited, context.readEmitHelpers());
81526             currentSourceFile = undefined;
81527             taggedTemplateStringDeclarations = undefined;
81528             return visited;
81529         }
81530         function visitor(node) {
81531             return visitorWorker(node, /*noDestructuringValue*/ false);
81532         }
81533         function visitorNoDestructuringValue(node) {
81534             return visitorWorker(node, /*noDestructuringValue*/ true);
81535         }
81536         function visitorNoAsyncModifier(node) {
81537             if (node.kind === 126 /* AsyncKeyword */) {
81538                 return undefined;
81539             }
81540             return node;
81541         }
81542         function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
81543             if (affectsSubtree(excludeFacts, includeFacts)) {
81544                 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
81545                 var result = cb(value);
81546                 exitSubtree(ancestorFacts);
81547                 return result;
81548             }
81549             return cb(value);
81550         }
81551         function visitDefault(node) {
81552             return ts.visitEachChild(node, visitor, context);
81553         }
81554         function visitorWorker(node, noDestructuringValue) {
81555             if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) {
81556                 return node;
81557             }
81558             switch (node.kind) {
81559                 case 206 /* AwaitExpression */:
81560                     return visitAwaitExpression(node);
81561                 case 212 /* YieldExpression */:
81562                     return visitYieldExpression(node);
81563                 case 235 /* ReturnStatement */:
81564                     return visitReturnStatement(node);
81565                 case 238 /* LabeledStatement */:
81566                     return visitLabeledStatement(node);
81567                 case 193 /* ObjectLiteralExpression */:
81568                     return visitObjectLiteralExpression(node);
81569                 case 209 /* BinaryExpression */:
81570                     return visitBinaryExpression(node, noDestructuringValue);
81571                 case 280 /* CatchClause */:
81572                     return visitCatchClause(node);
81573                 case 225 /* VariableStatement */:
81574                     return visitVariableStatement(node);
81575                 case 242 /* VariableDeclaration */:
81576                     return visitVariableDeclaration(node);
81577                 case 228 /* DoStatement */:
81578                 case 229 /* WhileStatement */:
81579                 case 231 /* ForInStatement */:
81580                     return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81581                 case 232 /* ForOfStatement */:
81582                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
81583                 case 230 /* ForStatement */:
81584                     return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81585                 case 205 /* VoidExpression */:
81586                     return visitVoidExpression(node);
81587                 case 162 /* Constructor */:
81588                     return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81589                 case 161 /* MethodDeclaration */:
81590                     return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81591                 case 163 /* GetAccessor */:
81592                     return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81593                 case 164 /* SetAccessor */:
81594                     return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81595                 case 244 /* FunctionDeclaration */:
81596                     return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81597                 case 201 /* FunctionExpression */:
81598                     return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81599                 case 202 /* ArrowFunction */:
81600                     return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */);
81601                 case 156 /* Parameter */:
81602                     return visitParameter(node);
81603                 case 226 /* ExpressionStatement */:
81604                     return visitExpressionStatement(node);
81605                 case 200 /* ParenthesizedExpression */:
81606                     return visitParenthesizedExpression(node, noDestructuringValue);
81607                 case 198 /* TaggedTemplateExpression */:
81608                     return visitTaggedTemplateExpression(node);
81609                 case 194 /* PropertyAccessExpression */:
81610                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
81611                         capturedSuperProperties.set(node.name.escapedText, true);
81612                     }
81613                     return ts.visitEachChild(node, visitor, context);
81614                 case 195 /* ElementAccessExpression */:
81615                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
81616                         hasSuperElementAccess = true;
81617                     }
81618                     return ts.visitEachChild(node, visitor, context);
81619                 case 245 /* ClassDeclaration */:
81620                 case 214 /* ClassExpression */:
81621                     return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81622                 default:
81623                     return ts.visitEachChild(node, visitor, context);
81624             }
81625         }
81626         function visitAwaitExpression(node) {
81627             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81628                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), 
81629                 /*location*/ node), node);
81630             }
81631             return ts.visitEachChild(node, visitor, context);
81632         }
81633         function visitYieldExpression(node) {
81634             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81635                 if (node.asteriskToken) {
81636                     var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81637                     return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
81638                 }
81639                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
81640                     ? ts.visitNode(node.expression, visitor, ts.isExpression)
81641                     : ts.createVoidZero())), node), node);
81642             }
81643             return ts.visitEachChild(node, visitor, context);
81644         }
81645         function visitReturnStatement(node) {
81646             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81647                 return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero()));
81648             }
81649             return ts.visitEachChild(node, visitor, context);
81650         }
81651         function visitLabeledStatement(node) {
81652             if (enclosingFunctionFlags & 2 /* Async */) {
81653                 var statement = ts.unwrapInnermostStatementOfLabel(node);
81654                 if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) {
81655                     return visitForOfStatement(statement, node);
81656                 }
81657                 return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node);
81658             }
81659             return ts.visitEachChild(node, visitor, context);
81660         }
81661         function chunkObjectLiteralElements(elements) {
81662             var chunkObject;
81663             var objects = [];
81664             for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
81665                 var e = elements_4[_i];
81666                 if (e.kind === 283 /* SpreadAssignment */) {
81667                     if (chunkObject) {
81668                         objects.push(ts.createObjectLiteral(chunkObject));
81669                         chunkObject = undefined;
81670                     }
81671                     var target = e.expression;
81672                     objects.push(ts.visitNode(target, visitor, ts.isExpression));
81673                 }
81674                 else {
81675                     chunkObject = ts.append(chunkObject, e.kind === 281 /* PropertyAssignment */
81676                         ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
81677                         : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
81678                 }
81679             }
81680             if (chunkObject) {
81681                 objects.push(ts.createObjectLiteral(chunkObject));
81682             }
81683             return objects;
81684         }
81685         function visitObjectLiteralExpression(node) {
81686             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81687                 // spread elements emit like so:
81688                 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
81689                 //     { a, ...o, b } => __assign(__assign({a}, o), {b});
81690                 // If the first element is a spread element, then the first argument to __assign is {}:
81691                 //     { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
81692                 //
81693                 // We cannot call __assign with more than two elements, since any element could cause side effects. For
81694                 // example:
81695                 //      var k = { a: 1, b: 2 };
81696                 //      var o = { a: 3, ...k, b: k.a++ };
81697                 //      // expected: { a: 1, b: 1 }
81698                 // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
81699                 // `k` is spread and we end up with `{ a: 2, b: 1 }`.
81700                 //
81701                 // This also occurs for spread elements, not just property assignments:
81702                 //      var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
81703                 //      var l = { c: 3 };
81704                 //      var o = { ...k, ...l };
81705                 //      // expected: { a: 1, b: 2, z: 9 }
81706                 // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
81707                 // end up with `{ a: 1, b: 2, c: 3 }`
81708                 var objects = chunkObjectLiteralElements(node.properties);
81709                 if (objects.length && objects[0].kind !== 193 /* ObjectLiteralExpression */) {
81710                     objects.unshift(ts.createObjectLiteral());
81711                 }
81712                 var expression = objects[0];
81713                 if (objects.length > 1) {
81714                     for (var i = 1; i < objects.length; i++) {
81715                         expression = createAssignHelper(context, [expression, objects[i]]);
81716                     }
81717                     return expression;
81718                 }
81719                 else {
81720                     return createAssignHelper(context, objects);
81721                 }
81722             }
81723             return ts.visitEachChild(node, visitor, context);
81724         }
81725         function visitExpressionStatement(node) {
81726             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81727         }
81728         function visitParenthesizedExpression(node, noDestructuringValue) {
81729             return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
81730         }
81731         function visitSourceFile(node) {
81732             var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ?
81733                 0 /* StrictModeSourceFileIncludes */ :
81734                 1 /* SourceFileIncludes */);
81735             exportedVariableStatement = false;
81736             var visited = ts.visitEachChild(node, visitor, context);
81737             var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [
81738                 ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))
81739             ]);
81740             var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements));
81741             exitSubtree(ancestorFacts);
81742             return result;
81743         }
81744         function visitTaggedTemplateExpression(node) {
81745             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction);
81746         }
81747         /**
81748          * Visits a BinaryExpression that contains a destructuring assignment.
81749          *
81750          * @param node A BinaryExpression node.
81751          */
81752         function visitBinaryExpression(node, noDestructuringValue) {
81753             if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81754                 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
81755             }
81756             else if (node.operatorToken.kind === 27 /* CommaToken */) {
81757                 return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression));
81758             }
81759             return ts.visitEachChild(node, visitor, context);
81760         }
81761         function visitCatchClause(node) {
81762             if (node.variableDeclaration &&
81763                 ts.isBindingPattern(node.variableDeclaration.name) &&
81764                 node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81765                 var name = ts.getGeneratedNameForNode(node.variableDeclaration.name);
81766                 var updatedDecl = ts.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*type*/ undefined, name);
81767                 var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
81768                 var block = ts.visitNode(node.block, visitor, ts.isBlock);
81769                 if (ts.some(visitedBindings)) {
81770                     block = ts.updateBlock(block, __spreadArrays([
81771                         ts.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
81772                     ], block.statements));
81773                 }
81774                 return ts.updateCatchClause(node, ts.updateVariableDeclaration(node.variableDeclaration, name, /*type*/ undefined, /*initializer*/ undefined), block);
81775             }
81776             return ts.visitEachChild(node, visitor, context);
81777         }
81778         function visitVariableStatement(node) {
81779             if (ts.hasModifier(node, 1 /* Export */)) {
81780                 var savedExportedVariableStatement = exportedVariableStatement;
81781                 exportedVariableStatement = true;
81782                 var visited = ts.visitEachChild(node, visitor, context);
81783                 exportedVariableStatement = savedExportedVariableStatement;
81784                 return visited;
81785             }
81786             return ts.visitEachChild(node, visitor, context);
81787         }
81788         /**
81789          * Visits a VariableDeclaration node with a binding pattern.
81790          *
81791          * @param node A VariableDeclaration node.
81792          */
81793         function visitVariableDeclaration(node) {
81794             if (exportedVariableStatement) {
81795                 var savedExportedVariableStatement = exportedVariableStatement;
81796                 exportedVariableStatement = false;
81797                 var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
81798                 exportedVariableStatement = savedExportedVariableStatement;
81799                 return visited;
81800             }
81801             return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
81802         }
81803         function visitVariableDeclarationWorker(node, exportedVariableStatement) {
81804             // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
81805             if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81806                 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, 
81807                 /*rval*/ undefined, exportedVariableStatement);
81808             }
81809             return ts.visitEachChild(node, visitor, context);
81810         }
81811         function visitForStatement(node) {
81812             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));
81813         }
81814         function visitVoidExpression(node) {
81815             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81816         }
81817         /**
81818          * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
81819          *
81820          * @param node A ForOfStatement.
81821          */
81822         function visitForOfStatement(node, outermostLabeledStatement) {
81823             var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81824             if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81825                 node = transformForOfStatementWithObjectRest(node);
81826             }
81827             var result = node.awaitModifier ?
81828                 transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
81829                 ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
81830             exitSubtree(ancestorFacts);
81831             return result;
81832         }
81833         function transformForOfStatementWithObjectRest(node) {
81834             var initializerWithoutParens = ts.skipParentheses(node.initializer);
81835             if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
81836                 var bodyLocation = void 0;
81837                 var statementsLocation = void 0;
81838                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
81839                 var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)];
81840                 if (ts.isBlock(node.statement)) {
81841                     ts.addRange(statements, node.statement.statements);
81842                     bodyLocation = node.statement;
81843                     statementsLocation = node.statement.statements;
81844                 }
81845                 else if (node.statement) {
81846                     ts.append(statements, node.statement);
81847                     bodyLocation = node.statement;
81848                     statementsLocation = node.statement;
81849                 }
81850                 return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([
81851                     ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer)
81852                 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
81853                 /*multiLine*/ true), bodyLocation));
81854             }
81855             return node;
81856         }
81857         function convertForOfStatementHead(node, boundValue) {
81858             var binding = ts.createForOfBindingStatement(node.initializer, boundValue);
81859             var bodyLocation;
81860             var statementsLocation;
81861             var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
81862             var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
81863             if (ts.isBlock(statement)) {
81864                 ts.addRange(statements, statement.statements);
81865                 bodyLocation = statement;
81866                 statementsLocation = statement.statements;
81867             }
81868             else {
81869                 statements.push(statement);
81870             }
81871             return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
81872             /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
81873         }
81874         function createDownlevelAwait(expression) {
81875             return enclosingFunctionFlags & 1 /* Generator */
81876                 ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression))
81877                 : ts.createAwait(expression);
81878         }
81879         function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
81880             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81881             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
81882             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
81883             var errorRecord = ts.createUniqueName("e");
81884             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
81885             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
81886             var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
81887             var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
81888             var getDone = ts.createPropertyAccess(result, "done");
81889             var getValue = ts.createPropertyAccess(result, "value");
81890             var callReturn = ts.createFunctionCall(returnMethod, iterator, []);
81891             hoistVariableDeclaration(errorRecord);
81892             hoistVariableDeclaration(returnMethod);
81893             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
81894             var initializer = ancestorFacts & 2 /* IterationContainer */ ?
81895                 ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) :
81896                 callValues;
81897             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
81898             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
81899                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
81900                 ts.createVariableDeclaration(result)
81901             ]), node.expression), 2097152 /* NoHoisting */), 
81902             /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), 
81903             /*incrementor*/ undefined, 
81904             /*statement*/ convertForOfStatementHead(node, getValue)), 
81905             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
81906             return ts.createTry(ts.createBlock([
81907                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
81908             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
81909                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
81910                     ts.createPropertyAssignment("error", catchVariable)
81911                 ])))
81912             ]), 1 /* SingleLine */)), ts.createBlock([
81913                 ts.createTry(
81914                 /*tryBlock*/ ts.createBlock([
81915                     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 */)
81916                 ]), 
81917                 /*catchClause*/ undefined, 
81918                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
81919                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
81920                 ]), 1 /* SingleLine */))
81921             ]));
81922         }
81923         function visitParameter(node) {
81924             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81925                 // Binding patterns are converted into a generated name and are
81926                 // evaluated inside the function body.
81927                 return ts.updateParameter(node, 
81928                 /*decorators*/ undefined, 
81929                 /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), 
81930                 /*questionToken*/ undefined, 
81931                 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
81932             }
81933             return ts.visitEachChild(node, visitor, context);
81934         }
81935         function visitConstructorDeclaration(node) {
81936             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81937             enclosingFunctionFlags = 0 /* Normal */;
81938             var updated = ts.updateConstructor(node, 
81939             /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
81940             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81941             return updated;
81942         }
81943         function visitGetAccessorDeclaration(node) {
81944             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81945             enclosingFunctionFlags = 0 /* Normal */;
81946             var updated = ts.updateGetAccessor(node, 
81947             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), 
81948             /*type*/ undefined, transformFunctionBody(node));
81949             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81950             return updated;
81951         }
81952         function visitSetAccessorDeclaration(node) {
81953             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81954             enclosingFunctionFlags = 0 /* Normal */;
81955             var updated = ts.updateSetAccessor(node, 
81956             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
81957             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81958             return updated;
81959         }
81960         function visitMethodDeclaration(node) {
81961             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81962             enclosingFunctionFlags = ts.getFunctionFlags(node);
81963             var updated = ts.updateMethod(node, 
81964             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
81965                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
81966                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
81967                 ? undefined
81968                 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), 
81969             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81970             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
81971                 ? transformAsyncGeneratorFunctionBody(node)
81972                 : transformFunctionBody(node));
81973             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81974             return updated;
81975         }
81976         function visitFunctionDeclaration(node) {
81977             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81978             enclosingFunctionFlags = ts.getFunctionFlags(node);
81979             var updated = ts.updateFunctionDeclaration(node, 
81980             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
81981                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
81982                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
81983                 ? undefined
81984                 : node.asteriskToken, node.name, 
81985             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81986             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
81987                 ? transformAsyncGeneratorFunctionBody(node)
81988                 : transformFunctionBody(node));
81989             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81990             return updated;
81991         }
81992         function visitArrowFunction(node) {
81993             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81994             enclosingFunctionFlags = ts.getFunctionFlags(node);
81995             var updated = ts.updateArrowFunction(node, node.modifiers, 
81996             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81997             /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
81998             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81999             return updated;
82000         }
82001         function visitFunctionExpression(node) {
82002             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82003             enclosingFunctionFlags = ts.getFunctionFlags(node);
82004             var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
82005                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
82006                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
82007                 ? undefined
82008                 : node.asteriskToken, node.name, 
82009             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
82010             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
82011                 ? transformAsyncGeneratorFunctionBody(node)
82012                 : transformFunctionBody(node));
82013             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82014             return updated;
82015         }
82016         function transformAsyncGeneratorFunctionBody(node) {
82017             resumeLexicalEnvironment();
82018             var statements = [];
82019             var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
82020             appendObjectRestAssignmentsIfNeeded(statements, node);
82021             var savedCapturedSuperProperties = capturedSuperProperties;
82022             var savedHasSuperElementAccess = hasSuperElementAccess;
82023             capturedSuperProperties = ts.createUnderscoreEscapedMap();
82024             hasSuperElementAccess = false;
82025             var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(
82026             /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), 
82027             /*typeParameters*/ undefined, 
82028             /*parameters*/ [], 
82029             /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */)));
82030             // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
82031             // This step isn't needed if we eventually transform this to ES5.
82032             var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
82033             if (emitSuperHelpers) {
82034                 enableSubstitutionForAsyncMethodsWithSuper();
82035                 var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
82036                 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
82037                 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
82038             }
82039             statements.push(returnStatement);
82040             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
82041             var block = ts.updateBlock(node.body, statements);
82042             if (emitSuperHelpers && hasSuperElementAccess) {
82043                 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
82044                     ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
82045                 }
82046                 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
82047                     ts.addEmitHelper(block, ts.asyncSuperHelper);
82048                 }
82049             }
82050             capturedSuperProperties = savedCapturedSuperProperties;
82051             hasSuperElementAccess = savedHasSuperElementAccess;
82052             return block;
82053         }
82054         function transformFunctionBody(node) {
82055             resumeLexicalEnvironment();
82056             var statementOffset = 0;
82057             var statements = [];
82058             var body = ts.visitNode(node.body, visitor, ts.isConciseBody);
82059             if (ts.isBlock(body)) {
82060                 statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
82061             }
82062             ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
82063             var leadingStatements = endLexicalEnvironment();
82064             if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
82065                 var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
82066                 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
82067                 ts.addRange(statements, block.statements.slice(statementOffset));
82068                 return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
82069             }
82070             return body;
82071         }
82072         function appendObjectRestAssignmentsIfNeeded(statements, node) {
82073             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
82074                 var parameter = _a[_i];
82075                 if (parameter.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
82076                     var temp = ts.getGeneratedNameForNode(parameter);
82077                     var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, 
82078                     /*doNotRecordTempVariablesInLine*/ false, 
82079                     /*skipInitializer*/ true);
82080                     if (ts.some(declarations)) {
82081                         var statement = ts.createVariableStatement(
82082                         /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations));
82083                         ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
82084                         statements = ts.append(statements, statement);
82085                     }
82086                 }
82087             }
82088             return statements;
82089         }
82090         function enableSubstitutionForAsyncMethodsWithSuper() {
82091             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
82092                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
82093                 // We need to enable substitutions for call, property access, and element access
82094                 // if we need to rewrite super calls.
82095                 context.enableSubstitution(196 /* CallExpression */);
82096                 context.enableSubstitution(194 /* PropertyAccessExpression */);
82097                 context.enableSubstitution(195 /* ElementAccessExpression */);
82098                 // We need to be notified when entering and exiting declarations that bind super.
82099                 context.enableEmitNotification(245 /* ClassDeclaration */);
82100                 context.enableEmitNotification(161 /* MethodDeclaration */);
82101                 context.enableEmitNotification(163 /* GetAccessor */);
82102                 context.enableEmitNotification(164 /* SetAccessor */);
82103                 context.enableEmitNotification(162 /* Constructor */);
82104                 // We need to be notified when entering the generated accessor arrow functions.
82105                 context.enableEmitNotification(225 /* VariableStatement */);
82106             }
82107         }
82108         /**
82109          * Called by the printer just before a node is printed.
82110          *
82111          * @param hint A hint as to the intended usage of the node.
82112          * @param node The node to be printed.
82113          * @param emitCallback The callback used to emit the node.
82114          */
82115         function onEmitNode(hint, node, emitCallback) {
82116             // If we need to support substitutions for `super` in an async method,
82117             // we should track it here.
82118             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
82119                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
82120                 if (superContainerFlags !== enclosingSuperContainerFlags) {
82121                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82122                     enclosingSuperContainerFlags = superContainerFlags;
82123                     previousOnEmitNode(hint, node, emitCallback);
82124                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82125                     return;
82126                 }
82127             }
82128             // Disable substitution in the generated super accessor itself.
82129             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
82130                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82131                 enclosingSuperContainerFlags = 0;
82132                 previousOnEmitNode(hint, node, emitCallback);
82133                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82134                 return;
82135             }
82136             previousOnEmitNode(hint, node, emitCallback);
82137         }
82138         /**
82139          * Hooks node substitutions.
82140          *
82141          * @param hint The context for the emitter.
82142          * @param node The node to substitute.
82143          */
82144         function onSubstituteNode(hint, node) {
82145             node = previousOnSubstituteNode(hint, node);
82146             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
82147                 return substituteExpression(node);
82148             }
82149             return node;
82150         }
82151         function substituteExpression(node) {
82152             switch (node.kind) {
82153                 case 194 /* PropertyAccessExpression */:
82154                     return substitutePropertyAccessExpression(node);
82155                 case 195 /* ElementAccessExpression */:
82156                     return substituteElementAccessExpression(node);
82157                 case 196 /* CallExpression */:
82158                     return substituteCallExpression(node);
82159             }
82160             return node;
82161         }
82162         function substitutePropertyAccessExpression(node) {
82163             if (node.expression.kind === 102 /* SuperKeyword */) {
82164                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
82165             }
82166             return node;
82167         }
82168         function substituteElementAccessExpression(node) {
82169             if (node.expression.kind === 102 /* SuperKeyword */) {
82170                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
82171             }
82172             return node;
82173         }
82174         function substituteCallExpression(node) {
82175             var expression = node.expression;
82176             if (ts.isSuperProperty(expression)) {
82177                 var argumentExpression = ts.isPropertyAccessExpression(expression)
82178                     ? substitutePropertyAccessExpression(expression)
82179                     : substituteElementAccessExpression(expression);
82180                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
82181                 /*typeArguments*/ undefined, __spreadArrays([
82182                     ts.createThis()
82183                 ], node.arguments));
82184             }
82185             return node;
82186         }
82187         function isSuperContainer(node) {
82188             var kind = node.kind;
82189             return kind === 245 /* ClassDeclaration */
82190                 || kind === 162 /* Constructor */
82191                 || kind === 161 /* MethodDeclaration */
82192                 || kind === 163 /* GetAccessor */
82193                 || kind === 164 /* SetAccessor */;
82194         }
82195         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
82196             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
82197                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), 
82198                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
82199             }
82200             else {
82201                 return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), 
82202                 /*typeArguments*/ undefined, [argumentExpression]), location);
82203             }
82204         }
82205     }
82206     ts.transformES2018 = transformES2018;
82207     ts.assignHelper = {
82208         name: "typescript:assign",
82209         importName: "__assign",
82210         scoped: false,
82211         priority: 1,
82212         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            };"
82213     };
82214     function createAssignHelper(context, attributesSegments) {
82215         if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
82216             return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), /*typeArguments*/ undefined, attributesSegments);
82217         }
82218         context.requestEmitHelper(ts.assignHelper);
82219         return ts.createCall(ts.getUnscopedHelperName("__assign"), 
82220         /*typeArguments*/ undefined, attributesSegments);
82221     }
82222     ts.createAssignHelper = createAssignHelper;
82223     ts.awaitHelper = {
82224         name: "typescript:await",
82225         importName: "__await",
82226         scoped: false,
82227         text: "\n            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
82228     };
82229     function createAwaitHelper(context, expression) {
82230         context.requestEmitHelper(ts.awaitHelper);
82231         return ts.createCall(ts.getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
82232     }
82233     ts.asyncGeneratorHelper = {
82234         name: "typescript:asyncGenerator",
82235         importName: "__asyncGenerator",
82236         scoped: false,
82237         dependencies: [ts.awaitHelper],
82238         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            };"
82239     };
82240     function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) {
82241         context.requestEmitHelper(ts.asyncGeneratorHelper);
82242         // Mark this node as originally an async function
82243         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
82244         return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), 
82245         /*typeArguments*/ undefined, [
82246             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
82247             ts.createIdentifier("arguments"),
82248             generatorFunc
82249         ]);
82250     }
82251     ts.asyncDelegator = {
82252         name: "typescript:asyncDelegator",
82253         importName: "__asyncDelegator",
82254         scoped: false,
82255         dependencies: [ts.awaitHelper],
82256         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            };"
82257     };
82258     function createAsyncDelegatorHelper(context, expression, location) {
82259         context.requestEmitHelper(ts.asyncDelegator);
82260         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncDelegator"), 
82261         /*typeArguments*/ undefined, [expression]), location);
82262     }
82263     ts.asyncValues = {
82264         name: "typescript:asyncValues",
82265         importName: "__asyncValues",
82266         scoped: false,
82267         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            };"
82268     };
82269     function createAsyncValuesHelper(context, expression, location) {
82270         context.requestEmitHelper(ts.asyncValues);
82271         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncValues"), 
82272         /*typeArguments*/ undefined, [expression]), location);
82273     }
82274 })(ts || (ts = {}));
82275 /*@internal*/
82276 var ts;
82277 (function (ts) {
82278     function transformES2019(context) {
82279         return ts.chainBundle(transformSourceFile);
82280         function transformSourceFile(node) {
82281             if (node.isDeclarationFile) {
82282                 return node;
82283             }
82284             return ts.visitEachChild(node, visitor, context);
82285         }
82286         function visitor(node) {
82287             if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) {
82288                 return node;
82289             }
82290             switch (node.kind) {
82291                 case 280 /* CatchClause */:
82292                     return visitCatchClause(node);
82293                 default:
82294                     return ts.visitEachChild(node, visitor, context);
82295             }
82296         }
82297         function visitCatchClause(node) {
82298             if (!node.variableDeclaration) {
82299                 return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
82300             }
82301             return ts.visitEachChild(node, visitor, context);
82302         }
82303     }
82304     ts.transformES2019 = transformES2019;
82305 })(ts || (ts = {}));
82306 /*@internal*/
82307 var ts;
82308 (function (ts) {
82309     function transformES2020(context) {
82310         var hoistVariableDeclaration = context.hoistVariableDeclaration;
82311         return ts.chainBundle(transformSourceFile);
82312         function transformSourceFile(node) {
82313             if (node.isDeclarationFile) {
82314                 return node;
82315             }
82316             return ts.visitEachChild(node, visitor, context);
82317         }
82318         function visitor(node) {
82319             if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) {
82320                 return node;
82321             }
82322             switch (node.kind) {
82323                 case 194 /* PropertyAccessExpression */:
82324                 case 195 /* ElementAccessExpression */:
82325                 case 196 /* CallExpression */:
82326                     if (node.flags & 32 /* OptionalChain */) {
82327                         var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
82328                         ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
82329                         return updated;
82330                     }
82331                     return ts.visitEachChild(node, visitor, context);
82332                 case 209 /* BinaryExpression */:
82333                     if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
82334                         return transformNullishCoalescingExpression(node);
82335                     }
82336                     return ts.visitEachChild(node, visitor, context);
82337                 case 203 /* DeleteExpression */:
82338                     return visitDeleteExpression(node);
82339                 default:
82340                     return ts.visitEachChild(node, visitor, context);
82341             }
82342         }
82343         function flattenChain(chain) {
82344             ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82345             var links = [chain];
82346             while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
82347                 chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain);
82348                 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82349                 links.unshift(chain);
82350             }
82351             return { expression: chain.expression, chain: links };
82352         }
82353         function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
82354             var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
82355             if (ts.isSyntheticReference(expression)) {
82356                 // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
82357                 // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
82358                 return ts.createSyntheticReferenceExpression(ts.updateParen(node, expression.expression), expression.thisArg);
82359             }
82360             return ts.updateParen(node, expression);
82361         }
82362         function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
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);
82366             }
82367             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
82368             ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
82369             var thisArg;
82370             if (captureThisArg) {
82371                 if (shouldCaptureInTempVariable(expression)) {
82372                     thisArg = ts.createTempVariable(hoistVariableDeclaration);
82373                     expression = ts.createAssignment(thisArg, expression);
82374                     // if (inParameterInitializer) tempVariableInParameter = true;
82375                 }
82376                 else {
82377                     thisArg = expression;
82378                 }
82379             }
82380             expression = node.kind === 194 /* PropertyAccessExpression */
82381                 ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
82382                 : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
82383             return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression;
82384         }
82385         function visitNonOptionalCallExpression(node, captureThisArg) {
82386             if (ts.isOptionalChain(node)) {
82387                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
82388                 return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
82389             }
82390             return ts.visitEachChild(node, visitor, context);
82391         }
82392         function visitNonOptionalExpression(node, captureThisArg, isDelete) {
82393             switch (node.kind) {
82394                 case 200 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
82395                 case 194 /* PropertyAccessExpression */:
82396                 case 195 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
82397                 case 196 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
82398                 default: return ts.visitNode(node, visitor, ts.isExpression);
82399             }
82400         }
82401         function visitOptionalExpression(node, captureThisArg, isDelete) {
82402             var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
82403             var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
82404             var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
82405             var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
82406             var capturedLeft = leftExpression;
82407             if (shouldCaptureInTempVariable(leftExpression)) {
82408                 capturedLeft = ts.createTempVariable(hoistVariableDeclaration);
82409                 leftExpression = ts.createAssignment(capturedLeft, leftExpression);
82410                 // if (inParameterInitializer) tempVariableInParameter = true;
82411             }
82412             var rightExpression = capturedLeft;
82413             var thisArg;
82414             for (var i = 0; i < chain.length; i++) {
82415                 var segment = chain[i];
82416                 switch (segment.kind) {
82417                     case 194 /* PropertyAccessExpression */:
82418                     case 195 /* ElementAccessExpression */:
82419                         if (i === chain.length - 1 && captureThisArg) {
82420                             if (shouldCaptureInTempVariable(rightExpression)) {
82421                                 thisArg = ts.createTempVariable(hoistVariableDeclaration);
82422                                 rightExpression = ts.createAssignment(thisArg, rightExpression);
82423                                 // if (inParameterInitializer) tempVariableInParameter = true;
82424                             }
82425                             else {
82426                                 thisArg = rightExpression;
82427                             }
82428                         }
82429                         rightExpression = segment.kind === 194 /* PropertyAccessExpression */
82430                             ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
82431                             : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
82432                         break;
82433                     case 196 /* CallExpression */:
82434                         if (i === 0 && leftThisArg) {
82435                             rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 102 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82436                         }
82437                         else {
82438                             rightExpression = ts.createCall(rightExpression, 
82439                             /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82440                         }
82441                         break;
82442                 }
82443                 ts.setOriginalNode(rightExpression, segment);
82444             }
82445             var target = isDelete
82446                 ? ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createTrue(), ts.createDelete(rightExpression))
82447                 : ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression);
82448             return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target;
82449         }
82450         function createNotNullCondition(left, right, invert) {
82451             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()));
82452         }
82453         function transformNullishCoalescingExpression(node) {
82454             var left = ts.visitNode(node.left, visitor, ts.isExpression);
82455             var right = left;
82456             if (shouldCaptureInTempVariable(left)) {
82457                 right = ts.createTempVariable(hoistVariableDeclaration);
82458                 left = ts.createAssignment(right, left);
82459                 // if (inParameterInitializer) tempVariableInParameter = true;
82460             }
82461             return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression));
82462         }
82463         function shouldCaptureInTempVariable(expression) {
82464             // don't capture identifiers and `this` in a temporary variable
82465             // `super` cannot be captured as it's no real variable
82466             return !ts.isIdentifier(expression) &&
82467                 expression.kind !== 104 /* ThisKeyword */ &&
82468                 expression.kind !== 102 /* SuperKeyword */;
82469         }
82470         function visitDeleteExpression(node) {
82471             return ts.isOptionalChain(ts.skipParentheses(node.expression))
82472                 ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
82473                 : ts.updateDelete(node, ts.visitNode(node.expression, visitor, ts.isExpression));
82474         }
82475     }
82476     ts.transformES2020 = transformES2020;
82477 })(ts || (ts = {}));
82478 /*@internal*/
82479 var ts;
82480 (function (ts) {
82481     function transformESNext(context) {
82482         return ts.chainBundle(transformSourceFile);
82483         function transformSourceFile(node) {
82484             if (node.isDeclarationFile) {
82485                 return node;
82486             }
82487             return ts.visitEachChild(node, visitor, context);
82488         }
82489         function visitor(node) {
82490             if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
82491                 return node;
82492             }
82493             switch (node.kind) {
82494                 default:
82495                     return ts.visitEachChild(node, visitor, context);
82496             }
82497         }
82498     }
82499     ts.transformESNext = transformESNext;
82500 })(ts || (ts = {}));
82501 /*@internal*/
82502 var ts;
82503 (function (ts) {
82504     function transformJsx(context) {
82505         var compilerOptions = context.getCompilerOptions();
82506         var currentSourceFile;
82507         return ts.chainBundle(transformSourceFile);
82508         /**
82509          * Transform JSX-specific syntax in a SourceFile.
82510          *
82511          * @param node A SourceFile node.
82512          */
82513         function transformSourceFile(node) {
82514             if (node.isDeclarationFile) {
82515                 return node;
82516             }
82517             currentSourceFile = node;
82518             var visited = ts.visitEachChild(node, visitor, context);
82519             ts.addEmitHelpers(visited, context.readEmitHelpers());
82520             return visited;
82521         }
82522         function visitor(node) {
82523             if (node.transformFlags & 2 /* ContainsJsx */) {
82524                 return visitorWorker(node);
82525             }
82526             else {
82527                 return node;
82528             }
82529         }
82530         function visitorWorker(node) {
82531             switch (node.kind) {
82532                 case 266 /* JsxElement */:
82533                     return visitJsxElement(node, /*isChild*/ false);
82534                 case 267 /* JsxSelfClosingElement */:
82535                     return visitJsxSelfClosingElement(node, /*isChild*/ false);
82536                 case 270 /* JsxFragment */:
82537                     return visitJsxFragment(node, /*isChild*/ false);
82538                 case 276 /* JsxExpression */:
82539                     return visitJsxExpression(node);
82540                 default:
82541                     return ts.visitEachChild(node, visitor, context);
82542             }
82543         }
82544         function transformJsxChildToExpression(node) {
82545             switch (node.kind) {
82546                 case 11 /* JsxText */:
82547                     return visitJsxText(node);
82548                 case 276 /* JsxExpression */:
82549                     return visitJsxExpression(node);
82550                 case 266 /* JsxElement */:
82551                     return visitJsxElement(node, /*isChild*/ true);
82552                 case 267 /* JsxSelfClosingElement */:
82553                     return visitJsxSelfClosingElement(node, /*isChild*/ true);
82554                 case 270 /* JsxFragment */:
82555                     return visitJsxFragment(node, /*isChild*/ true);
82556                 default:
82557                     return ts.Debug.failBadSyntaxKind(node);
82558             }
82559         }
82560         function visitJsxElement(node, isChild) {
82561             return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
82562         }
82563         function visitJsxSelfClosingElement(node, isChild) {
82564             return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
82565         }
82566         function visitJsxFragment(node, isChild) {
82567             return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
82568         }
82569         function visitJsxOpeningLikeElement(node, children, isChild, location) {
82570             var tagName = getTagName(node);
82571             var objectProperties;
82572             var attrs = node.attributes.properties;
82573             if (attrs.length === 0) {
82574                 // When there are no attributes, React wants "null"
82575                 objectProperties = ts.createNull();
82576             }
82577             else {
82578                 // Map spans of JsxAttribute nodes into object literals and spans
82579                 // of JsxSpreadAttribute nodes into expressions.
82580                 var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
82581                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
82582                     : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
82583                 if (ts.isJsxSpreadAttribute(attrs[0])) {
82584                     // We must always emit at least one object literal before a spread
82585                     // argument.
82586                     segments.unshift(ts.createObjectLiteral());
82587                 }
82588                 // Either emit one big object literal (no spread attribs), or
82589                 // a call to the __assign helper.
82590                 objectProperties = ts.singleOrUndefined(segments);
82591                 if (!objectProperties) {
82592                     objectProperties = ts.createAssignHelper(context, segments);
82593                 }
82594             }
82595             var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82596             tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
82597             if (isChild) {
82598                 ts.startOnNewLine(element);
82599             }
82600             return element;
82601         }
82602         function visitJsxOpeningFragment(node, children, isChild, location) {
82603             var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82604             ts.mapDefined(children, transformJsxChildToExpression), node, location);
82605             if (isChild) {
82606                 ts.startOnNewLine(element);
82607             }
82608             return element;
82609         }
82610         function transformJsxSpreadAttributeToExpression(node) {
82611             return ts.visitNode(node.expression, visitor, ts.isExpression);
82612         }
82613         function transformJsxAttributeToObjectLiteralElement(node) {
82614             var name = getAttributeName(node);
82615             var expression = transformJsxAttributeInitializer(node.initializer);
82616             return ts.createPropertyAssignment(name, expression);
82617         }
82618         function transformJsxAttributeInitializer(node) {
82619             if (node === undefined) {
82620                 return ts.createTrue();
82621             }
82622             else if (node.kind === 10 /* StringLiteral */) {
82623                 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
82624                 // Need to be escaped to be handled correctly in a normal string
82625                 var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text);
82626                 literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
82627                 return ts.setTextRange(literal, node);
82628             }
82629             else if (node.kind === 276 /* JsxExpression */) {
82630                 if (node.expression === undefined) {
82631                     return ts.createTrue();
82632                 }
82633                 return visitJsxExpression(node);
82634             }
82635             else {
82636                 return ts.Debug.failBadSyntaxKind(node);
82637             }
82638         }
82639         function visitJsxText(node) {
82640             var fixed = fixupWhitespaceAndDecodeEntities(node.text);
82641             return fixed === undefined ? undefined : ts.createLiteral(fixed);
82642         }
82643         /**
82644          * JSX trims whitespace at the end and beginning of lines, except that the
82645          * start/end of a tag is considered a start/end of a line only if that line is
82646          * on the same line as the closing tag. See examples in
82647          * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
82648          * 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
82649          *
82650          * An equivalent algorithm would be:
82651          * - If there is only one line, return it.
82652          * - If there is only whitespace (but multiple lines), return `undefined`.
82653          * - Split the text into lines.
82654          * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
82655          * - Decode entities on each line (individually).
82656          * - Remove empty lines and join the rest with " ".
82657          */
82658         function fixupWhitespaceAndDecodeEntities(text) {
82659             var acc;
82660             // First non-whitespace character on this line.
82661             var firstNonWhitespace = 0;
82662             // Last non-whitespace character on this line.
82663             var lastNonWhitespace = -1;
82664             // These initial values are special because the first line is:
82665             // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
82666             // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
82667             for (var i = 0; i < text.length; i++) {
82668                 var c = text.charCodeAt(i);
82669                 if (ts.isLineBreak(c)) {
82670                     // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
82671                     // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
82672                     if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
82673                         acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
82674                     }
82675                     // Reset firstNonWhitespace for the next line.
82676                     // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
82677                     firstNonWhitespace = -1;
82678                 }
82679                 else if (!ts.isWhiteSpaceSingleLine(c)) {
82680                     lastNonWhitespace = i;
82681                     if (firstNonWhitespace === -1) {
82682                         firstNonWhitespace = i;
82683                     }
82684                 }
82685             }
82686             return firstNonWhitespace !== -1
82687                 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
82688                 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
82689                 // Last line was all whitespace, so ignore it
82690                 : acc;
82691         }
82692         function addLineOfJsxText(acc, trimmedLine) {
82693             // We do not escape the string here as that is handled by the printer
82694             // when it emits the literal. We do, however, need to decode JSX entities.
82695             var decoded = decodeEntities(trimmedLine);
82696             return acc === undefined ? decoded : acc + " " + decoded;
82697         }
82698         /**
82699          * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
82700          * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
82701          */
82702         function decodeEntities(text) {
82703             return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
82704                 if (decimal) {
82705                     return ts.utf16EncodeAsString(parseInt(decimal, 10));
82706                 }
82707                 else if (hex) {
82708                     return ts.utf16EncodeAsString(parseInt(hex, 16));
82709                 }
82710                 else {
82711                     var ch = entities.get(word);
82712                     // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
82713                     return ch ? ts.utf16EncodeAsString(ch) : match;
82714                 }
82715             });
82716         }
82717         /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
82718         function tryDecodeEntities(text) {
82719             var decoded = decodeEntities(text);
82720             return decoded === text ? undefined : decoded;
82721         }
82722         function getTagName(node) {
82723             if (node.kind === 266 /* JsxElement */) {
82724                 return getTagName(node.openingElement);
82725             }
82726             else {
82727                 var name = node.tagName;
82728                 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
82729                     return ts.createLiteral(ts.idText(name));
82730                 }
82731                 else {
82732                     return ts.createExpressionFromEntityName(name);
82733                 }
82734             }
82735         }
82736         /**
82737          * Emit an attribute name, which is quoted if it needs to be quoted. Because
82738          * these emit into an object literal property name, we don't need to be worried
82739          * about keywords, just non-identifier characters
82740          */
82741         function getAttributeName(node) {
82742             var name = node.name;
82743             var text = ts.idText(name);
82744             if (/^[A-Za-z_]\w*$/.test(text)) {
82745                 return name;
82746             }
82747             else {
82748                 return ts.createLiteral(text);
82749             }
82750         }
82751         function visitJsxExpression(node) {
82752             return ts.visitNode(node.expression, visitor, ts.isExpression);
82753         }
82754     }
82755     ts.transformJsx = transformJsx;
82756     var entities = ts.createMapFromTemplate({
82757         quot: 0x0022,
82758         amp: 0x0026,
82759         apos: 0x0027,
82760         lt: 0x003C,
82761         gt: 0x003E,
82762         nbsp: 0x00A0,
82763         iexcl: 0x00A1,
82764         cent: 0x00A2,
82765         pound: 0x00A3,
82766         curren: 0x00A4,
82767         yen: 0x00A5,
82768         brvbar: 0x00A6,
82769         sect: 0x00A7,
82770         uml: 0x00A8,
82771         copy: 0x00A9,
82772         ordf: 0x00AA,
82773         laquo: 0x00AB,
82774         not: 0x00AC,
82775         shy: 0x00AD,
82776         reg: 0x00AE,
82777         macr: 0x00AF,
82778         deg: 0x00B0,
82779         plusmn: 0x00B1,
82780         sup2: 0x00B2,
82781         sup3: 0x00B3,
82782         acute: 0x00B4,
82783         micro: 0x00B5,
82784         para: 0x00B6,
82785         middot: 0x00B7,
82786         cedil: 0x00B8,
82787         sup1: 0x00B9,
82788         ordm: 0x00BA,
82789         raquo: 0x00BB,
82790         frac14: 0x00BC,
82791         frac12: 0x00BD,
82792         frac34: 0x00BE,
82793         iquest: 0x00BF,
82794         Agrave: 0x00C0,
82795         Aacute: 0x00C1,
82796         Acirc: 0x00C2,
82797         Atilde: 0x00C3,
82798         Auml: 0x00C4,
82799         Aring: 0x00C5,
82800         AElig: 0x00C6,
82801         Ccedil: 0x00C7,
82802         Egrave: 0x00C8,
82803         Eacute: 0x00C9,
82804         Ecirc: 0x00CA,
82805         Euml: 0x00CB,
82806         Igrave: 0x00CC,
82807         Iacute: 0x00CD,
82808         Icirc: 0x00CE,
82809         Iuml: 0x00CF,
82810         ETH: 0x00D0,
82811         Ntilde: 0x00D1,
82812         Ograve: 0x00D2,
82813         Oacute: 0x00D3,
82814         Ocirc: 0x00D4,
82815         Otilde: 0x00D5,
82816         Ouml: 0x00D6,
82817         times: 0x00D7,
82818         Oslash: 0x00D8,
82819         Ugrave: 0x00D9,
82820         Uacute: 0x00DA,
82821         Ucirc: 0x00DB,
82822         Uuml: 0x00DC,
82823         Yacute: 0x00DD,
82824         THORN: 0x00DE,
82825         szlig: 0x00DF,
82826         agrave: 0x00E0,
82827         aacute: 0x00E1,
82828         acirc: 0x00E2,
82829         atilde: 0x00E3,
82830         auml: 0x00E4,
82831         aring: 0x00E5,
82832         aelig: 0x00E6,
82833         ccedil: 0x00E7,
82834         egrave: 0x00E8,
82835         eacute: 0x00E9,
82836         ecirc: 0x00EA,
82837         euml: 0x00EB,
82838         igrave: 0x00EC,
82839         iacute: 0x00ED,
82840         icirc: 0x00EE,
82841         iuml: 0x00EF,
82842         eth: 0x00F0,
82843         ntilde: 0x00F1,
82844         ograve: 0x00F2,
82845         oacute: 0x00F3,
82846         ocirc: 0x00F4,
82847         otilde: 0x00F5,
82848         ouml: 0x00F6,
82849         divide: 0x00F7,
82850         oslash: 0x00F8,
82851         ugrave: 0x00F9,
82852         uacute: 0x00FA,
82853         ucirc: 0x00FB,
82854         uuml: 0x00FC,
82855         yacute: 0x00FD,
82856         thorn: 0x00FE,
82857         yuml: 0x00FF,
82858         OElig: 0x0152,
82859         oelig: 0x0153,
82860         Scaron: 0x0160,
82861         scaron: 0x0161,
82862         Yuml: 0x0178,
82863         fnof: 0x0192,
82864         circ: 0x02C6,
82865         tilde: 0x02DC,
82866         Alpha: 0x0391,
82867         Beta: 0x0392,
82868         Gamma: 0x0393,
82869         Delta: 0x0394,
82870         Epsilon: 0x0395,
82871         Zeta: 0x0396,
82872         Eta: 0x0397,
82873         Theta: 0x0398,
82874         Iota: 0x0399,
82875         Kappa: 0x039A,
82876         Lambda: 0x039B,
82877         Mu: 0x039C,
82878         Nu: 0x039D,
82879         Xi: 0x039E,
82880         Omicron: 0x039F,
82881         Pi: 0x03A0,
82882         Rho: 0x03A1,
82883         Sigma: 0x03A3,
82884         Tau: 0x03A4,
82885         Upsilon: 0x03A5,
82886         Phi: 0x03A6,
82887         Chi: 0x03A7,
82888         Psi: 0x03A8,
82889         Omega: 0x03A9,
82890         alpha: 0x03B1,
82891         beta: 0x03B2,
82892         gamma: 0x03B3,
82893         delta: 0x03B4,
82894         epsilon: 0x03B5,
82895         zeta: 0x03B6,
82896         eta: 0x03B7,
82897         theta: 0x03B8,
82898         iota: 0x03B9,
82899         kappa: 0x03BA,
82900         lambda: 0x03BB,
82901         mu: 0x03BC,
82902         nu: 0x03BD,
82903         xi: 0x03BE,
82904         omicron: 0x03BF,
82905         pi: 0x03C0,
82906         rho: 0x03C1,
82907         sigmaf: 0x03C2,
82908         sigma: 0x03C3,
82909         tau: 0x03C4,
82910         upsilon: 0x03C5,
82911         phi: 0x03C6,
82912         chi: 0x03C7,
82913         psi: 0x03C8,
82914         omega: 0x03C9,
82915         thetasym: 0x03D1,
82916         upsih: 0x03D2,
82917         piv: 0x03D6,
82918         ensp: 0x2002,
82919         emsp: 0x2003,
82920         thinsp: 0x2009,
82921         zwnj: 0x200C,
82922         zwj: 0x200D,
82923         lrm: 0x200E,
82924         rlm: 0x200F,
82925         ndash: 0x2013,
82926         mdash: 0x2014,
82927         lsquo: 0x2018,
82928         rsquo: 0x2019,
82929         sbquo: 0x201A,
82930         ldquo: 0x201C,
82931         rdquo: 0x201D,
82932         bdquo: 0x201E,
82933         dagger: 0x2020,
82934         Dagger: 0x2021,
82935         bull: 0x2022,
82936         hellip: 0x2026,
82937         permil: 0x2030,
82938         prime: 0x2032,
82939         Prime: 0x2033,
82940         lsaquo: 0x2039,
82941         rsaquo: 0x203A,
82942         oline: 0x203E,
82943         frasl: 0x2044,
82944         euro: 0x20AC,
82945         image: 0x2111,
82946         weierp: 0x2118,
82947         real: 0x211C,
82948         trade: 0x2122,
82949         alefsym: 0x2135,
82950         larr: 0x2190,
82951         uarr: 0x2191,
82952         rarr: 0x2192,
82953         darr: 0x2193,
82954         harr: 0x2194,
82955         crarr: 0x21B5,
82956         lArr: 0x21D0,
82957         uArr: 0x21D1,
82958         rArr: 0x21D2,
82959         dArr: 0x21D3,
82960         hArr: 0x21D4,
82961         forall: 0x2200,
82962         part: 0x2202,
82963         exist: 0x2203,
82964         empty: 0x2205,
82965         nabla: 0x2207,
82966         isin: 0x2208,
82967         notin: 0x2209,
82968         ni: 0x220B,
82969         prod: 0x220F,
82970         sum: 0x2211,
82971         minus: 0x2212,
82972         lowast: 0x2217,
82973         radic: 0x221A,
82974         prop: 0x221D,
82975         infin: 0x221E,
82976         ang: 0x2220,
82977         and: 0x2227,
82978         or: 0x2228,
82979         cap: 0x2229,
82980         cup: 0x222A,
82981         int: 0x222B,
82982         there4: 0x2234,
82983         sim: 0x223C,
82984         cong: 0x2245,
82985         asymp: 0x2248,
82986         ne: 0x2260,
82987         equiv: 0x2261,
82988         le: 0x2264,
82989         ge: 0x2265,
82990         sub: 0x2282,
82991         sup: 0x2283,
82992         nsub: 0x2284,
82993         sube: 0x2286,
82994         supe: 0x2287,
82995         oplus: 0x2295,
82996         otimes: 0x2297,
82997         perp: 0x22A5,
82998         sdot: 0x22C5,
82999         lceil: 0x2308,
83000         rceil: 0x2309,
83001         lfloor: 0x230A,
83002         rfloor: 0x230B,
83003         lang: 0x2329,
83004         rang: 0x232A,
83005         loz: 0x25CA,
83006         spades: 0x2660,
83007         clubs: 0x2663,
83008         hearts: 0x2665,
83009         diams: 0x2666
83010     });
83011 })(ts || (ts = {}));
83012 /*@internal*/
83013 var ts;
83014 (function (ts) {
83015     function transformES2016(context) {
83016         var hoistVariableDeclaration = context.hoistVariableDeclaration;
83017         return ts.chainBundle(transformSourceFile);
83018         function transformSourceFile(node) {
83019             if (node.isDeclarationFile) {
83020                 return node;
83021             }
83022             return ts.visitEachChild(node, visitor, context);
83023         }
83024         function visitor(node) {
83025             if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) {
83026                 return node;
83027             }
83028             switch (node.kind) {
83029                 case 209 /* BinaryExpression */:
83030                     return visitBinaryExpression(node);
83031                 default:
83032                     return ts.visitEachChild(node, visitor, context);
83033             }
83034         }
83035         function visitBinaryExpression(node) {
83036             switch (node.operatorToken.kind) {
83037                 case 66 /* AsteriskAsteriskEqualsToken */:
83038                     return visitExponentiationAssignmentExpression(node);
83039                 case 42 /* AsteriskAsteriskToken */:
83040                     return visitExponentiationExpression(node);
83041                 default:
83042                     return ts.visitEachChild(node, visitor, context);
83043             }
83044         }
83045         function visitExponentiationAssignmentExpression(node) {
83046             var target;
83047             var value;
83048             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83049             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83050             if (ts.isElementAccessExpression(left)) {
83051                 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
83052                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83053                 var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83054                 target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
83055                 value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left);
83056             }
83057             else if (ts.isPropertyAccessExpression(left)) {
83058                 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
83059                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83060                 target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
83061                 value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left);
83062             }
83063             else {
83064                 // Transforms `a **= b` into `a = Math.pow(a, b)`
83065                 target = left;
83066                 value = left;
83067             }
83068             return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node);
83069         }
83070         function visitExponentiationExpression(node) {
83071             // Transforms `a ** b` into `Math.pow(a, b)`
83072             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83073             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83074             return ts.createMathPow(left, right, /*location*/ node);
83075         }
83076     }
83077     ts.transformES2016 = transformES2016;
83078 })(ts || (ts = {}));
83079 /*@internal*/
83080 var ts;
83081 (function (ts) {
83082     var ES2015SubstitutionFlags;
83083     (function (ES2015SubstitutionFlags) {
83084         /** Enables substitutions for captured `this` */
83085         ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
83086         /** Enables substitutions for block-scoped bindings. */
83087         ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
83088     })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
83089     var LoopOutParameterFlags;
83090     (function (LoopOutParameterFlags) {
83091         LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
83092         LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
83093     })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
83094     var CopyDirection;
83095     (function (CopyDirection) {
83096         CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
83097         CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
83098     })(CopyDirection || (CopyDirection = {}));
83099     var Jump;
83100     (function (Jump) {
83101         Jump[Jump["Break"] = 2] = "Break";
83102         Jump[Jump["Continue"] = 4] = "Continue";
83103         Jump[Jump["Return"] = 8] = "Return";
83104     })(Jump || (Jump = {}));
83105     // Facts we track as we traverse the tree
83106     var HierarchyFacts;
83107     (function (HierarchyFacts) {
83108         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
83109         //
83110         // Ancestor facts
83111         //
83112         HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
83113         HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
83114         HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
83115         HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
83116         HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
83117         HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
83118         HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
83119         HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
83120         HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
83121         HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
83122         HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
83123         HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
83124         HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
83125         HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
83126         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
83127         // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
83128         //
83129         // Ancestor masks
83130         //
83131         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
83132         // We are always in *some* kind of block scope, but only specific block-scope containers are
83133         // top-level or Blocks.
83134         HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
83135         HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
83136         // A source file is a top-level block scope.
83137         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
83138         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
83139         // Functions, methods, and accessors are both new lexical scopes and new block scopes.
83140         HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
83141         HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
83142         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
83143         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
83144         // Arrow functions are lexically scoped to their container, but are new block scopes.
83145         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
83146         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
83147         // Constructors are both new lexical scopes and new block scopes. Constructors are also
83148         // always considered non-static members of a class.
83149         HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
83150         HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
83151         // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
83152         // within an IterationStatement to indicate whether the embedded statement is an
83153         // IterationStatementBlock.
83154         HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
83155         HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
83156         // 'for' statements are new block scopes and have special handling for 'let' declarations.
83157         HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
83158         HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
83159         // 'for-in' and 'for-of' statements are new block scopes and have special handling for
83160         // 'let' declarations.
83161         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
83162         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
83163         // Blocks (other than function bodies) are new block scopes.
83164         HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
83165         HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
83166         HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
83167         HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
83168         //
83169         // Subtree facts
83170         //
83171         HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
83172         HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 32768] = "CapturedLexicalThis";
83173         //
83174         // Subtree masks
83175         //
83176         HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
83177         HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
83178         HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 49152] = "FunctionSubtreeExcludes";
83179     })(HierarchyFacts || (HierarchyFacts = {}));
83180     function transformES2015(context) {
83181         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
83182         var compilerOptions = context.getCompilerOptions();
83183         var resolver = context.getEmitResolver();
83184         var previousOnSubstituteNode = context.onSubstituteNode;
83185         var previousOnEmitNode = context.onEmitNode;
83186         context.onEmitNode = onEmitNode;
83187         context.onSubstituteNode = onSubstituteNode;
83188         var currentSourceFile;
83189         var currentText;
83190         var hierarchyFacts;
83191         var taggedTemplateStringDeclarations;
83192         function recordTaggedTemplateString(temp) {
83193             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
83194         }
83195         /**
83196          * Used to track if we are emitting body of the converted loop
83197          */
83198         var convertedLoopState;
83199         /**
83200          * Keeps track of whether substitutions have been enabled for specific cases.
83201          * They are persisted between each SourceFile transformation and should not
83202          * be reset.
83203          */
83204         var enabledSubstitutions;
83205         return ts.chainBundle(transformSourceFile);
83206         function transformSourceFile(node) {
83207             if (node.isDeclarationFile) {
83208                 return node;
83209             }
83210             currentSourceFile = node;
83211             currentText = node.text;
83212             var visited = visitSourceFile(node);
83213             ts.addEmitHelpers(visited, context.readEmitHelpers());
83214             currentSourceFile = undefined;
83215             currentText = undefined;
83216             taggedTemplateStringDeclarations = undefined;
83217             hierarchyFacts = 0 /* None */;
83218             return visited;
83219         }
83220         /**
83221          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
83222          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
83223          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
83224          */
83225         function enterSubtree(excludeFacts, includeFacts) {
83226             var ancestorFacts = hierarchyFacts;
83227             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
83228             return ancestorFacts;
83229         }
83230         /**
83231          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
83232          * subtree, propagating specific facts from the subtree.
83233          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
83234          * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
83235          * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
83236          */
83237         function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
83238             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
83239         }
83240         function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
83241             return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
83242                 && node.kind === 235 /* ReturnStatement */
83243                 && !node.expression;
83244         }
83245         function shouldVisitNode(node) {
83246             return (node.transformFlags & 256 /* ContainsES2015 */) !== 0
83247                 || convertedLoopState !== undefined
83248                 || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 223 /* Block */)))
83249                 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
83250                 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
83251         }
83252         function visitor(node) {
83253             if (shouldVisitNode(node)) {
83254                 return visitJavaScript(node);
83255             }
83256             else {
83257                 return node;
83258             }
83259         }
83260         function callExpressionVisitor(node) {
83261             if (node.kind === 102 /* SuperKeyword */) {
83262                 return visitSuperKeyword(/*isExpressionOfCall*/ true);
83263             }
83264             return visitor(node);
83265         }
83266         function visitJavaScript(node) {
83267             switch (node.kind) {
83268                 case 120 /* StaticKeyword */:
83269                     return undefined; // elide static keyword
83270                 case 245 /* ClassDeclaration */:
83271                     return visitClassDeclaration(node);
83272                 case 214 /* ClassExpression */:
83273                     return visitClassExpression(node);
83274                 case 156 /* Parameter */:
83275                     return visitParameter(node);
83276                 case 244 /* FunctionDeclaration */:
83277                     return visitFunctionDeclaration(node);
83278                 case 202 /* ArrowFunction */:
83279                     return visitArrowFunction(node);
83280                 case 201 /* FunctionExpression */:
83281                     return visitFunctionExpression(node);
83282                 case 242 /* VariableDeclaration */:
83283                     return visitVariableDeclaration(node);
83284                 case 75 /* Identifier */:
83285                     return visitIdentifier(node);
83286                 case 243 /* VariableDeclarationList */:
83287                     return visitVariableDeclarationList(node);
83288                 case 237 /* SwitchStatement */:
83289                     return visitSwitchStatement(node);
83290                 case 251 /* CaseBlock */:
83291                     return visitCaseBlock(node);
83292                 case 223 /* Block */:
83293                     return visitBlock(node, /*isFunctionBody*/ false);
83294                 case 234 /* BreakStatement */:
83295                 case 233 /* ContinueStatement */:
83296                     return visitBreakOrContinueStatement(node);
83297                 case 238 /* LabeledStatement */:
83298                     return visitLabeledStatement(node);
83299                 case 228 /* DoStatement */:
83300                 case 229 /* WhileStatement */:
83301                     return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
83302                 case 230 /* ForStatement */:
83303                     return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
83304                 case 231 /* ForInStatement */:
83305                     return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
83306                 case 232 /* ForOfStatement */:
83307                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
83308                 case 226 /* ExpressionStatement */:
83309                     return visitExpressionStatement(node);
83310                 case 193 /* ObjectLiteralExpression */:
83311                     return visitObjectLiteralExpression(node);
83312                 case 280 /* CatchClause */:
83313                     return visitCatchClause(node);
83314                 case 282 /* ShorthandPropertyAssignment */:
83315                     return visitShorthandPropertyAssignment(node);
83316                 case 154 /* ComputedPropertyName */:
83317                     return visitComputedPropertyName(node);
83318                 case 192 /* ArrayLiteralExpression */:
83319                     return visitArrayLiteralExpression(node);
83320                 case 196 /* CallExpression */:
83321                     return visitCallExpression(node);
83322                 case 197 /* NewExpression */:
83323                     return visitNewExpression(node);
83324                 case 200 /* ParenthesizedExpression */:
83325                     return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true);
83326                 case 209 /* BinaryExpression */:
83327                     return visitBinaryExpression(node, /*needsDestructuringValue*/ true);
83328                 case 14 /* NoSubstitutionTemplateLiteral */:
83329                 case 15 /* TemplateHead */:
83330                 case 16 /* TemplateMiddle */:
83331                 case 17 /* TemplateTail */:
83332                     return visitTemplateLiteral(node);
83333                 case 10 /* StringLiteral */:
83334                     return visitStringLiteral(node);
83335                 case 8 /* NumericLiteral */:
83336                     return visitNumericLiteral(node);
83337                 case 198 /* TaggedTemplateExpression */:
83338                     return visitTaggedTemplateExpression(node);
83339                 case 211 /* TemplateExpression */:
83340                     return visitTemplateExpression(node);
83341                 case 212 /* YieldExpression */:
83342                     return visitYieldExpression(node);
83343                 case 213 /* SpreadElement */:
83344                     return visitSpreadElement(node);
83345                 case 102 /* SuperKeyword */:
83346                     return visitSuperKeyword(/*isExpressionOfCall*/ false);
83347                 case 104 /* ThisKeyword */:
83348                     return visitThisKeyword(node);
83349                 case 219 /* MetaProperty */:
83350                     return visitMetaProperty(node);
83351                 case 161 /* MethodDeclaration */:
83352                     return visitMethodDeclaration(node);
83353                 case 163 /* GetAccessor */:
83354                 case 164 /* SetAccessor */:
83355                     return visitAccessorDeclaration(node);
83356                 case 225 /* VariableStatement */:
83357                     return visitVariableStatement(node);
83358                 case 235 /* ReturnStatement */:
83359                     return visitReturnStatement(node);
83360                 default:
83361                     return ts.visitEachChild(node, visitor, context);
83362             }
83363         }
83364         function visitSourceFile(node) {
83365             var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
83366             var prologue = [];
83367             var statements = [];
83368             startLexicalEnvironment();
83369             var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
83370             statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
83371             ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
83372             if (taggedTemplateStringDeclarations) {
83373                 statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
83374             }
83375             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83376             insertCaptureThisForNodeIfNeeded(prologue, node);
83377             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83378             return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
83379         }
83380         function visitSwitchStatement(node) {
83381             if (convertedLoopState !== undefined) {
83382                 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
83383                 // for switch statement allow only non-labeled break
83384                 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
83385                 var result = ts.visitEachChild(node, visitor, context);
83386                 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
83387                 return result;
83388             }
83389             return ts.visitEachChild(node, visitor, context);
83390         }
83391         function visitCaseBlock(node) {
83392             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
83393             var updated = ts.visitEachChild(node, visitor, context);
83394             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83395             return updated;
83396         }
83397         function returnCapturedThis(node) {
83398             return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node);
83399         }
83400         function visitReturnStatement(node) {
83401             if (convertedLoopState) {
83402                 convertedLoopState.nonLocalJumps |= 8 /* Return */;
83403                 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83404                     node = returnCapturedThis(node);
83405                 }
83406                 return ts.createReturn(ts.createObjectLiteral([
83407                     ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression
83408                         ? ts.visitNode(node.expression, visitor, ts.isExpression)
83409                         : ts.createVoidZero())
83410                 ]));
83411             }
83412             else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83413                 return returnCapturedThis(node);
83414             }
83415             return ts.visitEachChild(node, visitor, context);
83416         }
83417         function visitThisKeyword(node) {
83418             if (hierarchyFacts & 2 /* ArrowFunction */) {
83419                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
83420             }
83421             if (convertedLoopState) {
83422                 if (hierarchyFacts & 2 /* ArrowFunction */) {
83423                     // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
83424                     convertedLoopState.containsLexicalThis = true;
83425                     return node;
83426                 }
83427                 return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this"));
83428             }
83429             return node;
83430         }
83431         function visitIdentifier(node) {
83432             if (!convertedLoopState) {
83433                 return node;
83434             }
83435             if (ts.isGeneratedIdentifier(node)) {
83436                 return node;
83437             }
83438             if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) {
83439                 return node;
83440             }
83441             return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments"));
83442         }
83443         function visitBreakOrContinueStatement(node) {
83444             if (convertedLoopState) {
83445                 // check if we can emit break/continue as is
83446                 // it is possible if either
83447                 //   - break/continue is labeled and label is located inside the converted loop
83448                 //   - break/continue is non-labeled and located in non-converted loop/switch statement
83449                 var jump = node.kind === 234 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
83450                 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
83451                     (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
83452                 if (!canUseBreakOrContinue) {
83453                     var labelMarker = void 0;
83454                     var label = node.label;
83455                     if (!label) {
83456                         if (node.kind === 234 /* BreakStatement */) {
83457                             convertedLoopState.nonLocalJumps |= 2 /* Break */;
83458                             labelMarker = "break";
83459                         }
83460                         else {
83461                             convertedLoopState.nonLocalJumps |= 4 /* Continue */;
83462                             // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
83463                             labelMarker = "continue";
83464                         }
83465                     }
83466                     else {
83467                         if (node.kind === 234 /* BreakStatement */) {
83468                             labelMarker = "break-" + label.escapedText;
83469                             setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
83470                         }
83471                         else {
83472                             labelMarker = "continue-" + label.escapedText;
83473                             setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
83474                         }
83475                     }
83476                     var returnExpression = ts.createLiteral(labelMarker);
83477                     if (convertedLoopState.loopOutParameters.length) {
83478                         var outParams = convertedLoopState.loopOutParameters;
83479                         var expr = void 0;
83480                         for (var i = 0; i < outParams.length; i++) {
83481                             var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
83482                             if (i === 0) {
83483                                 expr = copyExpr;
83484                             }
83485                             else {
83486                                 expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr);
83487                             }
83488                         }
83489                         returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression);
83490                     }
83491                     return ts.createReturn(returnExpression);
83492                 }
83493             }
83494             return ts.visitEachChild(node, visitor, context);
83495         }
83496         /**
83497          * Visits a ClassDeclaration and transforms it into a variable statement.
83498          *
83499          * @param node A ClassDeclaration node.
83500          */
83501         function visitClassDeclaration(node) {
83502             // [source]
83503             //      class C { }
83504             //
83505             // [output]
83506             //      var C = (function () {
83507             //          function C() {
83508             //          }
83509             //          return C;
83510             //      }());
83511             var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), 
83512             /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
83513             ts.setOriginalNode(variable, node);
83514             var statements = [];
83515             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]));
83516             ts.setOriginalNode(statement, node);
83517             ts.setTextRange(statement, node);
83518             ts.startOnNewLine(statement);
83519             statements.push(statement);
83520             // Add an `export default` statement for default exports (for `--target es5 --module es6`)
83521             if (ts.hasModifier(node, 1 /* Export */)) {
83522                 var exportStatement = ts.hasModifier(node, 512 /* Default */)
83523                     ? ts.createExportDefault(ts.getLocalName(node))
83524                     : ts.createExternalModuleExport(ts.getLocalName(node));
83525                 ts.setOriginalNode(exportStatement, statement);
83526                 statements.push(exportStatement);
83527             }
83528             var emitFlags = ts.getEmitFlags(node);
83529             if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
83530                 // Add a DeclarationMarker as a marker for the end of the declaration
83531                 statements.push(ts.createEndOfDeclarationMarker(node));
83532                 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
83533             }
83534             return ts.singleOrMany(statements);
83535         }
83536         /**
83537          * Visits a ClassExpression and transforms it into an expression.
83538          *
83539          * @param node A ClassExpression node.
83540          */
83541         function visitClassExpression(node) {
83542             // [source]
83543             //      C = class { }
83544             //
83545             // [output]
83546             //      C = (function () {
83547             //          function class_1() {
83548             //          }
83549             //          return class_1;
83550             //      }())
83551             return transformClassLikeDeclarationToExpression(node);
83552         }
83553         /**
83554          * Transforms a ClassExpression or ClassDeclaration into an expression.
83555          *
83556          * @param node A ClassExpression or ClassDeclaration node.
83557          */
83558         function transformClassLikeDeclarationToExpression(node) {
83559             // [source]
83560             //      class C extends D {
83561             //          constructor() {}
83562             //          method() {}
83563             //          get prop() {}
83564             //          set prop(v) {}
83565             //      }
83566             //
83567             // [output]
83568             //      (function (_super) {
83569             //          __extends(C, _super);
83570             //          function C() {
83571             //          }
83572             //          C.prototype.method = function () {}
83573             //          Object.defineProperty(C.prototype, "prop", {
83574             //              get: function() {},
83575             //              set: function() {},
83576             //              enumerable: true,
83577             //              configurable: true
83578             //          });
83579             //          return C;
83580             //      }(D))
83581             if (node.name) {
83582                 enableSubstitutionsForBlockScopedBindings();
83583             }
83584             var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
83585             var classFunction = ts.createFunctionExpression(
83586             /*modifiers*/ undefined, 
83587             /*asteriskToken*/ undefined, 
83588             /*name*/ undefined, 
83589             /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], 
83590             /*type*/ undefined, transformClassBody(node, extendsClauseElement));
83591             // To preserve the behavior of the old emitter, we explicitly indent
83592             // the body of the function here if it was requested in an earlier
83593             // transformation.
83594             ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
83595             // "inner" and "outer" below are added purely to preserve source map locations from
83596             // the old emitter
83597             var inner = ts.createPartiallyEmittedExpression(classFunction);
83598             inner.end = node.end;
83599             ts.setEmitFlags(inner, 1536 /* NoComments */);
83600             var outer = ts.createPartiallyEmittedExpression(inner);
83601             outer.end = ts.skipTrivia(currentText, node.pos);
83602             ts.setEmitFlags(outer, 1536 /* NoComments */);
83603             var result = ts.createParen(ts.createCall(outer, 
83604             /*typeArguments*/ undefined, extendsClauseElement
83605                 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
83606                 : []));
83607             ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
83608             return result;
83609         }
83610         /**
83611          * Transforms a ClassExpression or ClassDeclaration into a function body.
83612          *
83613          * @param node A ClassExpression or ClassDeclaration node.
83614          * @param extendsClauseElement The expression for the class `extends` clause.
83615          */
83616         function transformClassBody(node, extendsClauseElement) {
83617             var statements = [];
83618             startLexicalEnvironment();
83619             addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
83620             addConstructor(statements, node, extendsClauseElement);
83621             addClassMembers(statements, node);
83622             // Create a synthetic text range for the return statement.
83623             var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
83624             var localName = ts.getInternalName(node);
83625             // The following partially-emitted expression exists purely to align our sourcemap
83626             // emit with the original emitter.
83627             var outer = ts.createPartiallyEmittedExpression(localName);
83628             outer.end = closingBraceLocation.end;
83629             ts.setEmitFlags(outer, 1536 /* NoComments */);
83630             var statement = ts.createReturn(outer);
83631             statement.pos = closingBraceLocation.pos;
83632             ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
83633             statements.push(statement);
83634             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
83635             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
83636             ts.setEmitFlags(block, 1536 /* NoComments */);
83637             return block;
83638         }
83639         /**
83640          * Adds a call to the `__extends` helper if needed for a class.
83641          *
83642          * @param statements The statements of the class body function.
83643          * @param node The ClassExpression or ClassDeclaration node.
83644          * @param extendsClauseElement The expression for the class `extends` clause.
83645          */
83646         function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
83647             if (extendsClauseElement) {
83648                 statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), 
83649                 /*location*/ extendsClauseElement));
83650             }
83651         }
83652         /**
83653          * Adds the constructor of the class to a class body function.
83654          *
83655          * @param statements The statements of the class body function.
83656          * @param node The ClassExpression or ClassDeclaration node.
83657          * @param extendsClauseElement The expression for the class `extends` clause.
83658          */
83659         function addConstructor(statements, node, extendsClauseElement) {
83660             var savedConvertedLoopState = convertedLoopState;
83661             convertedLoopState = undefined;
83662             var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
83663             var constructor = ts.getFirstConstructorWithBody(node);
83664             var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
83665             var constructorFunction = ts.createFunctionDeclaration(
83666             /*decorators*/ undefined, 
83667             /*modifiers*/ undefined, 
83668             /*asteriskToken*/ undefined, ts.getInternalName(node), 
83669             /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), 
83670             /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
83671             ts.setTextRange(constructorFunction, constructor || node);
83672             if (extendsClauseElement) {
83673                 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
83674             }
83675             statements.push(constructorFunction);
83676             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
83677             convertedLoopState = savedConvertedLoopState;
83678         }
83679         /**
83680          * Transforms the parameters of the constructor declaration of a class.
83681          *
83682          * @param constructor The constructor for the class.
83683          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83684          *                            synthesized `super` call.
83685          */
83686         function transformConstructorParameters(constructor, hasSynthesizedSuper) {
83687             // If the TypeScript transformer needed to synthesize a constructor for property
83688             // initializers, it would have also added a synthetic `...args` parameter and
83689             // `super` call.
83690             // If this is the case, we do not include the synthetic `...args` parameter and
83691             // will instead use the `arguments` object in ES5/3.
83692             return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
83693                 || [];
83694         }
83695         function createDefaultConstructorBody(node, isDerivedClass) {
83696             // We must be here because the user didn't write a constructor
83697             // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
83698             // If that's the case we can just immediately return the result of a 'super()' call.
83699             var statements = [];
83700             resumeLexicalEnvironment();
83701             ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
83702             if (isDerivedClass) {
83703                 // return _super !== null && _super.apply(this, arguments) || this;
83704                 statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
83705             }
83706             var statementsArray = ts.createNodeArray(statements);
83707             ts.setTextRange(statementsArray, node.members);
83708             var block = ts.createBlock(statementsArray, /*multiLine*/ true);
83709             ts.setTextRange(block, node);
83710             ts.setEmitFlags(block, 1536 /* NoComments */);
83711             return block;
83712         }
83713         /**
83714          * Transforms the body of a constructor declaration of a class.
83715          *
83716          * @param constructor The constructor for the class.
83717          * @param node The node which contains the constructor.
83718          * @param extendsClauseElement The expression for the class `extends` clause.
83719          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83720          *                            synthesized `super` call.
83721          */
83722         function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
83723             // determine whether the class is known syntactically to be a derived class (e.g. a
83724             // class that extends a value that is not syntactically known to be `null`).
83725             var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */;
83726             // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
83727             // representation:
83728             //
83729             // ```
83730             // // es2015 (source)
83731             // class C extends Base { }
83732             //
83733             // // es5 (transformed)
83734             // var C = (function (_super) {
83735             //     function C() {
83736             //         return _super.apply(this, arguments) || this;
83737             //     }
83738             //     return C;
83739             // })(Base);
83740             // ```
83741             if (!constructor)
83742                 return createDefaultConstructorBody(node, isDerivedClass);
83743             // The prologue will contain all leading standard and custom prologue statements added by this transform
83744             var prologue = [];
83745             var statements = [];
83746             resumeLexicalEnvironment();
83747             // If a super call has already been synthesized,
83748             // we're going to assume that we should just transform everything after that.
83749             // The assumption is that no prior step in the pipeline has added any prologue directives.
83750             var statementOffset = 0;
83751             if (!hasSynthesizedSuper)
83752                 statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
83753             addDefaultValueAssignmentsIfNeeded(statements, constructor);
83754             addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
83755             if (!hasSynthesizedSuper)
83756                 statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
83757             // If the first statement is a call to `super()`, visit the statement directly
83758             var superCallExpression;
83759             if (hasSynthesizedSuper) {
83760                 superCallExpression = createDefaultSuperCallOrThis();
83761             }
83762             else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
83763                 var firstStatement = constructor.body.statements[statementOffset];
83764                 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
83765                     superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
83766                 }
83767             }
83768             if (superCallExpression) {
83769                 hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
83770                 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
83771             }
83772             // visit the remaining statements
83773             ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
83774             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83775             insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
83776             if (isDerivedClass) {
83777                 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) {
83778                     // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
83779                     // following representation:
83780                     //
83781                     // ```
83782                     // // es2015 (source)
83783                     // class C extends Base {
83784                     //     constructor() {
83785                     //         super("foo");
83786                     //     }
83787                     // }
83788                     //
83789                     // // es5 (transformed)
83790                     // var C = (function (_super) {
83791                     //     function C() {
83792                     //         return _super.call(this, "foo") || this;
83793                     //     }
83794                     //     return C;
83795                     // })(Base);
83796                     // ```
83797                     var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
83798                     var returnStatement = ts.createReturn(superCallExpression);
83799                     ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
83800                     ts.setEmitFlags(superCall, 1536 /* NoComments */);
83801                     statements.push(returnStatement);
83802                 }
83803                 else {
83804                     // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
83805                     //
83806                     // ```
83807                     // // es2015 (source)
83808                     // class C extends Base {
83809                     //     constructor() {
83810                     //         super("foo");
83811                     //         this.x = 1;
83812                     //     }
83813                     // }
83814                     //
83815                     // // es5 (transformed)
83816                     // var C = (function (_super) {
83817                     //     function C() {
83818                     //         var _this = _super.call(this, "foo") || this;
83819                     //         _this.x = 1;
83820                     //         return _this;
83821                     //     }
83822                     //     return C;
83823                     // })(Base);
83824                     // ```
83825                     // Since the `super()` call was the first statement, we insert the `this` capturing call to
83826                     // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
83827                     insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
83828                     if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
83829                         statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
83830                     }
83831                 }
83832             }
83833             else {
83834                 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
83835                 // captured when necessitated by an arrow function capturing the lexical `this`:
83836                 //
83837                 // ```
83838                 // // es2015
83839                 // class C {}
83840                 //
83841                 // // es5
83842                 // var C = (function () {
83843                 //     function C() {
83844                 //     }
83845                 //     return C;
83846                 // })();
83847                 // ```
83848                 insertCaptureThisForNodeIfNeeded(prologue, constructor);
83849             }
83850             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), 
83851             /*location*/ constructor.body.statements), 
83852             /*multiLine*/ true);
83853             ts.setTextRange(block, constructor.body);
83854             return block;
83855         }
83856         /**
83857          * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
83858          * It would generate obviously dead code, so we'll try to make things a little bit prettier
83859          * by doing a minimal check on whether some common patterns always explicitly return.
83860          */
83861         function isSufficientlyCoveredByReturnStatements(statement) {
83862             // A return statement is considered covered.
83863             if (statement.kind === 235 /* ReturnStatement */) {
83864                 return true;
83865             }
83866             // An if-statement with two covered branches is covered.
83867             else if (statement.kind === 227 /* IfStatement */) {
83868                 var ifStatement = statement;
83869                 if (ifStatement.elseStatement) {
83870                     return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
83871                         isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
83872                 }
83873             }
83874             // A block is covered if it has a last statement which is covered.
83875             else if (statement.kind === 223 /* Block */) {
83876                 var lastStatement = ts.lastOrUndefined(statement.statements);
83877                 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
83878                     return true;
83879                 }
83880             }
83881             return false;
83882         }
83883         function createActualThis() {
83884             return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
83885         }
83886         function createDefaultSuperCallOrThis() {
83887             return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis());
83888         }
83889         /**
83890          * Visits a parameter declaration.
83891          *
83892          * @param node A ParameterDeclaration node.
83893          */
83894         function visitParameter(node) {
83895             if (node.dotDotDotToken) {
83896                 // rest parameters are elided
83897                 return undefined;
83898             }
83899             else if (ts.isBindingPattern(node.name)) {
83900                 // Binding patterns are converted into a generated name and are
83901                 // evaluated inside the function body.
83902                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
83903                 /*decorators*/ undefined, 
83904                 /*modifiers*/ undefined, 
83905                 /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), 
83906                 /*questionToken*/ undefined, 
83907                 /*type*/ undefined, 
83908                 /*initializer*/ undefined), 
83909                 /*location*/ node), 
83910                 /*original*/ node);
83911             }
83912             else if (node.initializer) {
83913                 // Initializers are elided
83914                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
83915                 /*decorators*/ undefined, 
83916                 /*modifiers*/ undefined, 
83917                 /*dotDotDotToken*/ undefined, node.name, 
83918                 /*questionToken*/ undefined, 
83919                 /*type*/ undefined, 
83920                 /*initializer*/ undefined), 
83921                 /*location*/ node), 
83922                 /*original*/ node);
83923             }
83924             else {
83925                 return node;
83926             }
83927         }
83928         function hasDefaultValueOrBindingPattern(node) {
83929             return node.initializer !== undefined
83930                 || ts.isBindingPattern(node.name);
83931         }
83932         /**
83933          * Adds statements to the body of a function-like node if it contains parameters with
83934          * binding patterns or initializers.
83935          *
83936          * @param statements The statements for the new function body.
83937          * @param node A function-like node.
83938          */
83939         function addDefaultValueAssignmentsIfNeeded(statements, node) {
83940             if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
83941                 return false;
83942             }
83943             var added = false;
83944             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
83945                 var parameter = _a[_i];
83946                 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
83947                 // A rest parameter cannot have a binding pattern or an initializer,
83948                 // so let's just ignore it.
83949                 if (dotDotDotToken) {
83950                     continue;
83951                 }
83952                 if (ts.isBindingPattern(name)) {
83953                     added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
83954                 }
83955                 else if (initializer) {
83956                     insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
83957                     added = true;
83958                 }
83959             }
83960             return added;
83961         }
83962         /**
83963          * Adds statements to the body of a function-like node for parameters with binding patterns
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 insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
83971             // In cases where a binding pattern is simply '[]' or '{}',
83972             // we usually don't want to emit a var declaration; however, in the presence
83973             // of an initializer, we must emit that expression to preserve side effects.
83974             if (name.elements.length > 0) {
83975                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
83976                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
83977                 return true;
83978             }
83979             else if (initializer) {
83980                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
83981                 return true;
83982             }
83983             return false;
83984         }
83985         /**
83986          * Adds statements to the body of a function-like node for parameters with initializers.
83987          *
83988          * @param statements The statements for the new function body.
83989          * @param parameter The parameter for the function.
83990          * @param name The name of the parameter.
83991          * @param initializer The initializer for the parameter.
83992          */
83993         function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
83994             initializer = ts.visitNode(initializer, visitor, ts.isExpression);
83995             var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
83996                 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 */))
83997             ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
83998             ts.startOnNewLine(statement);
83999             ts.setTextRange(statement, parameter);
84000             ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
84001             ts.insertStatementAfterCustomPrologue(statements, statement);
84002         }
84003         /**
84004          * Gets a value indicating whether we need to add statements to handle a rest parameter.
84005          *
84006          * @param node A ParameterDeclaration node.
84007          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
84008          *                                          part of a constructor declaration with a
84009          *                                          synthesized call to `super`
84010          */
84011         function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
84012             return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
84013         }
84014         /**
84015          * Adds statements to the body of a function-like node if it contains a rest parameter.
84016          *
84017          * @param statements The statements for the new function body.
84018          * @param node A function-like node.
84019          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
84020          *                                          part of a constructor declaration with a
84021          *                                          synthesized call to `super`
84022          */
84023         function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
84024             var prologueStatements = [];
84025             var parameter = ts.lastOrUndefined(node.parameters);
84026             if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
84027                 return false;
84028             }
84029             // `declarationName` is the name of the local declaration for the parameter.
84030             var declarationName = parameter.name.kind === 75 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84031             ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
84032             // `expressionName` is the name of the parameter used in expressions.
84033             var expressionName = parameter.name.kind === 75 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName;
84034             var restIndex = node.parameters.length - 1;
84035             var temp = ts.createLoopVariable();
84036             // var param = [];
84037             prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84038             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84039                 ts.createVariableDeclaration(declarationName, 
84040                 /*type*/ undefined, ts.createArrayLiteral([]))
84041             ])), 
84042             /*location*/ parameter), 1048576 /* CustomPrologue */));
84043             // for (var _i = restIndex; _i < arguments.length; _i++) {
84044             //   param[_i - restIndex] = arguments[_i];
84045             // }
84046             var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([
84047                 ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex))
84048             ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([
84049                 ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0
84050                     ? temp
84051                     : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), 
84052                 /*location*/ parameter))
84053             ]));
84054             ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
84055             ts.startOnNewLine(forStatement);
84056             prologueStatements.push(forStatement);
84057             if (parameter.name.kind !== 75 /* Identifier */) {
84058                 // do the actual destructuring of the rest parameter if necessary
84059                 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84060                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
84061             }
84062             ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
84063             return true;
84064         }
84065         /**
84066          * Adds a statement to capture the `this` of a function declaration if it is needed.
84067          * NOTE: This must be executed *after* the subtree has been visited.
84068          *
84069          * @param statements The statements for the new function body.
84070          * @param node A node.
84071          */
84072         function insertCaptureThisForNodeIfNeeded(statements, node) {
84073             if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 202 /* ArrowFunction */) {
84074                 insertCaptureThisForNode(statements, node, ts.createThis());
84075                 return true;
84076             }
84077             return false;
84078         }
84079         function insertCaptureThisForNode(statements, node, initializer) {
84080             enableSubstitutionsForCapturedThis();
84081             var captureThisStatement = ts.createVariableStatement(
84082             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84083                 ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), 
84084                 /*type*/ undefined, initializer)
84085             ]));
84086             ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84087             ts.setSourceMapRange(captureThisStatement, node);
84088             ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
84089         }
84090         function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
84091             if (hierarchyFacts & 16384 /* NewTarget */) {
84092                 var newTarget = void 0;
84093                 switch (node.kind) {
84094                     case 202 /* ArrowFunction */:
84095                         return statements;
84096                     case 161 /* MethodDeclaration */:
84097                     case 163 /* GetAccessor */:
84098                     case 164 /* SetAccessor */:
84099                         // Methods and accessors cannot be constructors, so 'new.target' will
84100                         // always return 'undefined'.
84101                         newTarget = ts.createVoidZero();
84102                         break;
84103                     case 162 /* Constructor */:
84104                         // Class constructors can only be called with `new`, so `this.constructor`
84105                         // should be relatively safe to use.
84106                         newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor");
84107                         break;
84108                     case 244 /* FunctionDeclaration */:
84109                     case 201 /* FunctionExpression */:
84110                         // Functions can be called or constructed, and may have a `this` due to
84111                         // being a member or when calling an imported function via `other_1.f()`.
84112                         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());
84113                         break;
84114                     default:
84115                         return ts.Debug.failBadSyntaxKind(node);
84116                 }
84117                 var captureNewTargetStatement = ts.createVariableStatement(
84118                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
84119                     ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), 
84120                     /*type*/ undefined, newTarget)
84121                 ]));
84122                 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84123                 if (copyOnWrite) {
84124                     statements = statements.slice();
84125                 }
84126                 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
84127             }
84128             return statements;
84129         }
84130         /**
84131          * Adds statements to the class body function for a class to define the members of the
84132          * class.
84133          *
84134          * @param statements The statements for the class body function.
84135          * @param node The ClassExpression or ClassDeclaration node.
84136          */
84137         function addClassMembers(statements, node) {
84138             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
84139                 var member = _a[_i];
84140                 switch (member.kind) {
84141                     case 222 /* SemicolonClassElement */:
84142                         statements.push(transformSemicolonClassElementToStatement(member));
84143                         break;
84144                     case 161 /* MethodDeclaration */:
84145                         statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
84146                         break;
84147                     case 163 /* GetAccessor */:
84148                     case 164 /* SetAccessor */:
84149                         var accessors = ts.getAllAccessorDeclarations(node.members, member);
84150                         if (member === accessors.firstAccessor) {
84151                             statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
84152                         }
84153                         break;
84154                     case 162 /* Constructor */:
84155                         // Constructors are handled in visitClassExpression/visitClassDeclaration
84156                         break;
84157                     default:
84158                         ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
84159                         break;
84160                 }
84161             }
84162         }
84163         /**
84164          * Transforms a SemicolonClassElement into a statement for a class body function.
84165          *
84166          * @param member The SemicolonClassElement node.
84167          */
84168         function transformSemicolonClassElementToStatement(member) {
84169             return ts.setTextRange(ts.createEmptyStatement(), member);
84170         }
84171         /**
84172          * Transforms a MethodDeclaration into a statement for a class body function.
84173          *
84174          * @param receiver The receiver for the member.
84175          * @param member The MethodDeclaration node.
84176          */
84177         function transformClassMethodDeclarationToStatement(receiver, member, container) {
84178             var commentRange = ts.getCommentRange(member);
84179             var sourceMapRange = ts.getSourceMapRange(member);
84180             var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
84181             var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
84182             var e;
84183             if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) {
84184                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
84185                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
84186                         : propertyName;
84187                 e = ts.createObjectDefinePropertyCall(receiver, name, ts.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
84188             }
84189             else {
84190                 var memberName = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ member.name);
84191                 e = ts.createAssignment(memberName, memberFunction);
84192             }
84193             ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
84194             ts.setSourceMapRange(memberFunction, sourceMapRange);
84195             var statement = ts.setTextRange(ts.createExpressionStatement(e), /*location*/ member);
84196             ts.setOriginalNode(statement, member);
84197             ts.setCommentRange(statement, commentRange);
84198             // The location for the statement is used to emit comments only.
84199             // No source map should be emitted for this statement to align with the
84200             // old emitter.
84201             ts.setEmitFlags(statement, 48 /* NoSourceMap */);
84202             return statement;
84203         }
84204         /**
84205          * Transforms a set of related of get/set accessors into a statement for a class body function.
84206          *
84207          * @param receiver The receiver for the member.
84208          * @param accessors The set of related get/set accessors.
84209          */
84210         function transformAccessorsToStatement(receiver, accessors, container) {
84211             var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
84212             // The location for the statement is used to emit source maps only.
84213             // No comments should be emitted for this statement to align with the
84214             // old emitter.
84215             ts.setEmitFlags(statement, 1536 /* NoComments */);
84216             ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
84217             return statement;
84218         }
84219         /**
84220          * Transforms a set of related get/set accessors into an expression for either a class
84221          * body function or an ObjectLiteralExpression with computed properties.
84222          *
84223          * @param receiver The receiver for the member.
84224          */
84225         function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
84226             var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
84227             // To align with source maps in the old emitter, the receiver and property name
84228             // arguments are both mapped contiguously to the accessor name.
84229             var target = ts.getMutableClone(receiver);
84230             ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
84231             ts.setSourceMapRange(target, firstAccessor.name);
84232             var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
84233             if (ts.isPrivateIdentifier(visitedAccessorName)) {
84234                 return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
84235             }
84236             var propertyName = ts.createExpressionForPropertyName(visitedAccessorName);
84237             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
84238             ts.setSourceMapRange(propertyName, firstAccessor.name);
84239             var properties = [];
84240             if (getAccessor) {
84241                 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
84242                 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
84243                 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
84244                 var getter = ts.createPropertyAssignment("get", getterFunction);
84245                 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
84246                 properties.push(getter);
84247             }
84248             if (setAccessor) {
84249                 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
84250                 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
84251                 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
84252                 var setter = ts.createPropertyAssignment("set", setterFunction);
84253                 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
84254                 properties.push(setter);
84255             }
84256             properties.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue()));
84257             var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
84258             /*typeArguments*/ undefined, [
84259                 target,
84260                 propertyName,
84261                 ts.createObjectLiteral(properties, /*multiLine*/ true)
84262             ]);
84263             if (startsOnNewLine) {
84264                 ts.startOnNewLine(call);
84265             }
84266             return call;
84267         }
84268         /**
84269          * Visits an ArrowFunction and transforms it into a FunctionExpression.
84270          *
84271          * @param node An ArrowFunction node.
84272          */
84273         function visitArrowFunction(node) {
84274             if (node.transformFlags & 4096 /* ContainsLexicalThis */) {
84275                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
84276             }
84277             var savedConvertedLoopState = convertedLoopState;
84278             convertedLoopState = undefined;
84279             var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
84280             var func = ts.createFunctionExpression(
84281             /*modifiers*/ undefined, 
84282             /*asteriskToken*/ undefined, 
84283             /*name*/ undefined, 
84284             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
84285             /*type*/ undefined, transformFunctionBody(node));
84286             ts.setTextRange(func, node);
84287             ts.setOriginalNode(func, node);
84288             ts.setEmitFlags(func, 8 /* CapturesThis */);
84289             if (hierarchyFacts & 32768 /* CapturedLexicalThis */) {
84290                 enableSubstitutionsForCapturedThis();
84291             }
84292             // If an arrow function contains
84293             exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
84294             convertedLoopState = savedConvertedLoopState;
84295             return func;
84296         }
84297         /**
84298          * Visits a FunctionExpression node.
84299          *
84300          * @param node a FunctionExpression node.
84301          */
84302         function visitFunctionExpression(node) {
84303             var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
84304                 ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
84305                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84306             var savedConvertedLoopState = convertedLoopState;
84307             convertedLoopState = undefined;
84308             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84309             var body = transformFunctionBody(node);
84310             var name = hierarchyFacts & 16384 /* NewTarget */
84311                 ? ts.getLocalName(node)
84312                 : node.name;
84313             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84314             convertedLoopState = savedConvertedLoopState;
84315             return ts.updateFunctionExpression(node, 
84316             /*modifiers*/ undefined, node.asteriskToken, name, 
84317             /*typeParameters*/ undefined, parameters, 
84318             /*type*/ undefined, body);
84319         }
84320         /**
84321          * Visits a FunctionDeclaration node.
84322          *
84323          * @param node a FunctionDeclaration node.
84324          */
84325         function visitFunctionDeclaration(node) {
84326             var savedConvertedLoopState = convertedLoopState;
84327             convertedLoopState = undefined;
84328             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84329             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84330             var body = transformFunctionBody(node);
84331             var name = hierarchyFacts & 16384 /* NewTarget */
84332                 ? ts.getLocalName(node)
84333                 : node.name;
84334             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84335             convertedLoopState = savedConvertedLoopState;
84336             return ts.updateFunctionDeclaration(node, 
84337             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, 
84338             /*typeParameters*/ undefined, parameters, 
84339             /*type*/ undefined, body);
84340         }
84341         /**
84342          * Transforms a function-like node into a FunctionExpression.
84343          *
84344          * @param node The function-like node to transform.
84345          * @param location The source-map location for the new FunctionExpression.
84346          * @param name The name of the new FunctionExpression.
84347          */
84348         function transformFunctionLikeToExpression(node, location, name, container) {
84349             var savedConvertedLoopState = convertedLoopState;
84350             convertedLoopState = undefined;
84351             var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
84352                 ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
84353                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84354             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84355             var body = transformFunctionBody(node);
84356             if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) {
84357                 name = ts.getGeneratedNameForNode(node);
84358             }
84359             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84360             convertedLoopState = savedConvertedLoopState;
84361             return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
84362             /*modifiers*/ undefined, node.asteriskToken, name, 
84363             /*typeParameters*/ undefined, parameters, 
84364             /*type*/ undefined, body), location), 
84365             /*original*/ node);
84366         }
84367         /**
84368          * Transforms the body of a function-like node.
84369          *
84370          * @param node A function-like node.
84371          */
84372         function transformFunctionBody(node) {
84373             var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
84374             var singleLine = false; // indicates whether the block *may* be emitted as a single line
84375             var statementsLocation;
84376             var closeBraceLocation;
84377             var prologue = [];
84378             var statements = [];
84379             var body = node.body;
84380             var statementOffset;
84381             resumeLexicalEnvironment();
84382             if (ts.isBlock(body)) {
84383                 // ensureUseStrict is false because no new prologue-directive should be added.
84384                 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
84385                 statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
84386                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction);
84387                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement);
84388             }
84389             multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
84390             multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
84391             if (ts.isBlock(body)) {
84392                 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
84393                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
84394                 statementsLocation = body.statements;
84395                 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
84396                 // If the original body was a multi-line block, this must be a multi-line block.
84397                 if (!multiLine && body.multiLine) {
84398                     multiLine = true;
84399                 }
84400             }
84401             else {
84402                 ts.Debug.assert(node.kind === 202 /* ArrowFunction */);
84403                 // To align with the old emitter, we use a synthetic end position on the location
84404                 // for the statement list we synthesize when we down-level an arrow function with
84405                 // an expression function body. This prevents both comments and source maps from
84406                 // being emitted for the end position only.
84407                 statementsLocation = ts.moveRangeEnd(body, -1);
84408                 var equalsGreaterThanToken = node.equalsGreaterThanToken;
84409                 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
84410                     if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
84411                         singleLine = true;
84412                     }
84413                     else {
84414                         multiLine = true;
84415                     }
84416                 }
84417                 var expression = ts.visitNode(body, visitor, ts.isExpression);
84418                 var returnStatement = ts.createReturn(expression);
84419                 ts.setTextRange(returnStatement, body);
84420                 ts.moveSyntheticComments(returnStatement, body);
84421                 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
84422                 statements.push(returnStatement);
84423                 // To align with the source map emit for the old emitter, we set a custom
84424                 // source map location for the close brace.
84425                 closeBraceLocation = body;
84426             }
84427             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
84428             insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
84429             insertCaptureThisForNodeIfNeeded(prologue, node);
84430             // If we added any final generated statements, this must be a multi-line block
84431             if (ts.some(prologue)) {
84432                 multiLine = true;
84433             }
84434             statements.unshift.apply(statements, prologue);
84435             if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
84436                 // no changes were made, preserve the tree
84437                 return body;
84438             }
84439             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
84440             ts.setTextRange(block, node.body);
84441             if (!multiLine && singleLine) {
84442                 ts.setEmitFlags(block, 1 /* SingleLine */);
84443             }
84444             if (closeBraceLocation) {
84445                 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
84446             }
84447             ts.setOriginalNode(block, node.body);
84448             return block;
84449         }
84450         function visitBlock(node, isFunctionBody) {
84451             if (isFunctionBody) {
84452                 // A function body is not a block scope.
84453                 return ts.visitEachChild(node, visitor, context);
84454             }
84455             var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
84456                 ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
84457                 : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
84458             var updated = ts.visitEachChild(node, visitor, context);
84459             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84460             return updated;
84461         }
84462         /**
84463          * Visits an ExpressionStatement that contains a destructuring assignment.
84464          *
84465          * @param node An ExpressionStatement node.
84466          */
84467         function visitExpressionStatement(node) {
84468             // If we are here it is most likely because our expression is a destructuring assignment.
84469             switch (node.expression.kind) {
84470                 case 200 /* ParenthesizedExpression */:
84471                     return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84472                 case 209 /* BinaryExpression */:
84473                     return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84474             }
84475             return ts.visitEachChild(node, visitor, context);
84476         }
84477         /**
84478          * Visits a ParenthesizedExpression that may contain a destructuring assignment.
84479          *
84480          * @param node A ParenthesizedExpression node.
84481          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84482          *                                of a destructuring assignment.
84483          */
84484         function visitParenthesizedExpression(node, needsDestructuringValue) {
84485             // If we are here it is most likely because our expression is a destructuring assignment.
84486             if (!needsDestructuringValue) {
84487                 // By default we always emit the RHS at the end of a flattened destructuring
84488                 // expression. If we are in a state where we do not need the destructuring value,
84489                 // we pass that information along to the children that care about it.
84490                 switch (node.expression.kind) {
84491                     case 200 /* ParenthesizedExpression */:
84492                         return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84493                     case 209 /* BinaryExpression */:
84494                         return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84495                 }
84496             }
84497             return ts.visitEachChild(node, visitor, context);
84498         }
84499         /**
84500          * Visits a BinaryExpression that contains a destructuring assignment.
84501          *
84502          * @param node A BinaryExpression node.
84503          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84504          *                                of a destructuring assignment.
84505          */
84506         function visitBinaryExpression(node, needsDestructuringValue) {
84507             // If we are here it is because this is a destructuring assignment.
84508             if (ts.isDestructuringAssignment(node)) {
84509                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue);
84510             }
84511             return ts.visitEachChild(node, visitor, context);
84512         }
84513         function isVariableStatementOfTypeScriptClassWrapper(node) {
84514             return node.declarationList.declarations.length === 1
84515                 && !!node.declarationList.declarations[0].initializer
84516                 && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */);
84517         }
84518         function visitVariableStatement(node) {
84519             var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
84520             var updated;
84521             if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
84522                 // we are inside a converted loop - hoist variable declarations
84523                 var assignments = void 0;
84524                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
84525                     var decl = _a[_i];
84526                     hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
84527                     if (decl.initializer) {
84528                         var assignment = void 0;
84529                         if (ts.isBindingPattern(decl.name)) {
84530                             assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
84531                         }
84532                         else {
84533                             assignment = ts.createBinary(decl.name, 62 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
84534                             ts.setTextRange(assignment, decl);
84535                         }
84536                         assignments = ts.append(assignments, assignment);
84537                     }
84538                 }
84539                 if (assignments) {
84540                     updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node);
84541                 }
84542                 else {
84543                     // none of declarations has initializer - the entire variable statement can be deleted
84544                     updated = undefined;
84545                 }
84546             }
84547             else {
84548                 updated = ts.visitEachChild(node, visitor, context);
84549             }
84550             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84551             return updated;
84552         }
84553         /**
84554          * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
84555          *
84556          * @param node A VariableDeclarationList node.
84557          */
84558         function visitVariableDeclarationList(node) {
84559             if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) {
84560                 if (node.flags & 3 /* BlockScoped */) {
84561                     enableSubstitutionsForBlockScopedBindings();
84562                 }
84563                 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
84564                     ? visitVariableDeclarationInLetDeclarationList
84565                     : visitVariableDeclaration);
84566                 var declarationList = ts.createVariableDeclarationList(declarations);
84567                 ts.setOriginalNode(declarationList, node);
84568                 ts.setTextRange(declarationList, node);
84569                 ts.setCommentRange(declarationList, node);
84570                 // If the first or last declaration is a binding pattern, we need to modify
84571                 // the source map range for the declaration list.
84572                 if (node.transformFlags & 131072 /* ContainsBindingPattern */
84573                     && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
84574                     ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
84575                 }
84576                 return declarationList;
84577             }
84578             return ts.visitEachChild(node, visitor, context);
84579         }
84580         function getRangeUnion(declarations) {
84581             // declarations may not be sorted by position.
84582             // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
84583             var pos = -1, end = -1;
84584             for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
84585                 var node = declarations_10[_i];
84586                 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
84587                 end = Math.max(end, node.end);
84588             }
84589             return ts.createRange(pos, end);
84590         }
84591         /**
84592          * Gets a value indicating whether we should emit an explicit initializer for a variable
84593          * declaration in a `let` declaration list.
84594          *
84595          * @param node A VariableDeclaration node.
84596          */
84597         function shouldEmitExplicitInitializerForLetDeclaration(node) {
84598             // Nested let bindings might need to be initialized explicitly to preserve
84599             // ES6 semantic:
84600             //
84601             //  { let x = 1; }
84602             //  { let x; } // x here should be undefined. not 1
84603             //
84604             // Top level bindings never collide with anything and thus don't require
84605             // explicit initialization. As for nested let bindings there are two cases:
84606             //
84607             // - Nested let bindings that were not renamed definitely should be
84608             //   initialized explicitly:
84609             //
84610             //    { let x = 1; }
84611             //    { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
84612             //
84613             //   Without explicit initialization code in /*1*/ can be executed even if
84614             //   some-condition is evaluated to false.
84615             //
84616             // - Renaming introduces fresh name that should not collide with any
84617             //   existing names, however renamed bindings sometimes also should be
84618             //   explicitly initialized. One particular case: non-captured binding
84619             //   declared inside loop body (but not in loop initializer):
84620             //
84621             //    let x;
84622             //    for (;;) {
84623             //        let x;
84624             //    }
84625             //
84626             //   In downlevel codegen inner 'x' will be renamed so it won't collide
84627             //   with outer 'x' however it will should be reset on every iteration as
84628             //   if it was declared anew.
84629             //
84630             //   * Why non-captured binding?
84631             //     - Because if loop contains block scoped binding captured in some
84632             //       function then loop body will be rewritten to have a fresh scope
84633             //       on every iteration so everything will just work.
84634             //
84635             //   * Why loop initializer is excluded?
84636             //     - Since we've introduced a fresh name it already will be undefined.
84637             var flags = resolver.getNodeCheckFlags(node);
84638             var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
84639             var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
84640             var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
84641                 || (isCapturedInFunction
84642                     && isDeclaredInLoop
84643                     && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
84644             var emitExplicitInitializer = !emittedAsTopLevel
84645                 && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
84646                 && (!resolver.isDeclarationWithCollidingName(node)
84647                     || (isDeclaredInLoop
84648                         && !isCapturedInFunction
84649                         && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
84650             return emitExplicitInitializer;
84651         }
84652         /**
84653          * Visits a VariableDeclaration in a `let` declaration list.
84654          *
84655          * @param node A VariableDeclaration node.
84656          */
84657         function visitVariableDeclarationInLetDeclarationList(node) {
84658             // For binding pattern names that lack initializers there is no point to emit
84659             // explicit initializer since downlevel codegen for destructuring will fail
84660             // in the absence of initializer so all binding elements will say uninitialized
84661             var name = node.name;
84662             if (ts.isBindingPattern(name)) {
84663                 return visitVariableDeclaration(node);
84664             }
84665             if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
84666                 var clone_3 = ts.getMutableClone(node);
84667                 clone_3.initializer = ts.createVoidZero();
84668                 return clone_3;
84669             }
84670             return ts.visitEachChild(node, visitor, context);
84671         }
84672         /**
84673          * Visits a VariableDeclaration node with a binding pattern.
84674          *
84675          * @param node A VariableDeclaration node.
84676          */
84677         function visitVariableDeclaration(node) {
84678             var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
84679             var updated;
84680             if (ts.isBindingPattern(node.name)) {
84681                 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, 
84682                 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
84683             }
84684             else {
84685                 updated = ts.visitEachChild(node, visitor, context);
84686             }
84687             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84688             return updated;
84689         }
84690         function recordLabel(node) {
84691             convertedLoopState.labels.set(ts.idText(node.label), true);
84692         }
84693         function resetLabel(node) {
84694             convertedLoopState.labels.set(ts.idText(node.label), false);
84695         }
84696         function visitLabeledStatement(node) {
84697             if (convertedLoopState && !convertedLoopState.labels) {
84698                 convertedLoopState.labels = ts.createMap();
84699             }
84700             var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
84701             return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
84702                 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
84703                 : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel);
84704         }
84705         function visitIterationStatement(node, outermostLabeledStatement) {
84706             switch (node.kind) {
84707                 case 228 /* DoStatement */:
84708                 case 229 /* WhileStatement */:
84709                     return visitDoOrWhileStatement(node, outermostLabeledStatement);
84710                 case 230 /* ForStatement */:
84711                     return visitForStatement(node, outermostLabeledStatement);
84712                 case 231 /* ForInStatement */:
84713                     return visitForInStatement(node, outermostLabeledStatement);
84714                 case 232 /* ForOfStatement */:
84715                     return visitForOfStatement(node, outermostLabeledStatement);
84716             }
84717         }
84718         function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
84719             var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
84720             var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
84721             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84722             return updated;
84723         }
84724         function visitDoOrWhileStatement(node, outermostLabeledStatement) {
84725             return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
84726         }
84727         function visitForStatement(node, outermostLabeledStatement) {
84728             return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
84729         }
84730         function visitForInStatement(node, outermostLabeledStatement) {
84731             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
84732         }
84733         function visitForOfStatement(node, outermostLabeledStatement) {
84734             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
84735         }
84736         function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
84737             var statements = [];
84738             var initializer = node.initializer;
84739             if (ts.isVariableDeclarationList(initializer)) {
84740                 if (node.initializer.flags & 3 /* BlockScoped */) {
84741                     enableSubstitutionsForBlockScopedBindings();
84742                 }
84743                 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
84744                 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
84745                     // This works whether the declaration is a var, let, or const.
84746                     // It will use rhsIterationValue _a[_i] as the initializer.
84747                     var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
84748                     var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer);
84749                     ts.setOriginalNode(declarationList, node.initializer);
84750                     // Adjust the source map range for the first declaration to align with the old
84751                     // emitter.
84752                     ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
84753                     statements.push(ts.createVariableStatement(
84754                     /*modifiers*/ undefined, declarationList));
84755                 }
84756                 else {
84757                     // The following call does not include the initializer, so we have
84758                     // to emit it separately.
84759                     statements.push(ts.setTextRange(ts.createVariableStatement(
84760                     /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([
84761                         ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), 
84762                         /*type*/ undefined, boundValue)
84763                     ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
84764                 }
84765             }
84766             else {
84767                 // Initializer is an expression. Emit the expression in the body, so that it's
84768                 // evaluated on every iteration.
84769                 var assignment = ts.createAssignment(initializer, boundValue);
84770                 if (ts.isDestructuringAssignment(assignment)) {
84771                     ts.aggregateTransformFlags(assignment);
84772                     statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
84773                 }
84774                 else {
84775                     assignment.end = initializer.end;
84776                     statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
84777                 }
84778             }
84779             if (convertedLoopBodyStatements) {
84780                 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
84781             }
84782             else {
84783                 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
84784                 if (ts.isBlock(statement)) {
84785                     return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
84786                 }
84787                 else {
84788                     statements.push(statement);
84789                     return createSyntheticBlockForConvertedStatements(statements);
84790                 }
84791             }
84792         }
84793         function createSyntheticBlockForConvertedStatements(statements) {
84794             return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), 
84795             /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
84796         }
84797         function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
84798             // The following ES6 code:
84799             //
84800             //    for (let v of expr) { }
84801             //
84802             // should be emitted as
84803             //
84804             //    for (var _i = 0, _a = expr; _i < _a.length; _i++) {
84805             //        var v = _a[_i];
84806             //    }
84807             //
84808             // where _a and _i are temps emitted to capture the RHS and the counter,
84809             // respectively.
84810             // When the left hand side is an expression instead of a let declaration,
84811             // the "let v" is not emitted.
84812             // When the left hand side is a let/const, the v is renamed if there is
84813             // another v in scope.
84814             // Note that all assignments to the LHS are emitted in the body, including
84815             // all destructuring.
84816             // Note also that because an extra statement is needed to assign to the LHS,
84817             // for-of bodies are always emitted as blocks.
84818             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84819             // In the case where the user wrote an identifier as the RHS, like this:
84820             //
84821             //     for (let v of arr) { }
84822             //
84823             // we don't want to emit a temporary variable for the RHS, just use it directly.
84824             var counter = ts.createLoopVariable();
84825             var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84826             // The old emitter does not emit source maps for the expression
84827             ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
84828             var forStatement = ts.setTextRange(ts.createFor(
84829             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
84830                 ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)),
84831                 ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression)
84832             ]), node.expression), 2097152 /* NoHoisting */), 
84833             /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), 
84834             /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), 
84835             /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), 
84836             /*location*/ node);
84837             // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
84838             ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
84839             ts.setTextRange(forStatement, node);
84840             return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
84841         }
84842         function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
84843             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84844             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84845             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84846             var errorRecord = ts.createUniqueName("e");
84847             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
84848             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
84849             var values = ts.createValuesHelper(context, expression, node.expression);
84850             var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
84851             hoistVariableDeclaration(errorRecord);
84852             hoistVariableDeclaration(returnMethod);
84853             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
84854             var initializer = ancestorFacts & 1024 /* IterationContainer */
84855                 ? ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), values])
84856                 : values;
84857             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
84858             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
84859                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
84860                 ts.createVariableDeclaration(result, /*type*/ undefined, next)
84861             ]), node.expression), 2097152 /* NoHoisting */), 
84862             /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), 
84863             /*incrementor*/ ts.createAssignment(result, next), 
84864             /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), 
84865             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
84866             return ts.createTry(ts.createBlock([
84867                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
84868             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
84869                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
84870                     ts.createPropertyAssignment("error", catchVariable)
84871                 ])))
84872             ]), 1 /* SingleLine */)), ts.createBlock([
84873                 ts.createTry(
84874                 /*tryBlock*/ ts.createBlock([
84875                     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 */),
84876                 ]), 
84877                 /*catchClause*/ undefined, 
84878                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
84879                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
84880                 ]), 1 /* SingleLine */))
84881             ]));
84882         }
84883         /**
84884          * Visits an ObjectLiteralExpression with computed property names.
84885          *
84886          * @param node An ObjectLiteralExpression node.
84887          */
84888         function visitObjectLiteralExpression(node) {
84889             // We are here because a ComputedPropertyName was used somewhere in the expression.
84890             var properties = node.properties;
84891             var numProperties = properties.length;
84892             // Find the first computed property.
84893             // Everything until that point can be emitted as part of the initial object literal.
84894             var numInitialProperties = numProperties;
84895             var numInitialPropertiesWithoutYield = numProperties;
84896             for (var i = 0; i < numProperties; i++) {
84897                 var property = properties[i];
84898                 if ((property.transformFlags & 262144 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
84899                     && i < numInitialPropertiesWithoutYield) {
84900                     numInitialPropertiesWithoutYield = i;
84901                 }
84902                 if (property.name.kind === 154 /* ComputedPropertyName */) {
84903                     numInitialProperties = i;
84904                     break;
84905                 }
84906             }
84907             if (numInitialProperties !== numProperties) {
84908                 if (numInitialPropertiesWithoutYield < numInitialProperties) {
84909                     numInitialProperties = numInitialPropertiesWithoutYield;
84910                 }
84911                 // For computed properties, we need to create a unique handle to the object
84912                 // literal so we can modify it without risking internal assignments tainting the object.
84913                 var temp = ts.createTempVariable(hoistVariableDeclaration);
84914                 // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
84915                 var expressions = [];
84916                 var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */));
84917                 if (node.multiLine) {
84918                     ts.startOnNewLine(assignment);
84919                 }
84920                 expressions.push(assignment);
84921                 addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
84922                 // We need to clone the temporary identifier so that we can write it on a
84923                 // new line
84924                 expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
84925                 return ts.inlineExpressions(expressions);
84926             }
84927             return ts.visitEachChild(node, visitor, context);
84928         }
84929         function shouldConvertPartOfIterationStatement(node) {
84930             return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
84931         }
84932         function shouldConvertInitializerOfForStatement(node) {
84933             return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
84934         }
84935         function shouldConvertConditionOfForStatement(node) {
84936             return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
84937         }
84938         function shouldConvertIncrementorOfForStatement(node) {
84939             return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
84940         }
84941         function shouldConvertIterationStatement(node) {
84942             return shouldConvertBodyOfIterationStatement(node)
84943                 || shouldConvertInitializerOfForStatement(node);
84944         }
84945         function shouldConvertBodyOfIterationStatement(node) {
84946             return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
84947         }
84948         /**
84949          * Records constituents of name for the given variable to be hoisted in the outer scope.
84950          */
84951         function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
84952             if (!state.hoistedLocalVariables) {
84953                 state.hoistedLocalVariables = [];
84954             }
84955             visit(node.name);
84956             function visit(node) {
84957                 if (node.kind === 75 /* Identifier */) {
84958                     state.hoistedLocalVariables.push(node);
84959                 }
84960                 else {
84961                     for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
84962                         var element = _a[_i];
84963                         if (!ts.isOmittedExpression(element)) {
84964                             visit(element.name);
84965                         }
84966                     }
84967                 }
84968             }
84969         }
84970         function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
84971             if (!shouldConvertIterationStatement(node)) {
84972                 var saveAllowedNonLabeledJumps = void 0;
84973                 if (convertedLoopState) {
84974                     // we get here if we are trying to emit normal loop loop inside converted loop
84975                     // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
84976                     saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
84977                     convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
84978                 }
84979                 var result = convert
84980                     ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
84981                     : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
84982                 if (convertedLoopState) {
84983                     convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
84984                 }
84985                 return result;
84986             }
84987             var currentState = createConvertedLoopState(node);
84988             var statements = [];
84989             var outerConvertedLoopState = convertedLoopState;
84990             convertedLoopState = currentState;
84991             var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
84992             var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
84993             convertedLoopState = outerConvertedLoopState;
84994             if (initializerFunction)
84995                 statements.push(initializerFunction.functionDeclaration);
84996             if (bodyFunction)
84997                 statements.push(bodyFunction.functionDeclaration);
84998             addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
84999             if (initializerFunction) {
85000                 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
85001             }
85002             var loop;
85003             if (bodyFunction) {
85004                 if (convert) {
85005                     loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
85006                 }
85007                 else {
85008                     var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true));
85009                     ts.aggregateTransformFlags(clone_4);
85010                     loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
85011                 }
85012             }
85013             else {
85014                 var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
85015                 ts.aggregateTransformFlags(clone_5);
85016                 loop = ts.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel);
85017             }
85018             statements.push(loop);
85019             return statements;
85020         }
85021         function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
85022             switch (node.kind) {
85023                 case 230 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
85024                 case 231 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
85025                 case 232 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
85026                 case 228 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
85027                 case 229 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
85028                 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
85029             }
85030         }
85031         function convertForStatement(node, initializerFunction, convertedLoopBody) {
85032             var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
85033             var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
85034             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);
85035         }
85036         function convertForOfStatement(node, convertedLoopBody) {
85037             return ts.updateForOf(node, 
85038             /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85039         }
85040         function convertForInStatement(node, convertedLoopBody) {
85041             return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85042         }
85043         function convertDoStatement(node, convertedLoopBody) {
85044             return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
85045         }
85046         function convertWhileStatement(node, convertedLoopBody) {
85047             return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85048         }
85049         function createConvertedLoopState(node) {
85050             var loopInitializer;
85051             switch (node.kind) {
85052                 case 230 /* ForStatement */:
85053                 case 231 /* ForInStatement */:
85054                 case 232 /* ForOfStatement */:
85055                     var initializer = node.initializer;
85056                     if (initializer && initializer.kind === 243 /* VariableDeclarationList */) {
85057                         loopInitializer = initializer;
85058                     }
85059                     break;
85060             }
85061             // variables that will be passed to the loop as parameters
85062             var loopParameters = [];
85063             // variables declared in the loop initializer that will be changed inside the loop
85064             var loopOutParameters = [];
85065             if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
85066                 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
85067                 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
85068                     var decl = _a[_i];
85069                     processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85070                 }
85071             }
85072             var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
85073             if (convertedLoopState) {
85074                 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
85075                 // if outer converted loop has already accumulated some state - pass it through
85076                 if (convertedLoopState.argumentsName) {
85077                     // outer loop has already used 'arguments' so we've already have some name to alias it
85078                     // use the same name in all nested loops
85079                     currentState.argumentsName = convertedLoopState.argumentsName;
85080                 }
85081                 if (convertedLoopState.thisName) {
85082                     // outer loop has already used 'this' so we've already have some name to alias it
85083                     // use the same name in all nested loops
85084                     currentState.thisName = convertedLoopState.thisName;
85085                 }
85086                 if (convertedLoopState.hoistedLocalVariables) {
85087                     // we've already collected some non-block scoped variable declarations in enclosing loop
85088                     // use the same storage in nested loop
85089                     currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
85090                 }
85091             }
85092             return currentState;
85093         }
85094         function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
85095             var extraVariableDeclarations;
85096             // propagate state from the inner loop to the outer loop if necessary
85097             if (state.argumentsName) {
85098                 // if alias for arguments is set
85099                 if (outerState) {
85100                     // pass it to outer converted loop
85101                     outerState.argumentsName = state.argumentsName;
85102                 }
85103                 else {
85104                     // this is top level converted loop and we need to create an alias for 'arguments' object
85105                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, 
85106                     /*type*/ undefined, ts.createIdentifier("arguments")));
85107                 }
85108             }
85109             if (state.thisName) {
85110                 // if alias for this is set
85111                 if (outerState) {
85112                     // pass it to outer converted loop
85113                     outerState.thisName = state.thisName;
85114                 }
85115                 else {
85116                     // this is top level converted loop so we need to create an alias for 'this' here
85117                     // NOTE:
85118                     // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
85119                     // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
85120                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, 
85121                     /*type*/ undefined, ts.createIdentifier("this")));
85122                 }
85123             }
85124             if (state.hoistedLocalVariables) {
85125                 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
85126                 if (outerState) {
85127                     // pass them to outer converted loop
85128                     outerState.hoistedLocalVariables = state.hoistedLocalVariables;
85129                 }
85130                 else {
85131                     if (!extraVariableDeclarations) {
85132                         extraVariableDeclarations = [];
85133                     }
85134                     // hoist collected variable declarations
85135                     for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
85136                         var identifier = _a[_i];
85137                         extraVariableDeclarations.push(ts.createVariableDeclaration(identifier));
85138                     }
85139                 }
85140             }
85141             // add extra variables to hold out parameters if necessary
85142             if (state.loopOutParameters.length) {
85143                 if (!extraVariableDeclarations) {
85144                     extraVariableDeclarations = [];
85145                 }
85146                 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
85147                     var outParam = _c[_b];
85148                     extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName));
85149                 }
85150             }
85151             if (state.conditionVariable) {
85152                 if (!extraVariableDeclarations) {
85153                     extraVariableDeclarations = [];
85154                 }
85155                 extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse()));
85156             }
85157             // create variable statement to hold all introduced variable declarations
85158             if (extraVariableDeclarations) {
85159                 statements.push(ts.createVariableStatement(
85160                 /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations)));
85161             }
85162         }
85163         function createOutVariable(p) {
85164             return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName);
85165         }
85166         /**
85167          * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
85168          * that is captured in a closure inside of the initializer. The `_loop_init` function is
85169          * used to preserve the per-iteration environment semantics of
85170          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85171          */
85172         function createFunctionForInitializerOfForStatement(node, currentState) {
85173             var functionName = ts.createUniqueName("_loop_init");
85174             var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0;
85175             var emitFlags = 0 /* None */;
85176             if (currentState.containsLexicalThis)
85177                 emitFlags |= 8 /* CapturesThis */;
85178             if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
85179                 emitFlags |= 262144 /* AsyncFunctionBody */;
85180             var statements = [];
85181             statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer));
85182             copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
85183             // This transforms the following ES2015 syntax:
85184             //
85185             //  for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
85186             //      // loop body
85187             //  }
85188             //
85189             // Into the following ES5 syntax:
85190             //
85191             //  var _loop_init_1 = function () {
85192             //      var i = (setImmediate(() => console.log(i)), 0);
85193             //      out_i_1 = i;
85194             //  };
85195             //  var out_i_1;
85196             //  _loop_init_1();
85197             //  for (var i = out_i_1; i < 2; i++) {
85198             //      // loop body
85199             //  }
85200             //
85201             // Which prevents mutations to `i` in the per-iteration environment of the body
85202             // from affecting the initial value for `i` outside of the per-iteration environment.
85203             var functionDeclaration = ts.createVariableStatement(
85204             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85205                 ts.createVariableDeclaration(functionName, 
85206                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85207                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85208                 /*name*/ undefined, 
85209                 /*typeParameters*/ undefined, 
85210                 /*parameters*/ undefined, 
85211                 /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
85212             ]), 2097152 /* NoHoisting */));
85213             var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
85214             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85215         }
85216         /**
85217          * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
85218          * that is captured in a closure inside of the loop body. The `_loop` function is used to
85219          * preserve the per-iteration environment semantics of
85220          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85221          */
85222         function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
85223             var functionName = ts.createUniqueName("_loop");
85224             startLexicalEnvironment();
85225             var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
85226             var lexicalEnvironment = endLexicalEnvironment();
85227             var statements = [];
85228             if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
85229                 // If a block-scoped variable declared in the initializer of `node` is captured in
85230                 // the condition or incrementor, we must move the condition and incrementor into
85231                 // the body of the for loop.
85232                 //
85233                 // This transforms the following ES2015 syntax:
85234                 //
85235                 //  for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
85236                 //      // loop body
85237                 //  }
85238                 //
85239                 // Into the following ES5 syntax:
85240                 //
85241                 //  var _loop_1 = function (i) {
85242                 //      if (inc_1)
85243                 //          setImmediate(() => console.log(i)), i++;
85244                 //      else
85245                 //          inc_1 = true;
85246                 //      if (!(setImmediate(() => console.log(i)), i < 2))
85247                 //          return out_i_1 = i, "break";
85248                 //      // loop body
85249                 //      out_i_1 = i;
85250                 //  }
85251                 //  var out_i_1, inc_1 = false;
85252                 //  for (var i = 0;;) {
85253                 //      var state_1 = _loop_1(i);
85254                 //      i = out_i_1;
85255                 //      if (state_1 === "break")
85256                 //          break;
85257                 //  }
85258                 //
85259                 // Which prevents mutations to `i` in the per-iteration environment of the body
85260                 // from affecting the value of `i` in the previous per-iteration environment.
85261                 //
85262                 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
85263                 // environment that is carried over to the next iteration of the loop. As a result,
85264                 // we must indicate whether this is the first evaluation of the loop body so that
85265                 // we only evaluate the incrementor on subsequent evaluations.
85266                 currentState.conditionVariable = ts.createUniqueName("inc");
85267                 statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue()))));
85268                 if (shouldConvertConditionOfForStatement(node)) {
85269                     statements.push(ts.createIf(ts.createPrefix(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement)));
85270                 }
85271             }
85272             if (ts.isBlock(statement)) {
85273                 ts.addRange(statements, statement.statements);
85274             }
85275             else {
85276                 statements.push(statement);
85277             }
85278             copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
85279             ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
85280             var loopBody = ts.createBlock(statements, /*multiLine*/ true);
85281             if (ts.isBlock(statement))
85282                 ts.setOriginalNode(loopBody, statement);
85283             var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
85284             var emitFlags = 0;
85285             if (currentState.containsLexicalThis)
85286                 emitFlags |= 8 /* CapturesThis */;
85287             if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
85288                 emitFlags |= 262144 /* AsyncFunctionBody */;
85289             // This transforms the following ES2015 syntax (in addition to other variations):
85290             //
85291             //  for (let i = 0; i < 2; i++) {
85292             //      setImmediate(() => console.log(i));
85293             //  }
85294             //
85295             // Into the following ES5 syntax:
85296             //
85297             //  var _loop_1 = function (i) {
85298             //      setImmediate(() => console.log(i));
85299             //  };
85300             //  for (var i = 0; i < 2; i++) {
85301             //      _loop_1(i);
85302             //  }
85303             var functionDeclaration = ts.createVariableStatement(
85304             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85305                 ts.createVariableDeclaration(functionName, 
85306                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85307                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85308                 /*name*/ undefined, 
85309                 /*typeParameters*/ undefined, currentState.loopParameters, 
85310                 /*type*/ undefined, loopBody), emitFlags))
85311             ]), 2097152 /* NoHoisting */));
85312             var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
85313             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85314         }
85315         function copyOutParameter(outParam, copyDirection) {
85316             var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
85317             var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
85318             return ts.createBinary(target, 62 /* EqualsToken */, source);
85319         }
85320         function copyOutParameters(outParams, partFlags, copyDirection, statements) {
85321             for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
85322                 var outParam = outParams_1[_i];
85323                 if (outParam.flags & partFlags) {
85324                     statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
85325                 }
85326             }
85327         }
85328         function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
85329             var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []);
85330             var callResult = containsYield
85331                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85332                 : call;
85333             return ts.createStatement(callResult);
85334         }
85335         function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
85336             var statements = [];
85337             // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
85338             // simple loops are emitted as just 'loop()';
85339             // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
85340             var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
85341                 !state.labeledNonLocalBreaks &&
85342                 !state.labeledNonLocalContinues;
85343             var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
85344             var callResult = containsYield
85345                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85346                 : call;
85347             if (isSimpleLoop) {
85348                 statements.push(ts.createExpressionStatement(callResult));
85349                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85350             }
85351             else {
85352                 var loopResultName = ts.createUniqueName("state");
85353                 var stateVariable = ts.createVariableStatement(
85354                 /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)]));
85355                 statements.push(stateVariable);
85356                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85357                 if (state.nonLocalJumps & 8 /* Return */) {
85358                     var returnStatement = void 0;
85359                     if (outerState) {
85360                         outerState.nonLocalJumps |= 8 /* Return */;
85361                         returnStatement = ts.createReturn(loopResultName);
85362                     }
85363                     else {
85364                         returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value"));
85365                     }
85366                     statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement));
85367                 }
85368                 if (state.nonLocalJumps & 2 /* Break */) {
85369                     statements.push(ts.createIf(ts.createBinary(loopResultName, 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak()));
85370                 }
85371                 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
85372                     var caseClauses = [];
85373                     processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
85374                     processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
85375                     statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses)));
85376                 }
85377             }
85378             return statements;
85379         }
85380         function setLabeledJump(state, isBreak, labelText, labelMarker) {
85381             if (isBreak) {
85382                 if (!state.labeledNonLocalBreaks) {
85383                     state.labeledNonLocalBreaks = ts.createMap();
85384                 }
85385                 state.labeledNonLocalBreaks.set(labelText, labelMarker);
85386             }
85387             else {
85388                 if (!state.labeledNonLocalContinues) {
85389                     state.labeledNonLocalContinues = ts.createMap();
85390                 }
85391                 state.labeledNonLocalContinues.set(labelText, labelMarker);
85392             }
85393         }
85394         function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
85395             if (!table) {
85396                 return;
85397             }
85398             table.forEach(function (labelMarker, labelText) {
85399                 var statements = [];
85400                 // if there are no outer converted loop or outer label in question is located inside outer converted loop
85401                 // then emit labeled break\continue
85402                 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
85403                 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
85404                     var label = ts.createIdentifier(labelText);
85405                     statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label));
85406                 }
85407                 else {
85408                     setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
85409                     statements.push(ts.createReturn(loopResultName));
85410                 }
85411                 caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements));
85412             });
85413         }
85414         function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
85415             var name = decl.name;
85416             if (ts.isBindingPattern(name)) {
85417                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
85418                     var element = _a[_i];
85419                     if (!ts.isOmittedExpression(element)) {
85420                         processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85421                     }
85422                 }
85423             }
85424             else {
85425                 loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
85426                 var checkFlags = resolver.getNodeCheckFlags(decl);
85427                 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
85428                     var outParamName = ts.createUniqueName("out_" + ts.idText(name));
85429                     var flags = 0;
85430                     if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
85431                         flags |= 1 /* Body */;
85432                     }
85433                     if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
85434                         flags |= 2 /* Initializer */;
85435                     }
85436                     loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
85437                 }
85438             }
85439         }
85440         /**
85441          * Adds the members of an object literal to an array of expressions.
85442          *
85443          * @param expressions An array of expressions.
85444          * @param node An ObjectLiteralExpression node.
85445          * @param receiver The receiver for members of the ObjectLiteralExpression.
85446          * @param numInitialNonComputedProperties The number of initial properties without
85447          *                                        computed property names.
85448          */
85449         function addObjectLiteralMembers(expressions, node, receiver, start) {
85450             var properties = node.properties;
85451             var numProperties = properties.length;
85452             for (var i = start; i < numProperties; i++) {
85453                 var property = properties[i];
85454                 switch (property.kind) {
85455                     case 163 /* GetAccessor */:
85456                     case 164 /* SetAccessor */:
85457                         var accessors = ts.getAllAccessorDeclarations(node.properties, property);
85458                         if (property === accessors.firstAccessor) {
85459                             expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
85460                         }
85461                         break;
85462                     case 161 /* MethodDeclaration */:
85463                         expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
85464                         break;
85465                     case 281 /* PropertyAssignment */:
85466                         expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
85467                         break;
85468                     case 282 /* ShorthandPropertyAssignment */:
85469                         expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
85470                         break;
85471                     default:
85472                         ts.Debug.failBadSyntaxKind(node);
85473                         break;
85474                 }
85475             }
85476         }
85477         /**
85478          * Transforms a PropertyAssignment node into an expression.
85479          *
85480          * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
85481          * @param property The PropertyAssignment node.
85482          * @param receiver The receiver for the assignment.
85483          */
85484         function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85485             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
85486             ts.setTextRange(expression, property);
85487             if (startsOnNewLine) {
85488                 ts.startOnNewLine(expression);
85489             }
85490             return expression;
85491         }
85492         /**
85493          * Transforms a ShorthandPropertyAssignment node into an expression.
85494          *
85495          * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
85496          * @param property The ShorthandPropertyAssignment node.
85497          * @param receiver The receiver for the assignment.
85498          */
85499         function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85500             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name));
85501             ts.setTextRange(expression, property);
85502             if (startsOnNewLine) {
85503                 ts.startOnNewLine(expression);
85504             }
85505             return expression;
85506         }
85507         /**
85508          * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
85509          *
85510          * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
85511          * @param method The MethodDeclaration node.
85512          * @param receiver The receiver for the assignment.
85513          */
85514         function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
85515             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
85516             ts.setTextRange(expression, method);
85517             if (startsOnNewLine) {
85518                 ts.startOnNewLine(expression);
85519             }
85520             return expression;
85521         }
85522         function visitCatchClause(node) {
85523             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
85524             var updated;
85525             ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
85526             if (ts.isBindingPattern(node.variableDeclaration.name)) {
85527                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
85528                 var newVariableDeclaration = ts.createVariableDeclaration(temp);
85529                 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
85530                 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
85531                 var list = ts.createVariableDeclarationList(vars);
85532                 ts.setTextRange(list, node.variableDeclaration);
85533                 var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list);
85534                 updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
85535             }
85536             else {
85537                 updated = ts.visitEachChild(node, visitor, context);
85538             }
85539             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
85540             return updated;
85541         }
85542         function addStatementToStartOfBlock(block, statement) {
85543             var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
85544             return ts.updateBlock(block, __spreadArrays([statement], transformedStatements));
85545         }
85546         /**
85547          * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
85548          * PropertyAssignment.
85549          *
85550          * @param node A MethodDeclaration node.
85551          */
85552         function visitMethodDeclaration(node) {
85553             // We should only get here for methods on an object literal with regular identifier names.
85554             // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
85555             // Methods with computed property names are handled in visitObjectLiteralExpression.
85556             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85557             var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
85558             ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
85559             return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), 
85560             /*location*/ node);
85561         }
85562         /**
85563          * Visits an AccessorDeclaration of an ObjectLiteralExpression.
85564          *
85565          * @param node An AccessorDeclaration node.
85566          */
85567         function visitAccessorDeclaration(node) {
85568             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85569             var savedConvertedLoopState = convertedLoopState;
85570             convertedLoopState = undefined;
85571             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
85572             var updated;
85573             var parameters = ts.visitParameterList(node.parameters, visitor, context);
85574             var body = transformFunctionBody(node);
85575             if (node.kind === 163 /* GetAccessor */) {
85576                 updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
85577             }
85578             else {
85579                 updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
85580             }
85581             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
85582             convertedLoopState = savedConvertedLoopState;
85583             return updated;
85584         }
85585         /**
85586          * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
85587          *
85588          * @param node A ShorthandPropertyAssignment node.
85589          */
85590         function visitShorthandPropertyAssignment(node) {
85591             return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), 
85592             /*location*/ node);
85593         }
85594         function visitComputedPropertyName(node) {
85595             return ts.visitEachChild(node, visitor, context);
85596         }
85597         /**
85598          * Visits a YieldExpression node.
85599          *
85600          * @param node A YieldExpression node.
85601          */
85602         function visitYieldExpression(node) {
85603             // `yield` expressions are transformed using the generators transformer.
85604             return ts.visitEachChild(node, visitor, context);
85605         }
85606         /**
85607          * Visits an ArrayLiteralExpression that contains a spread element.
85608          *
85609          * @param node An ArrayLiteralExpression node.
85610          */
85611         function visitArrayLiteralExpression(node) {
85612             if (ts.some(node.elements, ts.isSpreadElement)) {
85613                 // We are here because we contain a SpreadElementExpression.
85614                 return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
85615             }
85616             return ts.visitEachChild(node, visitor, context);
85617         }
85618         /**
85619          * Visits a CallExpression that contains either a spread element or `super`.
85620          *
85621          * @param node a CallExpression.
85622          */
85623         function visitCallExpression(node) {
85624             if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
85625                 return visitTypeScriptClassWrapper(node);
85626             }
85627             var expression = ts.skipOuterExpressions(node.expression);
85628             if (expression.kind === 102 /* SuperKeyword */ ||
85629                 ts.isSuperProperty(expression) ||
85630                 ts.some(node.arguments, ts.isSpreadElement)) {
85631                 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
85632             }
85633             return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), 
85634             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
85635         }
85636         function visitTypeScriptClassWrapper(node) {
85637             // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
85638             // The wrapper has a form similar to:
85639             //
85640             //  (function() {
85641             //      class C { // 1
85642             //      }
85643             //      C.x = 1; // 2
85644             //      return C;
85645             //  }())
85646             //
85647             // When we transform the class, we end up with something like this:
85648             //
85649             //  (function () {
85650             //      var C = (function () { // 3
85651             //          function C() {
85652             //          }
85653             //          return C; // 4
85654             //      }());
85655             //      C.x = 1;
85656             //      return C;
85657             //  }())
85658             //
85659             // We want to simplify the two nested IIFEs to end up with something like this:
85660             //
85661             //  (function () {
85662             //      function C() {
85663             //      }
85664             //      C.x = 1;
85665             //      return C;
85666             //  }())
85667             // We skip any outer expressions in a number of places to get to the innermost
85668             // expression, but we will restore them later to preserve comments and source maps.
85669             var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
85670             // The class statements are the statements generated by visiting the first statement with initializer of the
85671             // body (1), while all other statements are added to remainingStatements (2)
85672             var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
85673             // visit the class body statements outside of any converted loop body.
85674             var savedConvertedLoopState = convertedLoopState;
85675             convertedLoopState = undefined;
85676             var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
85677             convertedLoopState = savedConvertedLoopState;
85678             var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
85679             var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
85680             var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
85681             // We know there is only one variable declaration here as we verified this in an
85682             // earlier call to isTypeScriptClassWrapper
85683             var variable = varStatement.declarationList.declarations[0];
85684             var initializer = ts.skipOuterExpressions(variable.initializer);
85685             // Under certain conditions, the 'ts' transformer may introduce a class alias, which
85686             // we see as an assignment, for example:
85687             //
85688             //  (function () {
85689             //      var C_1;
85690             //      var C = C_1 = (function () {
85691             //          function C() {
85692             //          }
85693             //          C.x = function () { return C_1; }
85694             //          return C;
85695             //      }());
85696             //      C = C_1 = __decorate([dec], C);
85697             //      return C;
85698             //  }())
85699             //
85700             var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
85701             // The underlying call (3) is another IIFE that may contain a '_super' argument.
85702             var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
85703             var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
85704             var funcStatements = func.body.statements;
85705             var classBodyStart = 0;
85706             var classBodyEnd = -1;
85707             var statements = [];
85708             if (aliasAssignment) {
85709                 // If we have a class alias assignment, we need to move it to the down-level constructor
85710                 // function we generated for the class.
85711                 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
85712                 if (extendsCall) {
85713                     statements.push(extendsCall);
85714                     classBodyStart++;
85715                 }
85716                 // The next statement is the function declaration.
85717                 statements.push(funcStatements[classBodyStart]);
85718                 classBodyStart++;
85719                 // Add the class alias following the declaration.
85720                 statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
85721             }
85722             // Find the trailing 'return' statement (4)
85723             while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
85724                 classBodyEnd--;
85725             }
85726             // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
85727             // as we already have one that has been introduced by the 'ts' transformer.
85728             ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
85729             if (classBodyEnd < -1) {
85730                 // If there were any hoisted declarations following the return statement, we should
85731                 // append them.
85732                 ts.addRange(statements, funcStatements, classBodyEnd + 1);
85733             }
85734             // Add the remaining statements of the outer wrapper.
85735             ts.addRange(statements, remainingStatements);
85736             // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
85737             // after the remaining statements from the 'ts' transformer.
85738             ts.addRange(statements, classStatements, /*start*/ 1);
85739             // Recreate any outer parentheses or partially-emitted expressions to preserve source map
85740             // and comment locations.
85741             return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, 
85742             /*modifiers*/ undefined, 
85743             /*asteriskToken*/ undefined, 
85744             /*name*/ undefined, 
85745             /*typeParameters*/ undefined, func.parameters, 
85746             /*type*/ undefined, ts.updateBlock(func.body, statements))), 
85747             /*typeArguments*/ undefined, call.arguments))));
85748         }
85749         function visitImmediateSuperCallInBody(node) {
85750             return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
85751         }
85752         function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
85753             // We are here either because SuperKeyword was used somewhere in the expression, or
85754             // because we contain a SpreadElementExpression.
85755             if (node.transformFlags & 8192 /* ContainsRestOrSpread */ ||
85756                 node.expression.kind === 102 /* SuperKeyword */ ||
85757                 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
85758                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85759                 if (node.expression.kind === 102 /* SuperKeyword */) {
85760                     ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
85761                 }
85762                 var resultingCall = void 0;
85763                 if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
85764                     // [source]
85765                     //      f(...a, b)
85766                     //      x.m(...a, b)
85767                     //      super(...a, b)
85768                     //      super.m(...a, b) // in static
85769                     //      super.m(...a, b) // in instance
85770                     //
85771                     // [output]
85772                     //      f.apply(void 0, a.concat([b]))
85773                     //      (_a = x).m.apply(_a, a.concat([b]))
85774                     //      _super.apply(this, a.concat([b]))
85775                     //      _super.m.apply(this, a.concat([b]))
85776                     //      _super.prototype.m.apply(this, a.concat([b]))
85777                     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));
85778                 }
85779                 else {
85780                     // [source]
85781                     //      super(a)
85782                     //      super.m(a) // in static
85783                     //      super.m(a) // in instance
85784                     //
85785                     // [output]
85786                     //      _super.call(this, a)
85787                     //      _super.m.call(this, a)
85788                     //      _super.prototype.m.call(this, a)
85789                     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), 
85790                     /*location*/ node);
85791                 }
85792                 if (node.expression.kind === 102 /* SuperKeyword */) {
85793                     var initializer = ts.createLogicalOr(resultingCall, createActualThis());
85794                     resultingCall = assignToCapturedThis
85795                         ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
85796                         : initializer;
85797                 }
85798                 return ts.setOriginalNode(resultingCall, node);
85799             }
85800             return ts.visitEachChild(node, visitor, context);
85801         }
85802         /**
85803          * Visits a NewExpression that contains a spread element.
85804          *
85805          * @param node A NewExpression node.
85806          */
85807         function visitNewExpression(node) {
85808             if (ts.some(node.arguments, ts.isSpreadElement)) {
85809                 // We are here because we contain a SpreadElementExpression.
85810                 // [source]
85811                 //      new C(...a)
85812                 //
85813                 // [output]
85814                 //      new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
85815                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85816                 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)), 
85817                 /*typeArguments*/ undefined, []);
85818             }
85819             return ts.visitEachChild(node, visitor, context);
85820         }
85821         /**
85822          * Transforms an array of Expression nodes that contains a SpreadExpression.
85823          *
85824          * @param elements The array of Expression nodes.
85825          * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
85826          * @param multiLine A value indicating whether the result should be emitted on multiple lines.
85827          */
85828         function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
85829             // [source]
85830             //      [a, ...b, c]
85831             //
85832             // [output (downlevelIteration)]
85833             //      __spread([a], b, [c])
85834             //
85835             // [output]
85836             //      __spreadArrays([a], b, [c])
85837             // Map spans of spread expressions into their expressions and spans of other
85838             // expressions into an array literal.
85839             var numElements = elements.length;
85840             var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
85841                 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
85842             }));
85843             if (compilerOptions.downlevelIteration) {
85844                 if (segments.length === 1) {
85845                     var firstSegment = segments[0];
85846                     if (isCallToHelper(firstSegment, "___spread")) {
85847                         return segments[0];
85848                     }
85849                 }
85850                 return ts.createSpreadHelper(context, segments);
85851             }
85852             else {
85853                 if (segments.length === 1) {
85854                     var firstSegment = segments[0];
85855                     if (!needsUniqueCopy
85856                         || isPackedArrayLiteral(firstSegment)
85857                         || isCallToHelper(firstSegment, "___spreadArrays")) {
85858                         return segments[0];
85859                     }
85860                 }
85861                 return ts.createSpreadArraysHelper(context, segments);
85862             }
85863         }
85864         function isPackedElement(node) {
85865             return !ts.isOmittedExpression(node);
85866         }
85867         function isPackedArrayLiteral(node) {
85868             return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
85869         }
85870         function isCallToHelper(firstSegment, helperName) {
85871             return ts.isCallExpression(firstSegment)
85872                 && ts.isIdentifier(firstSegment.expression)
85873                 && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
85874                 && firstSegment.expression.escapedText === helperName;
85875         }
85876         function partitionSpread(node) {
85877             return ts.isSpreadElement(node)
85878                 ? visitSpanOfSpreads
85879                 : visitSpanOfNonSpreads;
85880         }
85881         function visitSpanOfSpreads(chunk) {
85882             return ts.map(chunk, visitExpressionOfSpread);
85883         }
85884         function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
85885             return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
85886         }
85887         function visitSpreadElement(node) {
85888             return ts.visitNode(node.expression, visitor, ts.isExpression);
85889         }
85890         /**
85891          * Transforms the expression of a SpreadExpression node.
85892          *
85893          * @param node A SpreadExpression node.
85894          */
85895         function visitExpressionOfSpread(node) {
85896             return ts.visitNode(node.expression, visitor, ts.isExpression);
85897         }
85898         /**
85899          * Visits a template literal.
85900          *
85901          * @param node A template literal.
85902          */
85903         function visitTemplateLiteral(node) {
85904             return ts.setTextRange(ts.createLiteral(node.text), node);
85905         }
85906         /**
85907          * Visits a string literal with an extended unicode escape.
85908          *
85909          * @param node A string literal.
85910          */
85911         function visitStringLiteral(node) {
85912             if (node.hasExtendedUnicodeEscape) {
85913                 return ts.setTextRange(ts.createLiteral(node.text), node);
85914             }
85915             return node;
85916         }
85917         /**
85918          * Visits a binary or octal (ES6) numeric literal.
85919          *
85920          * @param node A string literal.
85921          */
85922         function visitNumericLiteral(node) {
85923             if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
85924                 return ts.setTextRange(ts.createNumericLiteral(node.text), node);
85925             }
85926             return node;
85927         }
85928         /**
85929          * Visits a TaggedTemplateExpression node.
85930          *
85931          * @param node A TaggedTemplateExpression node.
85932          */
85933         function visitTaggedTemplateExpression(node) {
85934             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All);
85935         }
85936         /**
85937          * Visits a TemplateExpression node.
85938          *
85939          * @param node A TemplateExpression node.
85940          */
85941         function visitTemplateExpression(node) {
85942             var expressions = [];
85943             addTemplateHead(expressions, node);
85944             addTemplateSpans(expressions, node);
85945             // createAdd will check if each expression binds less closely than binary '+'.
85946             // If it does, it wraps the expression in parentheses. Otherwise, something like
85947             //    `abc${ 1 << 2 }`
85948             // becomes
85949             //    "abc" + 1 << 2 + ""
85950             // which is really
85951             //    ("abc" + 1) << (2 + "")
85952             // rather than
85953             //    "abc" + (1 << 2) + ""
85954             var expression = ts.reduceLeft(expressions, ts.createAdd);
85955             if (ts.nodeIsSynthesized(expression)) {
85956                 expression.pos = node.pos;
85957                 expression.end = node.end;
85958             }
85959             return expression;
85960         }
85961         /**
85962          * Gets a value indicating whether we need to include the head of a TemplateExpression.
85963          *
85964          * @param node A TemplateExpression node.
85965          */
85966         function shouldAddTemplateHead(node) {
85967             // If this expression has an empty head literal and the first template span has a non-empty
85968             // literal, then emitting the empty head literal is not necessary.
85969             //     `${ foo } and ${ bar }`
85970             // can be emitted as
85971             //     foo + " and " + bar
85972             // This is because it is only required that one of the first two operands in the emit
85973             // output must be a string literal, so that the other operand and all following operands
85974             // are forced into strings.
85975             //
85976             // If the first template span has an empty literal, then the head must still be emitted.
85977             //     `${ foo }${ bar }`
85978             // must still be emitted as
85979             //     "" + foo + bar
85980             // There is always atleast one templateSpan in this code path, since
85981             // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
85982             ts.Debug.assert(node.templateSpans.length !== 0);
85983             return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
85984         }
85985         /**
85986          * Adds the head of a TemplateExpression to an array of expressions.
85987          *
85988          * @param expressions An array of expressions.
85989          * @param node A TemplateExpression node.
85990          */
85991         function addTemplateHead(expressions, node) {
85992             if (!shouldAddTemplateHead(node)) {
85993                 return;
85994             }
85995             expressions.push(ts.createLiteral(node.head.text));
85996         }
85997         /**
85998          * Visits and adds the template spans of a TemplateExpression to an array of expressions.
85999          *
86000          * @param expressions An array of expressions.
86001          * @param node A TemplateExpression node.
86002          */
86003         function addTemplateSpans(expressions, node) {
86004             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
86005                 var span = _a[_i];
86006                 expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
86007                 // Only emit if the literal is non-empty.
86008                 // The binary '+' operator is left-associative, so the first string concatenation
86009                 // with the head will force the result up to this point to be a string.
86010                 // Emitting a '+ ""' has no semantic effect for middles and tails.
86011                 if (span.literal.text.length !== 0) {
86012                     expressions.push(ts.createLiteral(span.literal.text));
86013                 }
86014             }
86015         }
86016         /**
86017          * Visits the `super` keyword
86018          */
86019         function visitSuperKeyword(isExpressionOfCall) {
86020             return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") :
86021                 ts.createFileLevelUniqueName("_super");
86022         }
86023         function visitMetaProperty(node) {
86024             if (node.keywordToken === 99 /* NewKeyword */ && node.name.escapedText === "target") {
86025                 hierarchyFacts |= 16384 /* NewTarget */;
86026                 return ts.createFileLevelUniqueName("_newTarget");
86027             }
86028             return node;
86029         }
86030         /**
86031          * Called by the printer just before a node is printed.
86032          *
86033          * @param hint A hint as to the intended usage of the node.
86034          * @param node The node to be printed.
86035          * @param emitCallback The callback used to emit the node.
86036          */
86037         function onEmitNode(hint, node, emitCallback) {
86038             if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
86039                 // If we are tracking a captured `this`, keep track of the enclosing function.
86040                 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
86041                     ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
86042                     : 65 /* FunctionIncludes */);
86043                 previousOnEmitNode(hint, node, emitCallback);
86044                 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
86045                 return;
86046             }
86047             previousOnEmitNode(hint, node, emitCallback);
86048         }
86049         /**
86050          * Enables a more costly code path for substitutions when we determine a source file
86051          * contains block-scoped bindings (e.g. `let` or `const`).
86052          */
86053         function enableSubstitutionsForBlockScopedBindings() {
86054             if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
86055                 enabledSubstitutions |= 2 /* BlockScopedBindings */;
86056                 context.enableSubstitution(75 /* Identifier */);
86057             }
86058         }
86059         /**
86060          * Enables a more costly code path for substitutions when we determine a source file
86061          * contains a captured `this`.
86062          */
86063         function enableSubstitutionsForCapturedThis() {
86064             if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
86065                 enabledSubstitutions |= 1 /* CapturedThis */;
86066                 context.enableSubstitution(104 /* ThisKeyword */);
86067                 context.enableEmitNotification(162 /* Constructor */);
86068                 context.enableEmitNotification(161 /* MethodDeclaration */);
86069                 context.enableEmitNotification(163 /* GetAccessor */);
86070                 context.enableEmitNotification(164 /* SetAccessor */);
86071                 context.enableEmitNotification(202 /* ArrowFunction */);
86072                 context.enableEmitNotification(201 /* FunctionExpression */);
86073                 context.enableEmitNotification(244 /* FunctionDeclaration */);
86074             }
86075         }
86076         /**
86077          * Hooks node substitutions.
86078          *
86079          * @param hint The context for the emitter.
86080          * @param node The node to substitute.
86081          */
86082         function onSubstituteNode(hint, node) {
86083             node = previousOnSubstituteNode(hint, node);
86084             if (hint === 1 /* Expression */) {
86085                 return substituteExpression(node);
86086             }
86087             if (ts.isIdentifier(node)) {
86088                 return substituteIdentifier(node);
86089             }
86090             return node;
86091         }
86092         /**
86093          * Hooks substitutions for non-expression identifiers.
86094          */
86095         function substituteIdentifier(node) {
86096             // Only substitute the identifier if we have enabled substitutions for block-scoped
86097             // bindings.
86098             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86099                 var original = ts.getParseTreeNode(node, ts.isIdentifier);
86100                 if (original && isNameOfDeclarationWithCollidingName(original)) {
86101                     return ts.setTextRange(ts.getGeneratedNameForNode(original), node);
86102                 }
86103             }
86104             return node;
86105         }
86106         /**
86107          * Determines whether a name is the name of a declaration with a colliding name.
86108          * NOTE: This function expects to be called with an original source tree node.
86109          *
86110          * @param node An original source tree node.
86111          */
86112         function isNameOfDeclarationWithCollidingName(node) {
86113             switch (node.parent.kind) {
86114                 case 191 /* BindingElement */:
86115                 case 245 /* ClassDeclaration */:
86116                 case 248 /* EnumDeclaration */:
86117                 case 242 /* VariableDeclaration */:
86118                     return node.parent.name === node
86119                         && resolver.isDeclarationWithCollidingName(node.parent);
86120             }
86121             return false;
86122         }
86123         /**
86124          * Substitutes an expression.
86125          *
86126          * @param node An Expression node.
86127          */
86128         function substituteExpression(node) {
86129             switch (node.kind) {
86130                 case 75 /* Identifier */:
86131                     return substituteExpressionIdentifier(node);
86132                 case 104 /* ThisKeyword */:
86133                     return substituteThisKeyword(node);
86134             }
86135             return node;
86136         }
86137         /**
86138          * Substitutes an expression identifier.
86139          *
86140          * @param node An Identifier node.
86141          */
86142         function substituteExpressionIdentifier(node) {
86143             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86144                 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
86145                 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
86146                     return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
86147                 }
86148             }
86149             return node;
86150         }
86151         function isPartOfClassBody(declaration, node) {
86152             var currentNode = ts.getParseTreeNode(node);
86153             if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
86154                 // if the node has no correlation to a parse tree node, its definitely not
86155                 // part of the body.
86156                 // if the node is outside of the document range of the declaration, its
86157                 // definitely not part of the body.
86158                 return false;
86159             }
86160             var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
86161             while (currentNode) {
86162                 if (currentNode === blockScope || currentNode === declaration) {
86163                     // if we are in the enclosing block scope of the declaration, we are definitely
86164                     // not inside the class body.
86165                     return false;
86166                 }
86167                 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
86168                     return true;
86169                 }
86170                 currentNode = currentNode.parent;
86171             }
86172             return false;
86173         }
86174         /**
86175          * Substitutes `this` when contained within an arrow function.
86176          *
86177          * @param node The ThisKeyword node.
86178          */
86179         function substituteThisKeyword(node) {
86180             if (enabledSubstitutions & 1 /* CapturedThis */
86181                 && hierarchyFacts & 16 /* CapturesThis */) {
86182                 return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node);
86183             }
86184             return node;
86185         }
86186         function getClassMemberPrefix(node, member) {
86187             return ts.hasModifier(member, 32 /* Static */)
86188                 ? ts.getInternalName(node)
86189                 : ts.createPropertyAccess(ts.getInternalName(node), "prototype");
86190         }
86191         function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
86192             if (!constructor || !hasExtendsClause) {
86193                 return false;
86194             }
86195             if (ts.some(constructor.parameters)) {
86196                 return false;
86197             }
86198             var statement = ts.firstOrUndefined(constructor.body.statements);
86199             if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 226 /* ExpressionStatement */) {
86200                 return false;
86201             }
86202             var statementExpression = statement.expression;
86203             if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 196 /* CallExpression */) {
86204                 return false;
86205             }
86206             var callTarget = statementExpression.expression;
86207             if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 102 /* SuperKeyword */) {
86208                 return false;
86209             }
86210             var callArgument = ts.singleOrUndefined(statementExpression.arguments);
86211             if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 213 /* SpreadElement */) {
86212                 return false;
86213             }
86214             var expression = callArgument.expression;
86215             return ts.isIdentifier(expression) && expression.escapedText === "arguments";
86216         }
86217     }
86218     ts.transformES2015 = transformES2015;
86219     function createExtendsHelper(context, name) {
86220         context.requestEmitHelper(ts.extendsHelper);
86221         return ts.createCall(ts.getUnscopedHelperName("__extends"), 
86222         /*typeArguments*/ undefined, [
86223             name,
86224             ts.createFileLevelUniqueName("_super")
86225         ]);
86226     }
86227     ts.extendsHelper = {
86228         name: "typescript:extends",
86229         importName: "__extends",
86230         scoped: false,
86231         priority: 0,
86232         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            })();"
86233     };
86234 })(ts || (ts = {}));
86235 /*@internal*/
86236 var ts;
86237 (function (ts) {
86238     /**
86239      * Transforms ES5 syntax into ES3 syntax.
86240      *
86241      * @param context Context and state information for the transformation.
86242      */
86243     function transformES5(context) {
86244         var compilerOptions = context.getCompilerOptions();
86245         // enable emit notification only if using --jsx preserve or react-native
86246         var previousOnEmitNode;
86247         var noSubstitution;
86248         if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
86249             previousOnEmitNode = context.onEmitNode;
86250             context.onEmitNode = onEmitNode;
86251             context.enableEmitNotification(268 /* JsxOpeningElement */);
86252             context.enableEmitNotification(269 /* JsxClosingElement */);
86253             context.enableEmitNotification(267 /* JsxSelfClosingElement */);
86254             noSubstitution = [];
86255         }
86256         var previousOnSubstituteNode = context.onSubstituteNode;
86257         context.onSubstituteNode = onSubstituteNode;
86258         context.enableSubstitution(194 /* PropertyAccessExpression */);
86259         context.enableSubstitution(281 /* PropertyAssignment */);
86260         return ts.chainBundle(transformSourceFile);
86261         /**
86262          * Transforms an ES5 source file to ES3.
86263          *
86264          * @param node A SourceFile
86265          */
86266         function transformSourceFile(node) {
86267             return node;
86268         }
86269         /**
86270          * Called by the printer just before a node is printed.
86271          *
86272          * @param hint A hint as to the intended usage of the node.
86273          * @param node The node to emit.
86274          * @param emitCallback A callback used to emit the node.
86275          */
86276         function onEmitNode(hint, node, emitCallback) {
86277             switch (node.kind) {
86278                 case 268 /* JsxOpeningElement */:
86279                 case 269 /* JsxClosingElement */:
86280                 case 267 /* JsxSelfClosingElement */:
86281                     var tagName = node.tagName;
86282                     noSubstitution[ts.getOriginalNodeId(tagName)] = true;
86283                     break;
86284             }
86285             previousOnEmitNode(hint, node, emitCallback);
86286         }
86287         /**
86288          * Hooks node substitutions.
86289          *
86290          * @param hint A hint as to the intended usage of the node.
86291          * @param node The node to substitute.
86292          */
86293         function onSubstituteNode(hint, node) {
86294             if (node.id && noSubstitution && noSubstitution[node.id]) {
86295                 return previousOnSubstituteNode(hint, node);
86296             }
86297             node = previousOnSubstituteNode(hint, node);
86298             if (ts.isPropertyAccessExpression(node)) {
86299                 return substitutePropertyAccessExpression(node);
86300             }
86301             else if (ts.isPropertyAssignment(node)) {
86302                 return substitutePropertyAssignment(node);
86303             }
86304             return node;
86305         }
86306         /**
86307          * Substitutes a PropertyAccessExpression whose name is a reserved word.
86308          *
86309          * @param node A PropertyAccessExpression
86310          */
86311         function substitutePropertyAccessExpression(node) {
86312             if (ts.isPrivateIdentifier(node.name)) {
86313                 return node;
86314             }
86315             var literalName = trySubstituteReservedName(node.name);
86316             if (literalName) {
86317                 return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node);
86318             }
86319             return node;
86320         }
86321         /**
86322          * Substitutes a PropertyAssignment whose name is a reserved word.
86323          *
86324          * @param node A PropertyAssignment
86325          */
86326         function substitutePropertyAssignment(node) {
86327             var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
86328             if (literalName) {
86329                 return ts.updatePropertyAssignment(node, literalName, node.initializer);
86330             }
86331             return node;
86332         }
86333         /**
86334          * If an identifier name is a reserved word, returns a string literal for the name.
86335          *
86336          * @param name An Identifier
86337          */
86338         function trySubstituteReservedName(name) {
86339             var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
86340             if (token !== undefined && token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */) {
86341                 return ts.setTextRange(ts.createLiteral(name), name);
86342             }
86343             return undefined;
86344         }
86345     }
86346     ts.transformES5 = transformES5;
86347 })(ts || (ts = {}));
86348 // Transforms generator functions into a compatible ES5 representation with similar runtime
86349 // semantics. This is accomplished by first transforming the body of each generator
86350 // function into an intermediate representation that is the compiled into a JavaScript
86351 // switch statement.
86352 //
86353 // Many functions in this transformer will contain comments indicating the expected
86354 // intermediate representation. For illustrative purposes, the following intermediate
86355 // language is used to define this intermediate representation:
86356 //
86357 //  .nop                            - Performs no operation.
86358 //  .local NAME, ...                - Define local variable declarations.
86359 //  .mark LABEL                     - Mark the location of a label.
86360 //  .br LABEL                       - Jump to a label. If jumping out of a protected
86361 //                                    region, all .finally blocks are executed.
86362 //  .brtrue LABEL, (x)              - Jump to a label IIF the expression `x` is truthy.
86363 //                                    If jumping out of a protected region, all .finally
86364 //                                    blocks are executed.
86365 //  .brfalse LABEL, (x)             - Jump to a label IIF the expression `x` is falsey.
86366 //                                    If jumping out of a protected region, all .finally
86367 //                                    blocks are executed.
86368 //  .yield (x)                      - Yield the value of the optional expression `x`.
86369 //                                    Resume at the next label.
86370 //  .yieldstar (x)                  - Delegate yield to the value of the optional
86371 //                                    expression `x`. Resume at the next label.
86372 //                                    NOTE: `x` must be an Iterator, not an Iterable.
86373 //  .loop CONTINUE, BREAK           - Marks the beginning of a loop. Any "continue" or
86374 //                                    "break" abrupt completions jump to the CONTINUE or
86375 //                                    BREAK labels, respectively.
86376 //  .endloop                        - Marks the end of a loop.
86377 //  .with (x)                       - Marks the beginning of a WithStatement block, using
86378 //                                    the supplied expression.
86379 //  .endwith                        - Marks the end of a WithStatement.
86380 //  .switch                         - Marks the beginning of a SwitchStatement.
86381 //  .endswitch                      - Marks the end of a SwitchStatement.
86382 //  .labeled NAME                   - Marks the beginning of a LabeledStatement with the
86383 //                                    supplied name.
86384 //  .endlabeled                     - Marks the end of a LabeledStatement.
86385 //  .try TRY, CATCH, FINALLY, END   - Marks the beginning of a protected region, and the
86386 //                                    labels for each block.
86387 //  .catch (x)                      - Marks the beginning of a catch block.
86388 //  .finally                        - Marks the beginning of a finally block.
86389 //  .endfinally                     - Marks the end of a finally block.
86390 //  .endtry                         - Marks the end of a protected region.
86391 //  .throw (x)                      - Throws the value of the expression `x`.
86392 //  .return (x)                     - Returns the value of the expression `x`.
86393 //
86394 // In addition, the illustrative intermediate representation introduces some special
86395 // variables:
86396 //
86397 //  %sent%                          - Either returns the next value sent to the generator,
86398 //                                    returns the result of a delegated yield, or throws
86399 //                                    the exception sent to the generator.
86400 //  %error%                         - Returns the value of the current exception in a
86401 //                                    catch block.
86402 //
86403 // This intermediate representation is then compiled into JavaScript syntax. The resulting
86404 // compilation output looks something like the following:
86405 //
86406 //  function f() {
86407 //      var /*locals*/;
86408 //      /*functions*/
86409 //      return __generator(function (state) {
86410 //          switch (state.label) {
86411 //              /*cases per label*/
86412 //          }
86413 //      });
86414 //  }
86415 //
86416 // Each of the above instructions corresponds to JavaScript emit similar to the following:
86417 //
86418 //  .local NAME                   | var NAME;
86419 // -------------------------------|----------------------------------------------
86420 //  .mark LABEL                   | case LABEL:
86421 // -------------------------------|----------------------------------------------
86422 //  .br LABEL                     |     return [3 /*break*/, LABEL];
86423 // -------------------------------|----------------------------------------------
86424 //  .brtrue LABEL, (x)            |     if (x) return [3 /*break*/, LABEL];
86425 // -------------------------------|----------------------------------------------
86426 //  .brfalse LABEL, (x)           |     if (!(x)) return [3, /*break*/, LABEL];
86427 // -------------------------------|----------------------------------------------
86428 //  .yield (x)                    |     return [4 /*yield*/, x];
86429 //  .mark RESUME                  | case RESUME:
86430 //      a = %sent%;               |     a = state.sent();
86431 // -------------------------------|----------------------------------------------
86432 //  .yieldstar (x)                |     return [5 /*yield**/, x];
86433 //  .mark RESUME                  | case RESUME:
86434 //      a = %sent%;               |     a = state.sent();
86435 // -------------------------------|----------------------------------------------
86436 //  .with (_a)                    |     with (_a) {
86437 //      a();                      |         a();
86438 //                                |     }
86439 //                                |     state.label = LABEL;
86440 //  .mark LABEL                   | case LABEL:
86441 //                                |     with (_a) {
86442 //      b();                      |         b();
86443 //                                |     }
86444 //  .endwith                      |
86445 // -------------------------------|----------------------------------------------
86446 //                                | case 0:
86447 //                                |     state.trys = [];
86448 //                                | ...
86449 //  .try TRY, CATCH, FINALLY, END |
86450 //  .mark TRY                     | case TRY:
86451 //                                |     state.trys.push([TRY, CATCH, FINALLY, END]);
86452 //  .nop                          |
86453 //      a();                      |     a();
86454 //  .br END                       |     return [3 /*break*/, END];
86455 //  .catch (e)                    |
86456 //  .mark CATCH                   | case CATCH:
86457 //                                |     e = state.sent();
86458 //      b();                      |     b();
86459 //  .br END                       |     return [3 /*break*/, END];
86460 //  .finally                      |
86461 //  .mark FINALLY                 | case FINALLY:
86462 //      c();                      |     c();
86463 //  .endfinally                   |     return [7 /*endfinally*/];
86464 //  .endtry                       |
86465 //  .mark END                     | case END:
86466 /*@internal*/
86467 var ts;
86468 (function (ts) {
86469     var OpCode;
86470     (function (OpCode) {
86471         OpCode[OpCode["Nop"] = 0] = "Nop";
86472         OpCode[OpCode["Statement"] = 1] = "Statement";
86473         OpCode[OpCode["Assign"] = 2] = "Assign";
86474         OpCode[OpCode["Break"] = 3] = "Break";
86475         OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
86476         OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
86477         OpCode[OpCode["Yield"] = 6] = "Yield";
86478         OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
86479         OpCode[OpCode["Return"] = 8] = "Return";
86480         OpCode[OpCode["Throw"] = 9] = "Throw";
86481         OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
86482     })(OpCode || (OpCode = {}));
86483     // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
86484     var BlockAction;
86485     (function (BlockAction) {
86486         BlockAction[BlockAction["Open"] = 0] = "Open";
86487         BlockAction[BlockAction["Close"] = 1] = "Close";
86488     })(BlockAction || (BlockAction = {}));
86489     // the kind for a generated code block in a FunctionBuilder
86490     var CodeBlockKind;
86491     (function (CodeBlockKind) {
86492         CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
86493         CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
86494         CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
86495         CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
86496         CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
86497     })(CodeBlockKind || (CodeBlockKind = {}));
86498     // the state for a generated code exception block
86499     var ExceptionBlockState;
86500     (function (ExceptionBlockState) {
86501         ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
86502         ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
86503         ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
86504         ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
86505     })(ExceptionBlockState || (ExceptionBlockState = {}));
86506     // NOTE: changes to this enum should be reflected in the __generator helper.
86507     var Instruction;
86508     (function (Instruction) {
86509         Instruction[Instruction["Next"] = 0] = "Next";
86510         Instruction[Instruction["Throw"] = 1] = "Throw";
86511         Instruction[Instruction["Return"] = 2] = "Return";
86512         Instruction[Instruction["Break"] = 3] = "Break";
86513         Instruction[Instruction["Yield"] = 4] = "Yield";
86514         Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
86515         Instruction[Instruction["Catch"] = 6] = "Catch";
86516         Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
86517     })(Instruction || (Instruction = {}));
86518     function getInstructionName(instruction) {
86519         switch (instruction) {
86520             case 2 /* Return */: return "return";
86521             case 3 /* Break */: return "break";
86522             case 4 /* Yield */: return "yield";
86523             case 5 /* YieldStar */: return "yield*";
86524             case 7 /* Endfinally */: return "endfinally";
86525             default: return undefined; // TODO: GH#18217
86526         }
86527     }
86528     function transformGenerators(context) {
86529         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
86530         var compilerOptions = context.getCompilerOptions();
86531         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
86532         var resolver = context.getEmitResolver();
86533         var previousOnSubstituteNode = context.onSubstituteNode;
86534         context.onSubstituteNode = onSubstituteNode;
86535         var renamedCatchVariables;
86536         var renamedCatchVariableDeclarations;
86537         var inGeneratorFunctionBody;
86538         var inStatementContainingYield;
86539         // The following three arrays store information about generated code blocks.
86540         // All three arrays are correlated by their index. This approach is used over allocating
86541         // objects to store the same information to avoid GC overhead.
86542         //
86543         var blocks; // Information about the code block
86544         var blockOffsets; // The operation offset at which a code block begins or ends
86545         var blockActions; // Whether the code block is opened or closed
86546         var blockStack; // A stack of currently open code blocks
86547         // Labels are used to mark locations in the code that can be the target of a Break (jump)
86548         // operation. These are translated into case clauses in a switch statement.
86549         // The following two arrays are correlated by their index. This approach is used over
86550         // allocating objects to store the same information to avoid GC overhead.
86551         //
86552         var labelOffsets; // The operation offset at which the label is defined.
86553         var labelExpressions; // The NumericLiteral nodes bound to each label.
86554         var nextLabelId = 1; // The next label id to use.
86555         // Operations store information about generated code for the function body. This
86556         // Includes things like statements, assignments, breaks (jumps), and yields.
86557         // The following three arrays are correlated by their index. This approach is used over
86558         // allocating objects to store the same information to avoid GC overhead.
86559         //
86560         var operations; // The operation to perform.
86561         var operationArguments; // The arguments to the operation.
86562         var operationLocations; // The source map location for the operation.
86563         var state; // The name of the state object used by the generator at runtime.
86564         // The following variables store information used by the `build` function:
86565         //
86566         var blockIndex = 0; // The index of the current block.
86567         var labelNumber = 0; // The current label number.
86568         var labelNumbers;
86569         var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
86570         var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
86571         var clauses; // The case clauses generated for labels.
86572         var statements; // The statements for the current label.
86573         var exceptionBlockStack; // A stack of containing exception blocks.
86574         var currentExceptionBlock; // The current exception block.
86575         var withBlockStack; // A stack containing `with` blocks.
86576         return ts.chainBundle(transformSourceFile);
86577         function transformSourceFile(node) {
86578             if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
86579                 return node;
86580             }
86581             var visited = ts.visitEachChild(node, visitor, context);
86582             ts.addEmitHelpers(visited, context.readEmitHelpers());
86583             return visited;
86584         }
86585         /**
86586          * Visits a node.
86587          *
86588          * @param node The node to visit.
86589          */
86590         function visitor(node) {
86591             var transformFlags = node.transformFlags;
86592             if (inStatementContainingYield) {
86593                 return visitJavaScriptInStatementContainingYield(node);
86594             }
86595             else if (inGeneratorFunctionBody) {
86596                 return visitJavaScriptInGeneratorFunctionBody(node);
86597             }
86598             else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
86599                 return visitGenerator(node);
86600             }
86601             else if (transformFlags & 512 /* ContainsGenerator */) {
86602                 return ts.visitEachChild(node, visitor, context);
86603             }
86604             else {
86605                 return node;
86606             }
86607         }
86608         /**
86609          * Visits a node that is contained within a statement that contains yield.
86610          *
86611          * @param node The node to visit.
86612          */
86613         function visitJavaScriptInStatementContainingYield(node) {
86614             switch (node.kind) {
86615                 case 228 /* DoStatement */:
86616                     return visitDoStatement(node);
86617                 case 229 /* WhileStatement */:
86618                     return visitWhileStatement(node);
86619                 case 237 /* SwitchStatement */:
86620                     return visitSwitchStatement(node);
86621                 case 238 /* LabeledStatement */:
86622                     return visitLabeledStatement(node);
86623                 default:
86624                     return visitJavaScriptInGeneratorFunctionBody(node);
86625             }
86626         }
86627         /**
86628          * Visits a node that is contained within a generator function.
86629          *
86630          * @param node The node to visit.
86631          */
86632         function visitJavaScriptInGeneratorFunctionBody(node) {
86633             switch (node.kind) {
86634                 case 244 /* FunctionDeclaration */:
86635                     return visitFunctionDeclaration(node);
86636                 case 201 /* FunctionExpression */:
86637                     return visitFunctionExpression(node);
86638                 case 163 /* GetAccessor */:
86639                 case 164 /* SetAccessor */:
86640                     return visitAccessorDeclaration(node);
86641                 case 225 /* VariableStatement */:
86642                     return visitVariableStatement(node);
86643                 case 230 /* ForStatement */:
86644                     return visitForStatement(node);
86645                 case 231 /* ForInStatement */:
86646                     return visitForInStatement(node);
86647                 case 234 /* BreakStatement */:
86648                     return visitBreakStatement(node);
86649                 case 233 /* ContinueStatement */:
86650                     return visitContinueStatement(node);
86651                 case 235 /* ReturnStatement */:
86652                     return visitReturnStatement(node);
86653                 default:
86654                     if (node.transformFlags & 262144 /* ContainsYield */) {
86655                         return visitJavaScriptContainingYield(node);
86656                     }
86657                     else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) {
86658                         return ts.visitEachChild(node, visitor, context);
86659                     }
86660                     else {
86661                         return node;
86662                     }
86663             }
86664         }
86665         /**
86666          * Visits a node that contains a YieldExpression.
86667          *
86668          * @param node The node to visit.
86669          */
86670         function visitJavaScriptContainingYield(node) {
86671             switch (node.kind) {
86672                 case 209 /* BinaryExpression */:
86673                     return visitBinaryExpression(node);
86674                 case 210 /* ConditionalExpression */:
86675                     return visitConditionalExpression(node);
86676                 case 212 /* YieldExpression */:
86677                     return visitYieldExpression(node);
86678                 case 192 /* ArrayLiteralExpression */:
86679                     return visitArrayLiteralExpression(node);
86680                 case 193 /* ObjectLiteralExpression */:
86681                     return visitObjectLiteralExpression(node);
86682                 case 195 /* ElementAccessExpression */:
86683                     return visitElementAccessExpression(node);
86684                 case 196 /* CallExpression */:
86685                     return visitCallExpression(node);
86686                 case 197 /* NewExpression */:
86687                     return visitNewExpression(node);
86688                 default:
86689                     return ts.visitEachChild(node, visitor, context);
86690             }
86691         }
86692         /**
86693          * Visits a generator function.
86694          *
86695          * @param node The node to visit.
86696          */
86697         function visitGenerator(node) {
86698             switch (node.kind) {
86699                 case 244 /* FunctionDeclaration */:
86700                     return visitFunctionDeclaration(node);
86701                 case 201 /* FunctionExpression */:
86702                     return visitFunctionExpression(node);
86703                 default:
86704                     return ts.Debug.failBadSyntaxKind(node);
86705             }
86706         }
86707         /**
86708          * Visits a function declaration.
86709          *
86710          * This will be called when one of the following conditions are met:
86711          * - The function declaration is a generator function.
86712          * - The function declaration is contained within the body of a generator function.
86713          *
86714          * @param node The node to visit.
86715          */
86716         function visitFunctionDeclaration(node) {
86717             // Currently, we only support generators that were originally async functions.
86718             if (node.asteriskToken) {
86719                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
86720                 /*decorators*/ undefined, node.modifiers, 
86721                 /*asteriskToken*/ undefined, node.name, 
86722                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86723                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86724                 /*location*/ node), node);
86725             }
86726             else {
86727                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86728                 var savedInStatementContainingYield = inStatementContainingYield;
86729                 inGeneratorFunctionBody = false;
86730                 inStatementContainingYield = false;
86731                 node = ts.visitEachChild(node, visitor, context);
86732                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86733                 inStatementContainingYield = savedInStatementContainingYield;
86734             }
86735             if (inGeneratorFunctionBody) {
86736                 // Function declarations in a generator function body are hoisted
86737                 // to the top of the lexical scope and elided from the current statement.
86738                 hoistFunctionDeclaration(node);
86739                 return undefined;
86740             }
86741             else {
86742                 return node;
86743             }
86744         }
86745         /**
86746          * Visits a function expression.
86747          *
86748          * This will be called when one of the following conditions are met:
86749          * - The function expression is a generator function.
86750          * - The function expression is contained within the body of a generator function.
86751          *
86752          * @param node The node to visit.
86753          */
86754         function visitFunctionExpression(node) {
86755             // Currently, we only support generators that were originally async functions.
86756             if (node.asteriskToken) {
86757                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
86758                 /*modifiers*/ undefined, 
86759                 /*asteriskToken*/ undefined, node.name, 
86760                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86761                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86762                 /*location*/ node), node);
86763             }
86764             else {
86765                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86766                 var savedInStatementContainingYield = inStatementContainingYield;
86767                 inGeneratorFunctionBody = false;
86768                 inStatementContainingYield = false;
86769                 node = ts.visitEachChild(node, visitor, context);
86770                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86771                 inStatementContainingYield = savedInStatementContainingYield;
86772             }
86773             return node;
86774         }
86775         /**
86776          * Visits a get or set accessor declaration.
86777          *
86778          * This will be called when one of the following conditions are met:
86779          * - The accessor is contained within the body of a generator function.
86780          *
86781          * @param node The node to visit.
86782          */
86783         function visitAccessorDeclaration(node) {
86784             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86785             var savedInStatementContainingYield = inStatementContainingYield;
86786             inGeneratorFunctionBody = false;
86787             inStatementContainingYield = false;
86788             node = ts.visitEachChild(node, visitor, context);
86789             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86790             inStatementContainingYield = savedInStatementContainingYield;
86791             return node;
86792         }
86793         /**
86794          * Transforms the body of a generator function declaration.
86795          *
86796          * @param node The function body to transform.
86797          */
86798         function transformGeneratorFunctionBody(body) {
86799             // Save existing generator state
86800             var statements = [];
86801             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86802             var savedInStatementContainingYield = inStatementContainingYield;
86803             var savedBlocks = blocks;
86804             var savedBlockOffsets = blockOffsets;
86805             var savedBlockActions = blockActions;
86806             var savedBlockStack = blockStack;
86807             var savedLabelOffsets = labelOffsets;
86808             var savedLabelExpressions = labelExpressions;
86809             var savedNextLabelId = nextLabelId;
86810             var savedOperations = operations;
86811             var savedOperationArguments = operationArguments;
86812             var savedOperationLocations = operationLocations;
86813             var savedState = state;
86814             // Initialize generator state
86815             inGeneratorFunctionBody = true;
86816             inStatementContainingYield = false;
86817             blocks = undefined;
86818             blockOffsets = undefined;
86819             blockActions = undefined;
86820             blockStack = undefined;
86821             labelOffsets = undefined;
86822             labelExpressions = undefined;
86823             nextLabelId = 1;
86824             operations = undefined;
86825             operationArguments = undefined;
86826             operationLocations = undefined;
86827             state = ts.createTempVariable(/*recordTempVariable*/ undefined);
86828             // Build the generator
86829             resumeLexicalEnvironment();
86830             var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
86831             transformAndEmitStatements(body.statements, statementOffset);
86832             var buildResult = build();
86833             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
86834             statements.push(ts.createReturn(buildResult));
86835             // Restore previous generator state
86836             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86837             inStatementContainingYield = savedInStatementContainingYield;
86838             blocks = savedBlocks;
86839             blockOffsets = savedBlockOffsets;
86840             blockActions = savedBlockActions;
86841             blockStack = savedBlockStack;
86842             labelOffsets = savedLabelOffsets;
86843             labelExpressions = savedLabelExpressions;
86844             nextLabelId = savedNextLabelId;
86845             operations = savedOperations;
86846             operationArguments = savedOperationArguments;
86847             operationLocations = savedOperationLocations;
86848             state = savedState;
86849             return ts.setTextRange(ts.createBlock(statements, body.multiLine), body);
86850         }
86851         /**
86852          * Visits a variable statement.
86853          *
86854          * This will be called when one of the following conditions are met:
86855          * - The variable statement is contained within the body of a generator function.
86856          *
86857          * @param node The node to visit.
86858          */
86859         function visitVariableStatement(node) {
86860             if (node.transformFlags & 262144 /* ContainsYield */) {
86861                 transformAndEmitVariableDeclarationList(node.declarationList);
86862                 return undefined;
86863             }
86864             else {
86865                 // Do not hoist custom prologues.
86866                 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
86867                     return node;
86868                 }
86869                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
86870                     var variable = _a[_i];
86871                     hoistVariableDeclaration(variable.name);
86872                 }
86873                 var variables = ts.getInitializedVariables(node.declarationList);
86874                 if (variables.length === 0) {
86875                     return undefined;
86876                 }
86877                 return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
86878             }
86879         }
86880         /**
86881          * Visits a binary expression.
86882          *
86883          * This will be called when one of the following conditions are met:
86884          * - The node contains a YieldExpression.
86885          *
86886          * @param node The node to visit.
86887          */
86888         function visitBinaryExpression(node) {
86889             var assoc = ts.getExpressionAssociativity(node);
86890             switch (assoc) {
86891                 case 0 /* Left */:
86892                     return visitLeftAssociativeBinaryExpression(node);
86893                 case 1 /* Right */:
86894                     return visitRightAssociativeBinaryExpression(node);
86895                 default:
86896                     return ts.Debug.assertNever(assoc);
86897             }
86898         }
86899         /**
86900          * Visits a right-associative binary expression containing `yield`.
86901          *
86902          * @param node The node to visit.
86903          */
86904         function visitRightAssociativeBinaryExpression(node) {
86905             var left = node.left, right = node.right;
86906             if (containsYield(right)) {
86907                 var target = void 0;
86908                 switch (left.kind) {
86909                     case 194 /* PropertyAccessExpression */:
86910                         // [source]
86911                         //      a.b = yield;
86912                         //
86913                         // [intermediate]
86914                         //  .local _a
86915                         //      _a = a;
86916                         //  .yield resumeLabel
86917                         //  .mark resumeLabel
86918                         //      _a.b = %sent%;
86919                         target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
86920                         break;
86921                     case 195 /* ElementAccessExpression */:
86922                         // [source]
86923                         //      a[b] = yield;
86924                         //
86925                         // [intermediate]
86926                         //  .local _a, _b
86927                         //      _a = a;
86928                         //      _b = b;
86929                         //  .yield resumeLabel
86930                         //  .mark resumeLabel
86931                         //      _a[_b] = %sent%;
86932                         target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
86933                         break;
86934                     default:
86935                         target = ts.visitNode(left, visitor, ts.isExpression);
86936                         break;
86937                 }
86938                 var operator = node.operatorToken.kind;
86939                 if (ts.isCompoundAssignment(operator)) {
86940                     return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
86941                 }
86942                 else {
86943                     return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression));
86944                 }
86945             }
86946             return ts.visitEachChild(node, visitor, context);
86947         }
86948         function visitLeftAssociativeBinaryExpression(node) {
86949             if (containsYield(node.right)) {
86950                 if (ts.isLogicalOperator(node.operatorToken.kind)) {
86951                     return visitLogicalBinaryExpression(node);
86952                 }
86953                 else if (node.operatorToken.kind === 27 /* CommaToken */) {
86954                     return visitCommaExpression(node);
86955                 }
86956                 // [source]
86957                 //      a() + (yield) + c()
86958                 //
86959                 // [intermediate]
86960                 //  .local _a
86961                 //      _a = a();
86962                 //  .yield resumeLabel
86963                 //      _a + %sent% + c()
86964                 var clone_6 = ts.getMutableClone(node);
86965                 clone_6.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression));
86966                 clone_6.right = ts.visitNode(node.right, visitor, ts.isExpression);
86967                 return clone_6;
86968             }
86969             return ts.visitEachChild(node, visitor, context);
86970         }
86971         /**
86972          * Visits a logical binary expression containing `yield`.
86973          *
86974          * @param node A node to visit.
86975          */
86976         function visitLogicalBinaryExpression(node) {
86977             // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
86978             // to be transformed as such:
86979             //
86980             // [source]
86981             //      x = a() && yield;
86982             //
86983             // [intermediate]
86984             //  .local _a
86985             //      _a = a();
86986             //  .brfalse resultLabel, (_a)
86987             //  .yield resumeLabel
86988             //  .mark resumeLabel
86989             //      _a = %sent%;
86990             //  .mark resultLabel
86991             //      x = _a;
86992             //
86993             // [source]
86994             //      x = a() || yield;
86995             //
86996             // [intermediate]
86997             //  .local _a
86998             //      _a = a();
86999             //  .brtrue resultLabel, (_a)
87000             //  .yield resumeLabel
87001             //  .mark resumeLabel
87002             //      _a = %sent%;
87003             //  .mark resultLabel
87004             //      x = _a;
87005             var resultLabel = defineLabel();
87006             var resultLocal = declareLocal();
87007             emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
87008             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
87009                 // Logical `&&` shortcuts when the left-hand operand is falsey.
87010                 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
87011             }
87012             else {
87013                 // Logical `||` shortcuts when the left-hand operand is truthy.
87014                 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
87015             }
87016             emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
87017             markLabel(resultLabel);
87018             return resultLocal;
87019         }
87020         /**
87021          * Visits a comma expression containing `yield`.
87022          *
87023          * @param node The node to visit.
87024          */
87025         function visitCommaExpression(node) {
87026             // [source]
87027             //      x = a(), yield, b();
87028             //
87029             // [intermediate]
87030             //      a();
87031             //  .yield resumeLabel
87032             //  .mark resumeLabel
87033             //      x = %sent%, b();
87034             var pendingExpressions = [];
87035             visit(node.left);
87036             visit(node.right);
87037             return ts.inlineExpressions(pendingExpressions);
87038             function visit(node) {
87039                 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
87040                     visit(node.left);
87041                     visit(node.right);
87042                 }
87043                 else {
87044                     if (containsYield(node) && pendingExpressions.length > 0) {
87045                         emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]);
87046                         pendingExpressions = [];
87047                     }
87048                     pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
87049                 }
87050             }
87051         }
87052         /**
87053          * Visits a conditional expression containing `yield`.
87054          *
87055          * @param node The node to visit.
87056          */
87057         function visitConditionalExpression(node) {
87058             // [source]
87059             //      x = a() ? yield : b();
87060             //
87061             // [intermediate]
87062             //  .local _a
87063             //  .brfalse whenFalseLabel, (a())
87064             //  .yield resumeLabel
87065             //  .mark resumeLabel
87066             //      _a = %sent%;
87067             //  .br resultLabel
87068             //  .mark whenFalseLabel
87069             //      _a = b();
87070             //  .mark resultLabel
87071             //      x = _a;
87072             // We only need to perform a specific transformation if a `yield` expression exists
87073             // in either the `whenTrue` or `whenFalse` branches.
87074             // A `yield` in the condition will be handled by the normal visitor.
87075             if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
87076                 var whenFalseLabel = defineLabel();
87077                 var resultLabel = defineLabel();
87078                 var resultLocal = declareLocal();
87079                 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
87080                 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
87081                 emitBreak(resultLabel);
87082                 markLabel(whenFalseLabel);
87083                 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
87084                 markLabel(resultLabel);
87085                 return resultLocal;
87086             }
87087             return ts.visitEachChild(node, visitor, context);
87088         }
87089         /**
87090          * Visits a `yield` expression.
87091          *
87092          * @param node The node to visit.
87093          */
87094         function visitYieldExpression(node) {
87095             // [source]
87096             //      x = yield a();
87097             //
87098             // [intermediate]
87099             //  .yield resumeLabel, (a())
87100             //  .mark resumeLabel
87101             //      x = %sent%;
87102             var resumeLabel = defineLabel();
87103             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
87104             if (node.asteriskToken) {
87105                 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
87106                     ? ts.createValuesHelper(context, expression, /*location*/ node)
87107                     : expression;
87108                 emitYieldStar(iterator, /*location*/ node);
87109             }
87110             else {
87111                 emitYield(expression, /*location*/ node);
87112             }
87113             markLabel(resumeLabel);
87114             return createGeneratorResume(/*location*/ node);
87115         }
87116         /**
87117          * Visits an ArrayLiteralExpression that contains a YieldExpression.
87118          *
87119          * @param node The node to visit.
87120          */
87121         function visitArrayLiteralExpression(node) {
87122             return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
87123         }
87124         /**
87125          * Visits an array of expressions containing one or more YieldExpression nodes
87126          * and returns an expression for the resulting value.
87127          *
87128          * @param elements The elements to visit.
87129          * @param multiLine Whether array literals created should be emitted on multiple lines.
87130          */
87131         function visitElements(elements, leadingElement, location, multiLine) {
87132             // [source]
87133             //      ar = [1, yield, 2];
87134             //
87135             // [intermediate]
87136             //  .local _a
87137             //      _a = [1];
87138             //  .yield resumeLabel
87139             //  .mark resumeLabel
87140             //      ar = _a.concat([%sent%, 2]);
87141             var numInitialElements = countInitialNodesWithoutYield(elements);
87142             var temp;
87143             if (numInitialElements > 0) {
87144                 temp = declareLocal();
87145                 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
87146                 emitAssignment(temp, ts.createArrayLiteral(leadingElement
87147                     ? __spreadArrays([leadingElement], initialElements) : initialElements));
87148                 leadingElement = undefined;
87149             }
87150             var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
87151             return temp
87152                 ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87153                 : ts.setTextRange(ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine), location);
87154             function reduceElement(expressions, element) {
87155                 if (containsYield(element) && expressions.length > 0) {
87156                     var hasAssignedTemp = temp !== undefined;
87157                     if (!temp) {
87158                         temp = declareLocal();
87159                     }
87160                     emitAssignment(temp, hasAssignedTemp
87161                         ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87162                         : ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine));
87163                     leadingElement = undefined;
87164                     expressions = [];
87165                 }
87166                 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
87167                 return expressions;
87168             }
87169         }
87170         function visitObjectLiteralExpression(node) {
87171             // [source]
87172             //      o = {
87173             //          a: 1,
87174             //          b: yield,
87175             //          c: 2
87176             //      };
87177             //
87178             // [intermediate]
87179             //  .local _a
87180             //      _a = {
87181             //          a: 1
87182             //      };
87183             //  .yield resumeLabel
87184             //  .mark resumeLabel
87185             //      o = (_a.b = %sent%,
87186             //          _a.c = 2,
87187             //          _a);
87188             var properties = node.properties;
87189             var multiLine = node.multiLine;
87190             var numInitialProperties = countInitialNodesWithoutYield(properties);
87191             var temp = declareLocal();
87192             emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
87193             var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
87194             expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
87195             return ts.inlineExpressions(expressions);
87196             function reduceProperty(expressions, property) {
87197                 if (containsYield(property) && expressions.length > 0) {
87198                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions)));
87199                     expressions = [];
87200                 }
87201                 var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp);
87202                 var visited = ts.visitNode(expression, visitor, ts.isExpression);
87203                 if (visited) {
87204                     if (multiLine) {
87205                         ts.startOnNewLine(visited);
87206                     }
87207                     expressions.push(visited);
87208                 }
87209                 return expressions;
87210             }
87211         }
87212         /**
87213          * Visits an ElementAccessExpression that contains a YieldExpression.
87214          *
87215          * @param node The node to visit.
87216          */
87217         function visitElementAccessExpression(node) {
87218             if (containsYield(node.argumentExpression)) {
87219                 // [source]
87220                 //      a = x[yield];
87221                 //
87222                 // [intermediate]
87223                 //  .local _a
87224                 //      _a = x;
87225                 //  .yield resumeLabel
87226                 //  .mark resumeLabel
87227                 //      a = _a[%sent%]
87228                 var clone_7 = ts.getMutableClone(node);
87229                 clone_7.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
87230                 clone_7.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression);
87231                 return clone_7;
87232             }
87233             return ts.visitEachChild(node, visitor, context);
87234         }
87235         function visitCallExpression(node) {
87236             if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
87237                 // [source]
87238                 //      a.b(1, yield, 2);
87239                 //
87240                 // [intermediate]
87241                 //  .local _a, _b, _c
87242                 //      _b = (_a = a).b;
87243                 //      _c = [1];
87244                 //  .yield resumeLabel
87245                 //  .mark resumeLabel
87246                 //      _b.apply(_a, _c.concat([%sent%, 2]));
87247                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
87248                 return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), 
87249                 /*location*/ node), node);
87250             }
87251             return ts.visitEachChild(node, visitor, context);
87252         }
87253         function visitNewExpression(node) {
87254             if (ts.forEach(node.arguments, containsYield)) {
87255                 // [source]
87256                 //      new a.b(1, yield, 2);
87257                 //
87258                 // [intermediate]
87259                 //  .local _a, _b, _c
87260                 //      _b = (_a = a.b).bind;
87261                 //      _c = [1];
87262                 //  .yield resumeLabel
87263                 //  .mark resumeLabel
87264                 //      new (_b.apply(_a, _c.concat([%sent%, 2])));
87265                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
87266                 return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, 
87267                 /*leadingElement*/ ts.createVoidZero())), 
87268                 /*typeArguments*/ undefined, []), node), node);
87269             }
87270             return ts.visitEachChild(node, visitor, context);
87271         }
87272         function transformAndEmitStatements(statements, start) {
87273             if (start === void 0) { start = 0; }
87274             var numStatements = statements.length;
87275             for (var i = start; i < numStatements; i++) {
87276                 transformAndEmitStatement(statements[i]);
87277             }
87278         }
87279         function transformAndEmitEmbeddedStatement(node) {
87280             if (ts.isBlock(node)) {
87281                 transformAndEmitStatements(node.statements);
87282             }
87283             else {
87284                 transformAndEmitStatement(node);
87285             }
87286         }
87287         function transformAndEmitStatement(node) {
87288             var savedInStatementContainingYield = inStatementContainingYield;
87289             if (!inStatementContainingYield) {
87290                 inStatementContainingYield = containsYield(node);
87291             }
87292             transformAndEmitStatementWorker(node);
87293             inStatementContainingYield = savedInStatementContainingYield;
87294         }
87295         function transformAndEmitStatementWorker(node) {
87296             switch (node.kind) {
87297                 case 223 /* Block */:
87298                     return transformAndEmitBlock(node);
87299                 case 226 /* ExpressionStatement */:
87300                     return transformAndEmitExpressionStatement(node);
87301                 case 227 /* IfStatement */:
87302                     return transformAndEmitIfStatement(node);
87303                 case 228 /* DoStatement */:
87304                     return transformAndEmitDoStatement(node);
87305                 case 229 /* WhileStatement */:
87306                     return transformAndEmitWhileStatement(node);
87307                 case 230 /* ForStatement */:
87308                     return transformAndEmitForStatement(node);
87309                 case 231 /* ForInStatement */:
87310                     return transformAndEmitForInStatement(node);
87311                 case 233 /* ContinueStatement */:
87312                     return transformAndEmitContinueStatement(node);
87313                 case 234 /* BreakStatement */:
87314                     return transformAndEmitBreakStatement(node);
87315                 case 235 /* ReturnStatement */:
87316                     return transformAndEmitReturnStatement(node);
87317                 case 236 /* WithStatement */:
87318                     return transformAndEmitWithStatement(node);
87319                 case 237 /* SwitchStatement */:
87320                     return transformAndEmitSwitchStatement(node);
87321                 case 238 /* LabeledStatement */:
87322                     return transformAndEmitLabeledStatement(node);
87323                 case 239 /* ThrowStatement */:
87324                     return transformAndEmitThrowStatement(node);
87325                 case 240 /* TryStatement */:
87326                     return transformAndEmitTryStatement(node);
87327                 default:
87328                     return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87329             }
87330         }
87331         function transformAndEmitBlock(node) {
87332             if (containsYield(node)) {
87333                 transformAndEmitStatements(node.statements);
87334             }
87335             else {
87336                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87337             }
87338         }
87339         function transformAndEmitExpressionStatement(node) {
87340             emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87341         }
87342         function transformAndEmitVariableDeclarationList(node) {
87343             for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
87344                 var variable = _a[_i];
87345                 var name = ts.getSynthesizedClone(variable.name);
87346                 ts.setCommentRange(name, variable.name);
87347                 hoistVariableDeclaration(name);
87348             }
87349             var variables = ts.getInitializedVariables(node);
87350             var numVariables = variables.length;
87351             var variablesWritten = 0;
87352             var pendingExpressions = [];
87353             while (variablesWritten < numVariables) {
87354                 for (var i = variablesWritten; i < numVariables; i++) {
87355                     var variable = variables[i];
87356                     if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
87357                         break;
87358                     }
87359                     pendingExpressions.push(transformInitializedVariable(variable));
87360                 }
87361                 if (pendingExpressions.length) {
87362                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
87363                     variablesWritten += pendingExpressions.length;
87364                     pendingExpressions = [];
87365                 }
87366             }
87367             return undefined;
87368         }
87369         function transformInitializedVariable(node) {
87370             return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
87371         }
87372         function transformAndEmitIfStatement(node) {
87373             if (containsYield(node)) {
87374                 // [source]
87375                 //      if (x)
87376                 //          /*thenStatement*/
87377                 //      else
87378                 //          /*elseStatement*/
87379                 //
87380                 // [intermediate]
87381                 //  .brfalse elseLabel, (x)
87382                 //      /*thenStatement*/
87383                 //  .br endLabel
87384                 //  .mark elseLabel
87385                 //      /*elseStatement*/
87386                 //  .mark endLabel
87387                 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
87388                     var endLabel = defineLabel();
87389                     var elseLabel = node.elseStatement ? defineLabel() : undefined;
87390                     emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
87391                     transformAndEmitEmbeddedStatement(node.thenStatement);
87392                     if (node.elseStatement) {
87393                         emitBreak(endLabel);
87394                         markLabel(elseLabel);
87395                         transformAndEmitEmbeddedStatement(node.elseStatement);
87396                     }
87397                     markLabel(endLabel);
87398                 }
87399                 else {
87400                     emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87401                 }
87402             }
87403             else {
87404                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87405             }
87406         }
87407         function transformAndEmitDoStatement(node) {
87408             if (containsYield(node)) {
87409                 // [source]
87410                 //      do {
87411                 //          /*body*/
87412                 //      }
87413                 //      while (i < 10);
87414                 //
87415                 // [intermediate]
87416                 //  .loop conditionLabel, endLabel
87417                 //  .mark loopLabel
87418                 //      /*body*/
87419                 //  .mark conditionLabel
87420                 //  .brtrue loopLabel, (i < 10)
87421                 //  .endloop
87422                 //  .mark endLabel
87423                 var conditionLabel = defineLabel();
87424                 var loopLabel = defineLabel();
87425                 beginLoopBlock(/*continueLabel*/ conditionLabel);
87426                 markLabel(loopLabel);
87427                 transformAndEmitEmbeddedStatement(node.statement);
87428                 markLabel(conditionLabel);
87429                 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87430                 endLoopBlock();
87431             }
87432             else {
87433                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87434             }
87435         }
87436         function visitDoStatement(node) {
87437             if (inStatementContainingYield) {
87438                 beginScriptLoopBlock();
87439                 node = ts.visitEachChild(node, visitor, context);
87440                 endLoopBlock();
87441                 return node;
87442             }
87443             else {
87444                 return ts.visitEachChild(node, visitor, context);
87445             }
87446         }
87447         function transformAndEmitWhileStatement(node) {
87448             if (containsYield(node)) {
87449                 // [source]
87450                 //      while (i < 10) {
87451                 //          /*body*/
87452                 //      }
87453                 //
87454                 // [intermediate]
87455                 //  .loop loopLabel, endLabel
87456                 //  .mark loopLabel
87457                 //  .brfalse endLabel, (i < 10)
87458                 //      /*body*/
87459                 //  .br loopLabel
87460                 //  .endloop
87461                 //  .mark endLabel
87462                 var loopLabel = defineLabel();
87463                 var endLabel = beginLoopBlock(loopLabel);
87464                 markLabel(loopLabel);
87465                 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87466                 transformAndEmitEmbeddedStatement(node.statement);
87467                 emitBreak(loopLabel);
87468                 endLoopBlock();
87469             }
87470             else {
87471                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87472             }
87473         }
87474         function visitWhileStatement(node) {
87475             if (inStatementContainingYield) {
87476                 beginScriptLoopBlock();
87477                 node = ts.visitEachChild(node, visitor, context);
87478                 endLoopBlock();
87479                 return node;
87480             }
87481             else {
87482                 return ts.visitEachChild(node, visitor, context);
87483             }
87484         }
87485         function transformAndEmitForStatement(node) {
87486             if (containsYield(node)) {
87487                 // [source]
87488                 //      for (var i = 0; i < 10; i++) {
87489                 //          /*body*/
87490                 //      }
87491                 //
87492                 // [intermediate]
87493                 //  .local i
87494                 //      i = 0;
87495                 //  .loop incrementLabel, endLoopLabel
87496                 //  .mark conditionLabel
87497                 //  .brfalse endLoopLabel, (i < 10)
87498                 //      /*body*/
87499                 //  .mark incrementLabel
87500                 //      i++;
87501                 //  .br conditionLabel
87502                 //  .endloop
87503                 //  .mark endLoopLabel
87504                 var conditionLabel = defineLabel();
87505                 var incrementLabel = defineLabel();
87506                 var endLabel = beginLoopBlock(incrementLabel);
87507                 if (node.initializer) {
87508                     var initializer = node.initializer;
87509                     if (ts.isVariableDeclarationList(initializer)) {
87510                         transformAndEmitVariableDeclarationList(initializer);
87511                     }
87512                     else {
87513                         emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
87514                     }
87515                 }
87516                 markLabel(conditionLabel);
87517                 if (node.condition) {
87518                     emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
87519                 }
87520                 transformAndEmitEmbeddedStatement(node.statement);
87521                 markLabel(incrementLabel);
87522                 if (node.incrementor) {
87523                     emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
87524                 }
87525                 emitBreak(conditionLabel);
87526                 endLoopBlock();
87527             }
87528             else {
87529                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87530             }
87531         }
87532         function visitForStatement(node) {
87533             if (inStatementContainingYield) {
87534                 beginScriptLoopBlock();
87535             }
87536             var initializer = node.initializer;
87537             if (initializer && ts.isVariableDeclarationList(initializer)) {
87538                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87539                     var variable = _a[_i];
87540                     hoistVariableDeclaration(variable.name);
87541                 }
87542                 var variables = ts.getInitializedVariables(initializer);
87543                 node = ts.updateFor(node, variables.length > 0
87544                     ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable))
87545                     : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87546             }
87547             else {
87548                 node = ts.visitEachChild(node, visitor, context);
87549             }
87550             if (inStatementContainingYield) {
87551                 endLoopBlock();
87552             }
87553             return node;
87554         }
87555         function transformAndEmitForInStatement(node) {
87556             // TODO(rbuckton): Source map locations
87557             if (containsYield(node)) {
87558                 // [source]
87559                 //      for (var p in o) {
87560                 //          /*body*/
87561                 //      }
87562                 //
87563                 // [intermediate]
87564                 //  .local _a, _b, _i
87565                 //      _a = [];
87566                 //      for (_b in o) _a.push(_b);
87567                 //      _i = 0;
87568                 //  .loop incrementLabel, endLoopLabel
87569                 //  .mark conditionLabel
87570                 //  .brfalse endLoopLabel, (_i < _a.length)
87571                 //      p = _a[_i];
87572                 //      /*body*/
87573                 //  .mark incrementLabel
87574                 //      _b++;
87575                 //  .br conditionLabel
87576                 //  .endloop
87577                 //  .mark endLoopLabel
87578                 var keysArray = declareLocal(); // _a
87579                 var key = declareLocal(); // _b
87580                 var keysIndex = ts.createLoopVariable(); // _i
87581                 var initializer = node.initializer;
87582                 hoistVariableDeclaration(keysIndex);
87583                 emitAssignment(keysArray, ts.createArrayLiteral());
87584                 emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), 
87585                 /*typeArguments*/ undefined, [key]))));
87586                 emitAssignment(keysIndex, ts.createLiteral(0));
87587                 var conditionLabel = defineLabel();
87588                 var incrementLabel = defineLabel();
87589                 var endLabel = beginLoopBlock(incrementLabel);
87590                 markLabel(conditionLabel);
87591                 emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length")));
87592                 var variable = void 0;
87593                 if (ts.isVariableDeclarationList(initializer)) {
87594                     for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87595                         var variable_1 = _a[_i];
87596                         hoistVariableDeclaration(variable_1.name);
87597                     }
87598                     variable = ts.getSynthesizedClone(initializer.declarations[0].name);
87599                 }
87600                 else {
87601                     variable = ts.visitNode(initializer, visitor, ts.isExpression);
87602                     ts.Debug.assert(ts.isLeftHandSideExpression(variable));
87603                 }
87604                 emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex));
87605                 transformAndEmitEmbeddedStatement(node.statement);
87606                 markLabel(incrementLabel);
87607                 emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex)));
87608                 emitBreak(conditionLabel);
87609                 endLoopBlock();
87610             }
87611             else {
87612                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87613             }
87614         }
87615         function visitForInStatement(node) {
87616             // [source]
87617             //      for (var x in a) {
87618             //          /*body*/
87619             //      }
87620             //
87621             // [intermediate]
87622             //  .local x
87623             //  .loop
87624             //      for (x in a) {
87625             //          /*body*/
87626             //      }
87627             //  .endloop
87628             if (inStatementContainingYield) {
87629                 beginScriptLoopBlock();
87630             }
87631             var initializer = node.initializer;
87632             if (ts.isVariableDeclarationList(initializer)) {
87633                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87634                     var variable = _a[_i];
87635                     hoistVariableDeclaration(variable.name);
87636                 }
87637                 node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87638             }
87639             else {
87640                 node = ts.visitEachChild(node, visitor, context);
87641             }
87642             if (inStatementContainingYield) {
87643                 endLoopBlock();
87644             }
87645             return node;
87646         }
87647         function transformAndEmitContinueStatement(node) {
87648             var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
87649             if (label > 0) {
87650                 emitBreak(label, /*location*/ node);
87651             }
87652             else {
87653                 // invalid continue without a containing loop. Leave the node as is, per #17875.
87654                 emitStatement(node);
87655             }
87656         }
87657         function visitContinueStatement(node) {
87658             if (inStatementContainingYield) {
87659                 var label = findContinueTarget(node.label && ts.idText(node.label));
87660                 if (label > 0) {
87661                     return createInlineBreak(label, /*location*/ node);
87662                 }
87663             }
87664             return ts.visitEachChild(node, visitor, context);
87665         }
87666         function transformAndEmitBreakStatement(node) {
87667             var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
87668             if (label > 0) {
87669                 emitBreak(label, /*location*/ node);
87670             }
87671             else {
87672                 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
87673                 emitStatement(node);
87674             }
87675         }
87676         function visitBreakStatement(node) {
87677             if (inStatementContainingYield) {
87678                 var label = findBreakTarget(node.label && ts.idText(node.label));
87679                 if (label > 0) {
87680                     return createInlineBreak(label, /*location*/ node);
87681                 }
87682             }
87683             return ts.visitEachChild(node, visitor, context);
87684         }
87685         function transformAndEmitReturnStatement(node) {
87686             emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87687             /*location*/ node);
87688         }
87689         function visitReturnStatement(node) {
87690             return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87691             /*location*/ node);
87692         }
87693         function transformAndEmitWithStatement(node) {
87694             if (containsYield(node)) {
87695                 // [source]
87696                 //      with (x) {
87697                 //          /*body*/
87698                 //      }
87699                 //
87700                 // [intermediate]
87701                 //  .with (x)
87702                 //      /*body*/
87703                 //  .endwith
87704                 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
87705                 transformAndEmitEmbeddedStatement(node.statement);
87706                 endWithBlock();
87707             }
87708             else {
87709                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87710             }
87711         }
87712         function transformAndEmitSwitchStatement(node) {
87713             if (containsYield(node.caseBlock)) {
87714                 // [source]
87715                 //      switch (x) {
87716                 //          case a:
87717                 //              /*caseStatements*/
87718                 //          case b:
87719                 //              /*caseStatements*/
87720                 //          default:
87721                 //              /*defaultStatements*/
87722                 //      }
87723                 //
87724                 // [intermediate]
87725                 //  .local _a
87726                 //  .switch endLabel
87727                 //      _a = x;
87728                 //      switch (_a) {
87729                 //          case a:
87730                 //  .br clauseLabels[0]
87731                 //      }
87732                 //      switch (_a) {
87733                 //          case b:
87734                 //  .br clauseLabels[1]
87735                 //      }
87736                 //  .br clauseLabels[2]
87737                 //  .mark clauseLabels[0]
87738                 //      /*caseStatements*/
87739                 //  .mark clauseLabels[1]
87740                 //      /*caseStatements*/
87741                 //  .mark clauseLabels[2]
87742                 //      /*caseStatements*/
87743                 //  .endswitch
87744                 //  .mark endLabel
87745                 var caseBlock = node.caseBlock;
87746                 var numClauses = caseBlock.clauses.length;
87747                 var endLabel = beginSwitchBlock();
87748                 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
87749                 // Create labels for each clause and find the index of the first default clause.
87750                 var clauseLabels = [];
87751                 var defaultClauseIndex = -1;
87752                 for (var i = 0; i < numClauses; i++) {
87753                     var clause = caseBlock.clauses[i];
87754                     clauseLabels.push(defineLabel());
87755                     if (clause.kind === 278 /* DefaultClause */ && defaultClauseIndex === -1) {
87756                         defaultClauseIndex = i;
87757                     }
87758                 }
87759                 // Emit switch statements for each run of case clauses either from the first case
87760                 // clause or the next case clause with a `yield` in its expression, up to the next
87761                 // case clause with a `yield` in its expression.
87762                 var clausesWritten = 0;
87763                 var pendingClauses = [];
87764                 while (clausesWritten < numClauses) {
87765                     var defaultClausesSkipped = 0;
87766                     for (var i = clausesWritten; i < numClauses; i++) {
87767                         var clause = caseBlock.clauses[i];
87768                         if (clause.kind === 277 /* CaseClause */) {
87769                             if (containsYield(clause.expression) && pendingClauses.length > 0) {
87770                                 break;
87771                             }
87772                             pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
87773                                 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
87774                             ]));
87775                         }
87776                         else {
87777                             defaultClausesSkipped++;
87778                         }
87779                     }
87780                     if (pendingClauses.length) {
87781                         emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses)));
87782                         clausesWritten += pendingClauses.length;
87783                         pendingClauses = [];
87784                     }
87785                     if (defaultClausesSkipped > 0) {
87786                         clausesWritten += defaultClausesSkipped;
87787                         defaultClausesSkipped = 0;
87788                     }
87789                 }
87790                 if (defaultClauseIndex >= 0) {
87791                     emitBreak(clauseLabels[defaultClauseIndex]);
87792                 }
87793                 else {
87794                     emitBreak(endLabel);
87795                 }
87796                 for (var i = 0; i < numClauses; i++) {
87797                     markLabel(clauseLabels[i]);
87798                     transformAndEmitStatements(caseBlock.clauses[i].statements);
87799                 }
87800                 endSwitchBlock();
87801             }
87802             else {
87803                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87804             }
87805         }
87806         function visitSwitchStatement(node) {
87807             if (inStatementContainingYield) {
87808                 beginScriptSwitchBlock();
87809             }
87810             node = ts.visitEachChild(node, visitor, context);
87811             if (inStatementContainingYield) {
87812                 endSwitchBlock();
87813             }
87814             return node;
87815         }
87816         function transformAndEmitLabeledStatement(node) {
87817             if (containsYield(node)) {
87818                 // [source]
87819                 //      x: {
87820                 //          /*body*/
87821                 //      }
87822                 //
87823                 // [intermediate]
87824                 //  .labeled "x", endLabel
87825                 //      /*body*/
87826                 //  .endlabeled
87827                 //  .mark endLabel
87828                 beginLabeledBlock(ts.idText(node.label));
87829                 transformAndEmitEmbeddedStatement(node.statement);
87830                 endLabeledBlock();
87831             }
87832             else {
87833                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87834             }
87835         }
87836         function visitLabeledStatement(node) {
87837             if (inStatementContainingYield) {
87838                 beginScriptLabeledBlock(ts.idText(node.label));
87839             }
87840             node = ts.visitEachChild(node, visitor, context);
87841             if (inStatementContainingYield) {
87842                 endLabeledBlock();
87843             }
87844             return node;
87845         }
87846         function transformAndEmitThrowStatement(node) {
87847             emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), 
87848             /*location*/ node);
87849         }
87850         function transformAndEmitTryStatement(node) {
87851             if (containsYield(node)) {
87852                 // [source]
87853                 //      try {
87854                 //          /*tryBlock*/
87855                 //      }
87856                 //      catch (e) {
87857                 //          /*catchBlock*/
87858                 //      }
87859                 //      finally {
87860                 //          /*finallyBlock*/
87861                 //      }
87862                 //
87863                 // [intermediate]
87864                 //  .local _a
87865                 //  .try tryLabel, catchLabel, finallyLabel, endLabel
87866                 //  .mark tryLabel
87867                 //  .nop
87868                 //      /*tryBlock*/
87869                 //  .br endLabel
87870                 //  .catch
87871                 //  .mark catchLabel
87872                 //      _a = %error%;
87873                 //      /*catchBlock*/
87874                 //  .br endLabel
87875                 //  .finally
87876                 //  .mark finallyLabel
87877                 //      /*finallyBlock*/
87878                 //  .endfinally
87879                 //  .endtry
87880                 //  .mark endLabel
87881                 beginExceptionBlock();
87882                 transformAndEmitEmbeddedStatement(node.tryBlock);
87883                 if (node.catchClause) {
87884                     beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
87885                     transformAndEmitEmbeddedStatement(node.catchClause.block);
87886                 }
87887                 if (node.finallyBlock) {
87888                     beginFinallyBlock();
87889                     transformAndEmitEmbeddedStatement(node.finallyBlock);
87890                 }
87891                 endExceptionBlock();
87892             }
87893             else {
87894                 emitStatement(ts.visitEachChild(node, visitor, context));
87895             }
87896         }
87897         function containsYield(node) {
87898             return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0;
87899         }
87900         function countInitialNodesWithoutYield(nodes) {
87901             var numNodes = nodes.length;
87902             for (var i = 0; i < numNodes; i++) {
87903                 if (containsYield(nodes[i])) {
87904                     return i;
87905                 }
87906             }
87907             return -1;
87908         }
87909         function onSubstituteNode(hint, node) {
87910             node = previousOnSubstituteNode(hint, node);
87911             if (hint === 1 /* Expression */) {
87912                 return substituteExpression(node);
87913             }
87914             return node;
87915         }
87916         function substituteExpression(node) {
87917             if (ts.isIdentifier(node)) {
87918                 return substituteExpressionIdentifier(node);
87919             }
87920             return node;
87921         }
87922         function substituteExpressionIdentifier(node) {
87923             if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
87924                 var original = ts.getOriginalNode(node);
87925                 if (ts.isIdentifier(original) && original.parent) {
87926                     var declaration = resolver.getReferencedValueDeclaration(original);
87927                     if (declaration) {
87928                         var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
87929                         if (name) {
87930                             var clone_8 = ts.getMutableClone(name);
87931                             ts.setSourceMapRange(clone_8, node);
87932                             ts.setCommentRange(clone_8, node);
87933                             return clone_8;
87934                         }
87935                     }
87936                 }
87937             }
87938             return node;
87939         }
87940         function cacheExpression(node) {
87941             if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
87942                 return node;
87943             }
87944             var temp = ts.createTempVariable(hoistVariableDeclaration);
87945             emitAssignment(temp, node, /*location*/ node);
87946             return temp;
87947         }
87948         function declareLocal(name) {
87949             var temp = name
87950                 ? ts.createUniqueName(name)
87951                 : ts.createTempVariable(/*recordTempVariable*/ undefined);
87952             hoistVariableDeclaration(temp);
87953             return temp;
87954         }
87955         /**
87956          * Defines a label, uses as the target of a Break operation.
87957          */
87958         function defineLabel() {
87959             if (!labelOffsets) {
87960                 labelOffsets = [];
87961             }
87962             var label = nextLabelId;
87963             nextLabelId++;
87964             labelOffsets[label] = -1;
87965             return label;
87966         }
87967         /**
87968          * Marks the current operation with the specified label.
87969          */
87970         function markLabel(label) {
87971             ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
87972             labelOffsets[label] = operations ? operations.length : 0;
87973         }
87974         /**
87975          * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
87976          *
87977          * @param block Information about the block.
87978          */
87979         function beginBlock(block) {
87980             if (!blocks) {
87981                 blocks = [];
87982                 blockActions = [];
87983                 blockOffsets = [];
87984                 blockStack = [];
87985             }
87986             var index = blockActions.length;
87987             blockActions[index] = 0 /* Open */;
87988             blockOffsets[index] = operations ? operations.length : 0;
87989             blocks[index] = block;
87990             blockStack.push(block);
87991             return index;
87992         }
87993         /**
87994          * Ends the current block operation.
87995          */
87996         function endBlock() {
87997             var block = peekBlock();
87998             if (block === undefined)
87999                 return ts.Debug.fail("beginBlock was never called.");
88000             var index = blockActions.length;
88001             blockActions[index] = 1 /* Close */;
88002             blockOffsets[index] = operations ? operations.length : 0;
88003             blocks[index] = block;
88004             blockStack.pop();
88005             return block;
88006         }
88007         /**
88008          * Gets the current open block.
88009          */
88010         function peekBlock() {
88011             return ts.lastOrUndefined(blockStack);
88012         }
88013         /**
88014          * Gets the kind of the current open block.
88015          */
88016         function peekBlockKind() {
88017             var block = peekBlock();
88018             return block && block.kind;
88019         }
88020         /**
88021          * Begins a code block for a generated `with` statement.
88022          *
88023          * @param expression An identifier representing expression for the `with` block.
88024          */
88025         function beginWithBlock(expression) {
88026             var startLabel = defineLabel();
88027             var endLabel = defineLabel();
88028             markLabel(startLabel);
88029             beginBlock({
88030                 kind: 1 /* With */,
88031                 expression: expression,
88032                 startLabel: startLabel,
88033                 endLabel: endLabel
88034             });
88035         }
88036         /**
88037          * Ends a code block for a generated `with` statement.
88038          */
88039         function endWithBlock() {
88040             ts.Debug.assert(peekBlockKind() === 1 /* With */);
88041             var block = endBlock();
88042             markLabel(block.endLabel);
88043         }
88044         /**
88045          * Begins a code block for a generated `try` statement.
88046          */
88047         function beginExceptionBlock() {
88048             var startLabel = defineLabel();
88049             var endLabel = defineLabel();
88050             markLabel(startLabel);
88051             beginBlock({
88052                 kind: 0 /* Exception */,
88053                 state: 0 /* Try */,
88054                 startLabel: startLabel,
88055                 endLabel: endLabel
88056             });
88057             emitNop();
88058             return endLabel;
88059         }
88060         /**
88061          * Enters the `catch` clause of a generated `try` statement.
88062          *
88063          * @param variable The catch variable.
88064          */
88065         function beginCatchBlock(variable) {
88066             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88067             // generated identifiers should already be unique within a file
88068             var name;
88069             if (ts.isGeneratedIdentifier(variable.name)) {
88070                 name = variable.name;
88071                 hoistVariableDeclaration(variable.name);
88072             }
88073             else {
88074                 var text = ts.idText(variable.name);
88075                 name = declareLocal(text);
88076                 if (!renamedCatchVariables) {
88077                     renamedCatchVariables = ts.createMap();
88078                     renamedCatchVariableDeclarations = [];
88079                     context.enableSubstitution(75 /* Identifier */);
88080                 }
88081                 renamedCatchVariables.set(text, true);
88082                 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
88083             }
88084             var exception = peekBlock();
88085             ts.Debug.assert(exception.state < 1 /* Catch */);
88086             var endLabel = exception.endLabel;
88087             emitBreak(endLabel);
88088             var catchLabel = defineLabel();
88089             markLabel(catchLabel);
88090             exception.state = 1 /* Catch */;
88091             exception.catchVariable = name;
88092             exception.catchLabel = catchLabel;
88093             emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, []));
88094             emitNop();
88095         }
88096         /**
88097          * Enters the `finally` block of a generated `try` statement.
88098          */
88099         function beginFinallyBlock() {
88100             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88101             var exception = peekBlock();
88102             ts.Debug.assert(exception.state < 2 /* Finally */);
88103             var endLabel = exception.endLabel;
88104             emitBreak(endLabel);
88105             var finallyLabel = defineLabel();
88106             markLabel(finallyLabel);
88107             exception.state = 2 /* Finally */;
88108             exception.finallyLabel = finallyLabel;
88109         }
88110         /**
88111          * Ends the code block for a generated `try` statement.
88112          */
88113         function endExceptionBlock() {
88114             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88115             var exception = endBlock();
88116             var state = exception.state;
88117             if (state < 2 /* Finally */) {
88118                 emitBreak(exception.endLabel);
88119             }
88120             else {
88121                 emitEndfinally();
88122             }
88123             markLabel(exception.endLabel);
88124             emitNop();
88125             exception.state = 3 /* Done */;
88126         }
88127         /**
88128          * Begins a code block that supports `break` or `continue` statements that are defined in
88129          * the source tree and not from generated code.
88130          *
88131          * @param labelText Names from containing labeled statements.
88132          */
88133         function beginScriptLoopBlock() {
88134             beginBlock({
88135                 kind: 3 /* Loop */,
88136                 isScript: true,
88137                 breakLabel: -1,
88138                 continueLabel: -1
88139             });
88140         }
88141         /**
88142          * Begins a code block that supports `break` or `continue` statements that are defined in
88143          * generated code. Returns a label used to mark the operation to which to jump when a
88144          * `break` statement targets this block.
88145          *
88146          * @param continueLabel A Label used to mark the operation to which to jump when a
88147          *                      `continue` statement targets this block.
88148          */
88149         function beginLoopBlock(continueLabel) {
88150             var breakLabel = defineLabel();
88151             beginBlock({
88152                 kind: 3 /* Loop */,
88153                 isScript: false,
88154                 breakLabel: breakLabel,
88155                 continueLabel: continueLabel,
88156             });
88157             return breakLabel;
88158         }
88159         /**
88160          * Ends a code block that supports `break` or `continue` statements that are defined in
88161          * generated code or in the source tree.
88162          */
88163         function endLoopBlock() {
88164             ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
88165             var block = endBlock();
88166             var breakLabel = block.breakLabel;
88167             if (!block.isScript) {
88168                 markLabel(breakLabel);
88169             }
88170         }
88171         /**
88172          * Begins a code block that supports `break` statements that are defined in the source
88173          * tree and not from generated code.
88174          *
88175          */
88176         function beginScriptSwitchBlock() {
88177             beginBlock({
88178                 kind: 2 /* Switch */,
88179                 isScript: true,
88180                 breakLabel: -1
88181             });
88182         }
88183         /**
88184          * Begins a code block that supports `break` statements that are defined in generated code.
88185          * Returns a label used to mark the operation to which to jump when a `break` statement
88186          * targets this block.
88187          */
88188         function beginSwitchBlock() {
88189             var breakLabel = defineLabel();
88190             beginBlock({
88191                 kind: 2 /* Switch */,
88192                 isScript: false,
88193                 breakLabel: breakLabel,
88194             });
88195             return breakLabel;
88196         }
88197         /**
88198          * Ends a code block that supports `break` statements that are defined in generated code.
88199          */
88200         function endSwitchBlock() {
88201             ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
88202             var block = endBlock();
88203             var breakLabel = block.breakLabel;
88204             if (!block.isScript) {
88205                 markLabel(breakLabel);
88206             }
88207         }
88208         function beginScriptLabeledBlock(labelText) {
88209             beginBlock({
88210                 kind: 4 /* Labeled */,
88211                 isScript: true,
88212                 labelText: labelText,
88213                 breakLabel: -1
88214             });
88215         }
88216         function beginLabeledBlock(labelText) {
88217             var breakLabel = defineLabel();
88218             beginBlock({
88219                 kind: 4 /* Labeled */,
88220                 isScript: false,
88221                 labelText: labelText,
88222                 breakLabel: breakLabel
88223             });
88224         }
88225         function endLabeledBlock() {
88226             ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
88227             var block = endBlock();
88228             if (!block.isScript) {
88229                 markLabel(block.breakLabel);
88230             }
88231         }
88232         /**
88233          * Indicates whether the provided block supports `break` statements.
88234          *
88235          * @param block A code block.
88236          */
88237         function supportsUnlabeledBreak(block) {
88238             return block.kind === 2 /* Switch */
88239                 || block.kind === 3 /* Loop */;
88240         }
88241         /**
88242          * Indicates whether the provided block supports `break` statements with labels.
88243          *
88244          * @param block A code block.
88245          */
88246         function supportsLabeledBreakOrContinue(block) {
88247             return block.kind === 4 /* Labeled */;
88248         }
88249         /**
88250          * Indicates whether the provided block supports `continue` statements.
88251          *
88252          * @param block A code block.
88253          */
88254         function supportsUnlabeledContinue(block) {
88255             return block.kind === 3 /* Loop */;
88256         }
88257         function hasImmediateContainingLabeledBlock(labelText, start) {
88258             for (var j = start; j >= 0; j--) {
88259                 var containingBlock = blockStack[j];
88260                 if (supportsLabeledBreakOrContinue(containingBlock)) {
88261                     if (containingBlock.labelText === labelText) {
88262                         return true;
88263                     }
88264                 }
88265                 else {
88266                     break;
88267                 }
88268             }
88269             return false;
88270         }
88271         /**
88272          * Finds the label that is the target for a `break` statement.
88273          *
88274          * @param labelText An optional name of a containing labeled statement.
88275          */
88276         function findBreakTarget(labelText) {
88277             if (blockStack) {
88278                 if (labelText) {
88279                     for (var i = blockStack.length - 1; i >= 0; i--) {
88280                         var block = blockStack[i];
88281                         if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
88282                             return block.breakLabel;
88283                         }
88284                         else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88285                             return block.breakLabel;
88286                         }
88287                     }
88288                 }
88289                 else {
88290                     for (var i = blockStack.length - 1; i >= 0; i--) {
88291                         var block = blockStack[i];
88292                         if (supportsUnlabeledBreak(block)) {
88293                             return block.breakLabel;
88294                         }
88295                     }
88296                 }
88297             }
88298             return 0;
88299         }
88300         /**
88301          * Finds the label that is the target for a `continue` statement.
88302          *
88303          * @param labelText An optional name of a containing labeled statement.
88304          */
88305         function findContinueTarget(labelText) {
88306             if (blockStack) {
88307                 if (labelText) {
88308                     for (var i = blockStack.length - 1; i >= 0; i--) {
88309                         var block = blockStack[i];
88310                         if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88311                             return block.continueLabel;
88312                         }
88313                     }
88314                 }
88315                 else {
88316                     for (var i = blockStack.length - 1; i >= 0; i--) {
88317                         var block = blockStack[i];
88318                         if (supportsUnlabeledContinue(block)) {
88319                             return block.continueLabel;
88320                         }
88321                     }
88322                 }
88323             }
88324             return 0;
88325         }
88326         /**
88327          * Creates an expression that can be used to indicate the value for a label.
88328          *
88329          * @param label A label.
88330          */
88331         function createLabel(label) {
88332             if (label !== undefined && label > 0) {
88333                 if (labelExpressions === undefined) {
88334                     labelExpressions = [];
88335                 }
88336                 var expression = ts.createLiteral(-1);
88337                 if (labelExpressions[label] === undefined) {
88338                     labelExpressions[label] = [expression];
88339                 }
88340                 else {
88341                     labelExpressions[label].push(expression);
88342                 }
88343                 return expression;
88344             }
88345             return ts.createOmittedExpression();
88346         }
88347         /**
88348          * Creates a numeric literal for the provided instruction.
88349          */
88350         function createInstruction(instruction) {
88351             var literal = ts.createLiteral(instruction);
88352             ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
88353             return literal;
88354         }
88355         /**
88356          * Creates a statement that can be used indicate a Break operation to the provided label.
88357          *
88358          * @param label A label.
88359          * @param location An optional source map location for the statement.
88360          */
88361         function createInlineBreak(label, location) {
88362             ts.Debug.assertLessThan(0, label, "Invalid label");
88363             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88364                 createInstruction(3 /* Break */),
88365                 createLabel(label)
88366             ])), location);
88367         }
88368         /**
88369          * Creates a statement that can be used indicate a Return operation.
88370          *
88371          * @param expression The expression for the return statement.
88372          * @param location An optional source map location for the statement.
88373          */
88374         function createInlineReturn(expression, location) {
88375             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88376                 ? [createInstruction(2 /* Return */), expression]
88377                 : [createInstruction(2 /* Return */)])), location);
88378         }
88379         /**
88380          * Creates an expression that can be used to resume from a Yield operation.
88381          */
88382         function createGeneratorResume(location) {
88383             return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), 
88384             /*typeArguments*/ undefined, []), location);
88385         }
88386         /**
88387          * Emits an empty instruction.
88388          */
88389         function emitNop() {
88390             emitWorker(0 /* Nop */);
88391         }
88392         /**
88393          * Emits a Statement.
88394          *
88395          * @param node A statement.
88396          */
88397         function emitStatement(node) {
88398             if (node) {
88399                 emitWorker(1 /* Statement */, [node]);
88400             }
88401             else {
88402                 emitNop();
88403             }
88404         }
88405         /**
88406          * Emits an Assignment operation.
88407          *
88408          * @param left The left-hand side of the assignment.
88409          * @param right The right-hand side of the assignment.
88410          * @param location An optional source map location for the assignment.
88411          */
88412         function emitAssignment(left, right, location) {
88413             emitWorker(2 /* Assign */, [left, right], location);
88414         }
88415         /**
88416          * Emits a Break operation to the specified label.
88417          *
88418          * @param label A label.
88419          * @param location An optional source map location for the assignment.
88420          */
88421         function emitBreak(label, location) {
88422             emitWorker(3 /* Break */, [label], location);
88423         }
88424         /**
88425          * Emits a Break operation to the specified label when a condition evaluates to a truthy
88426          * value at runtime.
88427          *
88428          * @param label A label.
88429          * @param condition The condition.
88430          * @param location An optional source map location for the assignment.
88431          */
88432         function emitBreakWhenTrue(label, condition, location) {
88433             emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
88434         }
88435         /**
88436          * Emits a Break to the specified label when a condition evaluates to a falsey value at
88437          * runtime.
88438          *
88439          * @param label A label.
88440          * @param condition The condition.
88441          * @param location An optional source map location for the assignment.
88442          */
88443         function emitBreakWhenFalse(label, condition, location) {
88444             emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
88445         }
88446         /**
88447          * Emits a YieldStar operation for the provided expression.
88448          *
88449          * @param expression An optional value for the yield operation.
88450          * @param location An optional source map location for the assignment.
88451          */
88452         function emitYieldStar(expression, location) {
88453             emitWorker(7 /* YieldStar */, [expression], location);
88454         }
88455         /**
88456          * Emits a Yield operation for the provided expression.
88457          *
88458          * @param expression An optional value for the yield operation.
88459          * @param location An optional source map location for the assignment.
88460          */
88461         function emitYield(expression, location) {
88462             emitWorker(6 /* Yield */, [expression], location);
88463         }
88464         /**
88465          * Emits a Return operation for the provided expression.
88466          *
88467          * @param expression An optional value for the operation.
88468          * @param location An optional source map location for the assignment.
88469          */
88470         function emitReturn(expression, location) {
88471             emitWorker(8 /* Return */, [expression], location);
88472         }
88473         /**
88474          * Emits a Throw operation for the provided expression.
88475          *
88476          * @param expression A value for the operation.
88477          * @param location An optional source map location for the assignment.
88478          */
88479         function emitThrow(expression, location) {
88480             emitWorker(9 /* Throw */, [expression], location);
88481         }
88482         /**
88483          * Emits an Endfinally operation. This is used to handle `finally` block semantics.
88484          */
88485         function emitEndfinally() {
88486             emitWorker(10 /* Endfinally */);
88487         }
88488         /**
88489          * Emits an operation.
88490          *
88491          * @param code The OpCode for the operation.
88492          * @param args The optional arguments for the operation.
88493          */
88494         function emitWorker(code, args, location) {
88495             if (operations === undefined) {
88496                 operations = [];
88497                 operationArguments = [];
88498                 operationLocations = [];
88499             }
88500             if (labelOffsets === undefined) {
88501                 // mark entry point
88502                 markLabel(defineLabel());
88503             }
88504             var operationIndex = operations.length;
88505             operations[operationIndex] = code;
88506             operationArguments[operationIndex] = args;
88507             operationLocations[operationIndex] = location;
88508         }
88509         /**
88510          * Builds the generator function body.
88511          */
88512         function build() {
88513             blockIndex = 0;
88514             labelNumber = 0;
88515             labelNumbers = undefined;
88516             lastOperationWasAbrupt = false;
88517             lastOperationWasCompletion = false;
88518             clauses = undefined;
88519             statements = undefined;
88520             exceptionBlockStack = undefined;
88521             currentExceptionBlock = undefined;
88522             withBlockStack = undefined;
88523             var buildResult = buildStatements();
88524             return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(
88525             /*modifiers*/ undefined, 
88526             /*asteriskToken*/ undefined, 
88527             /*name*/ undefined, 
88528             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], 
88529             /*type*/ undefined, ts.createBlock(buildResult, 
88530             /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
88531         }
88532         /**
88533          * Builds the statements for the generator function body.
88534          */
88535         function buildStatements() {
88536             if (operations) {
88537                 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
88538                     writeOperation(operationIndex);
88539                 }
88540                 flushFinalLabel(operations.length);
88541             }
88542             else {
88543                 flushFinalLabel(0);
88544             }
88545             if (clauses) {
88546                 var labelExpression = ts.createPropertyAccess(state, "label");
88547                 var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses));
88548                 return [ts.startOnNewLine(switchStatement)];
88549             }
88550             if (statements) {
88551                 return statements;
88552             }
88553             return [];
88554         }
88555         /**
88556          * Flush the current label and advance to a new label.
88557          */
88558         function flushLabel() {
88559             if (!statements) {
88560                 return;
88561             }
88562             appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
88563             lastOperationWasAbrupt = false;
88564             lastOperationWasCompletion = false;
88565             labelNumber++;
88566         }
88567         /**
88568          * Flush the final label of the generator function body.
88569          */
88570         function flushFinalLabel(operationIndex) {
88571             if (isFinalLabelReachable(operationIndex)) {
88572                 tryEnterLabel(operationIndex);
88573                 withBlockStack = undefined;
88574                 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
88575             }
88576             if (statements && clauses) {
88577                 appendLabel(/*markLabelEnd*/ false);
88578             }
88579             updateLabelExpressions();
88580         }
88581         /**
88582          * Tests whether the final label of the generator function body
88583          * is reachable by user code.
88584          */
88585         function isFinalLabelReachable(operationIndex) {
88586             // if the last operation was *not* a completion (return/throw) then
88587             // the final label is reachable.
88588             if (!lastOperationWasCompletion) {
88589                 return true;
88590             }
88591             // if there are no labels defined or referenced, then the final label is
88592             // not reachable.
88593             if (!labelOffsets || !labelExpressions) {
88594                 return false;
88595             }
88596             // if the label for this offset is referenced, then the final label
88597             // is reachable.
88598             for (var label = 0; label < labelOffsets.length; label++) {
88599                 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
88600                     return true;
88601                 }
88602             }
88603             return false;
88604         }
88605         /**
88606          * Appends a case clause for the last label and sets the new label.
88607          *
88608          * @param markLabelEnd Indicates that the transition between labels was a fall-through
88609          *                     from a previous case clause and the change in labels should be
88610          *                     reflected on the `state` object.
88611          */
88612         function appendLabel(markLabelEnd) {
88613             if (!clauses) {
88614                 clauses = [];
88615             }
88616             if (statements) {
88617                 if (withBlockStack) {
88618                     // The previous label was nested inside one or more `with` blocks, so we
88619                     // surround the statements in generated `with` blocks to create the same environment.
88620                     for (var i = withBlockStack.length - 1; i >= 0; i--) {
88621                         var withBlock = withBlockStack[i];
88622                         statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))];
88623                     }
88624                 }
88625                 if (currentExceptionBlock) {
88626                     // The previous label was nested inside of an exception block, so we must
88627                     // indicate entry into a protected region by pushing the label numbers
88628                     // for each block in the protected region.
88629                     var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
88630                     statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), 
88631                     /*typeArguments*/ undefined, [
88632                         ts.createArrayLiteral([
88633                             createLabel(startLabel),
88634                             createLabel(catchLabel),
88635                             createLabel(finallyLabel),
88636                             createLabel(endLabel)
88637                         ])
88638                     ])));
88639                     currentExceptionBlock = undefined;
88640                 }
88641                 if (markLabelEnd) {
88642                     // The case clause for the last label falls through to this label, so we
88643                     // add an assignment statement to reflect the change in labels.
88644                     statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1))));
88645                 }
88646             }
88647             clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || []));
88648             statements = undefined;
88649         }
88650         /**
88651          * Tries to enter into a new label at the current operation index.
88652          */
88653         function tryEnterLabel(operationIndex) {
88654             if (!labelOffsets) {
88655                 return;
88656             }
88657             for (var label = 0; label < labelOffsets.length; label++) {
88658                 if (labelOffsets[label] === operationIndex) {
88659                     flushLabel();
88660                     if (labelNumbers === undefined) {
88661                         labelNumbers = [];
88662                     }
88663                     if (labelNumbers[labelNumber] === undefined) {
88664                         labelNumbers[labelNumber] = [label];
88665                     }
88666                     else {
88667                         labelNumbers[labelNumber].push(label);
88668                     }
88669                 }
88670             }
88671         }
88672         /**
88673          * Updates literal expressions for labels with actual label numbers.
88674          */
88675         function updateLabelExpressions() {
88676             if (labelExpressions !== undefined && labelNumbers !== undefined) {
88677                 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
88678                     var labels = labelNumbers[labelNumber_1];
88679                     if (labels !== undefined) {
88680                         for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
88681                             var label = labels_1[_i];
88682                             var expressions = labelExpressions[label];
88683                             if (expressions !== undefined) {
88684                                 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
88685                                     var expression = expressions_1[_a];
88686                                     expression.text = String(labelNumber_1);
88687                                 }
88688                             }
88689                         }
88690                     }
88691                 }
88692             }
88693         }
88694         /**
88695          * Tries to enter or leave a code block.
88696          */
88697         function tryEnterOrLeaveBlock(operationIndex) {
88698             if (blocks) {
88699                 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
88700                     var block = blocks[blockIndex];
88701                     var blockAction = blockActions[blockIndex];
88702                     switch (block.kind) {
88703                         case 0 /* Exception */:
88704                             if (blockAction === 0 /* Open */) {
88705                                 if (!exceptionBlockStack) {
88706                                     exceptionBlockStack = [];
88707                                 }
88708                                 if (!statements) {
88709                                     statements = [];
88710                                 }
88711                                 exceptionBlockStack.push(currentExceptionBlock);
88712                                 currentExceptionBlock = block;
88713                             }
88714                             else if (blockAction === 1 /* Close */) {
88715                                 currentExceptionBlock = exceptionBlockStack.pop();
88716                             }
88717                             break;
88718                         case 1 /* With */:
88719                             if (blockAction === 0 /* Open */) {
88720                                 if (!withBlockStack) {
88721                                     withBlockStack = [];
88722                                 }
88723                                 withBlockStack.push(block);
88724                             }
88725                             else if (blockAction === 1 /* Close */) {
88726                                 withBlockStack.pop();
88727                             }
88728                             break;
88729                         // default: do nothing
88730                     }
88731                 }
88732             }
88733         }
88734         /**
88735          * Writes an operation as a statement to the current label's statement list.
88736          *
88737          * @param operation The OpCode of the operation
88738          */
88739         function writeOperation(operationIndex) {
88740             tryEnterLabel(operationIndex);
88741             tryEnterOrLeaveBlock(operationIndex);
88742             // early termination, nothing else to process in this label
88743             if (lastOperationWasAbrupt) {
88744                 return;
88745             }
88746             lastOperationWasAbrupt = false;
88747             lastOperationWasCompletion = false;
88748             var opcode = operations[operationIndex];
88749             if (opcode === 0 /* Nop */) {
88750                 return;
88751             }
88752             else if (opcode === 10 /* Endfinally */) {
88753                 return writeEndfinally();
88754             }
88755             var args = operationArguments[operationIndex];
88756             if (opcode === 1 /* Statement */) {
88757                 return writeStatement(args[0]);
88758             }
88759             var location = operationLocations[operationIndex];
88760             switch (opcode) {
88761                 case 2 /* Assign */:
88762                     return writeAssign(args[0], args[1], location);
88763                 case 3 /* Break */:
88764                     return writeBreak(args[0], location);
88765                 case 4 /* BreakWhenTrue */:
88766                     return writeBreakWhenTrue(args[0], args[1], location);
88767                 case 5 /* BreakWhenFalse */:
88768                     return writeBreakWhenFalse(args[0], args[1], location);
88769                 case 6 /* Yield */:
88770                     return writeYield(args[0], location);
88771                 case 7 /* YieldStar */:
88772                     return writeYieldStar(args[0], location);
88773                 case 8 /* Return */:
88774                     return writeReturn(args[0], location);
88775                 case 9 /* Throw */:
88776                     return writeThrow(args[0], location);
88777             }
88778         }
88779         /**
88780          * Writes a statement to the current label's statement list.
88781          *
88782          * @param statement A statement to write.
88783          */
88784         function writeStatement(statement) {
88785             if (statement) {
88786                 if (!statements) {
88787                     statements = [statement];
88788                 }
88789                 else {
88790                     statements.push(statement);
88791                 }
88792             }
88793         }
88794         /**
88795          * Writes an Assign operation to the current label's statement list.
88796          *
88797          * @param left The left-hand side of the assignment.
88798          * @param right The right-hand side of the assignment.
88799          * @param operationLocation The source map location for the operation.
88800          */
88801         function writeAssign(left, right, operationLocation) {
88802             writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation));
88803         }
88804         /**
88805          * Writes a Throw operation to the current label's statement list.
88806          *
88807          * @param expression The value to throw.
88808          * @param operationLocation The source map location for the operation.
88809          */
88810         function writeThrow(expression, operationLocation) {
88811             lastOperationWasAbrupt = true;
88812             lastOperationWasCompletion = true;
88813             writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation));
88814         }
88815         /**
88816          * Writes a Return operation to the current label's statement list.
88817          *
88818          * @param expression The value to return.
88819          * @param operationLocation The source map location for the operation.
88820          */
88821         function writeReturn(expression, operationLocation) {
88822             lastOperationWasAbrupt = true;
88823             lastOperationWasCompletion = true;
88824             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88825                 ? [createInstruction(2 /* Return */), expression]
88826                 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
88827         }
88828         /**
88829          * Writes a Break operation to the current label's statement list.
88830          *
88831          * @param label The label for the Break.
88832          * @param operationLocation The source map location for the operation.
88833          */
88834         function writeBreak(label, operationLocation) {
88835             lastOperationWasAbrupt = true;
88836             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88837                 createInstruction(3 /* Break */),
88838                 createLabel(label)
88839             ])), operationLocation), 384 /* NoTokenSourceMaps */));
88840         }
88841         /**
88842          * Writes a BreakWhenTrue operation to the current label's statement list.
88843          *
88844          * @param label The label for the Break.
88845          * @param condition The condition for the Break.
88846          * @param operationLocation The source map location for the operation.
88847          */
88848         function writeBreakWhenTrue(label, condition, operationLocation) {
88849             writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88850                 createInstruction(3 /* Break */),
88851                 createLabel(label)
88852             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
88853         }
88854         /**
88855          * Writes a BreakWhenFalse operation to the current label's statement list.
88856          *
88857          * @param label The label for the Break.
88858          * @param condition The condition for the Break.
88859          * @param operationLocation The source map location for the operation.
88860          */
88861         function writeBreakWhenFalse(label, condition, operationLocation) {
88862             writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88863                 createInstruction(3 /* Break */),
88864                 createLabel(label)
88865             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
88866         }
88867         /**
88868          * Writes a Yield operation to the current label's statement list.
88869          *
88870          * @param expression The expression to yield.
88871          * @param operationLocation The source map location for the operation.
88872          */
88873         function writeYield(expression, operationLocation) {
88874             lastOperationWasAbrupt = true;
88875             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88876                 ? [createInstruction(4 /* Yield */), expression]
88877                 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
88878         }
88879         /**
88880          * Writes a YieldStar instruction to the current label's statement list.
88881          *
88882          * @param expression The expression to yield.
88883          * @param operationLocation The source map location for the operation.
88884          */
88885         function writeYieldStar(expression, operationLocation) {
88886             lastOperationWasAbrupt = true;
88887             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88888                 createInstruction(5 /* YieldStar */),
88889                 expression
88890             ])), operationLocation), 384 /* NoTokenSourceMaps */));
88891         }
88892         /**
88893          * Writes an Endfinally instruction to the current label's statement list.
88894          */
88895         function writeEndfinally() {
88896             lastOperationWasAbrupt = true;
88897             writeStatement(ts.createReturn(ts.createArrayLiteral([
88898                 createInstruction(7 /* Endfinally */)
88899             ])));
88900         }
88901     }
88902     ts.transformGenerators = transformGenerators;
88903     function createGeneratorHelper(context, body) {
88904         context.requestEmitHelper(ts.generatorHelper);
88905         return ts.createCall(ts.getUnscopedHelperName("__generator"), 
88906         /*typeArguments*/ undefined, [ts.createThis(), body]);
88907     }
88908     // The __generator helper is used by down-level transformations to emulate the runtime
88909     // semantics of an ES2015 generator function. When called, this helper returns an
88910     // object that implements the Iterator protocol, in that it has `next`, `return`, and
88911     // `throw` methods that step through the generator when invoked.
88912     //
88913     // parameters:
88914     //  @param thisArg  The value to use as the `this` binding for the transformed generator body.
88915     //  @param body     A function that acts as the transformed generator body.
88916     //
88917     // variables:
88918     //  _       Persistent state for the generator that is shared between the helper and the
88919     //          generator body. The state object has the following members:
88920     //            sent() - A method that returns or throws the current completion value.
88921     //            label  - The next point at which to resume evaluation of the generator body.
88922     //            trys   - A stack of protected regions (try/catch/finally blocks).
88923     //            ops    - A stack of pending instructions when inside of a finally block.
88924     //  f       A value indicating whether the generator is executing.
88925     //  y       An iterator to delegate for a yield*.
88926     //  t       A temporary variable that holds one of the following values (note that these
88927     //          cases do not overlap):
88928     //          - The completion value when resuming from a `yield` or `yield*`.
88929     //          - The error value for a catch block.
88930     //          - The current protected region (array of try/catch/finally/end labels).
88931     //          - The verb (`next`, `throw`, or `return` method) to delegate to the expression
88932     //            of a `yield*`.
88933     //          - The result of evaluating the verb delegated to the expression of a `yield*`.
88934     //
88935     // functions:
88936     //  verb(n)     Creates a bound callback to the `step` function for opcode `n`.
88937     //  step(op)    Evaluates opcodes in a generator body until execution is suspended or
88938     //              completed.
88939     //
88940     // The __generator helper understands a limited set of instructions:
88941     //  0: next(value?)     - Start or resume the generator with the specified value.
88942     //  1: throw(error)     - Resume the generator with an exception. If the generator is
88943     //                        suspended inside of one or more protected regions, evaluates
88944     //                        any intervening finally blocks between the current label and
88945     //                        the nearest catch block or function boundary. If uncaught, the
88946     //                        exception is thrown to the caller.
88947     //  2: return(value?)   - Resume the generator as if with a return. If the generator is
88948     //                        suspended inside of one or more protected regions, evaluates any
88949     //                        intervening finally blocks.
88950     //  3: break(label)     - Jump to the specified label. If the label is outside of the
88951     //                        current protected region, evaluates any intervening finally
88952     //                        blocks.
88953     //  4: yield(value?)    - Yield execution to the caller with an optional value. When
88954     //                        resumed, the generator will continue at the next label.
88955     //  5: yield*(value)    - Delegates evaluation to the supplied iterator. When
88956     //                        delegation completes, the generator will continue at the next
88957     //                        label.
88958     //  6: catch(error)     - Handles an exception thrown from within the generator body. If
88959     //                        the current label is inside of one or more protected regions,
88960     //                        evaluates any intervening finally blocks between the current
88961     //                        label and the nearest catch block or function boundary. If
88962     //                        uncaught, the exception is thrown to the caller.
88963     //  7: endfinally       - Ends a finally block, resuming the last instruction prior to
88964     //                        entering a finally block.
88965     //
88966     // For examples of how these are used, see the comments in ./transformers/generators.ts
88967     ts.generatorHelper = {
88968         name: "typescript:generator",
88969         importName: "__generator",
88970         scoped: false,
88971         priority: 6,
88972         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            };"
88973     };
88974 })(ts || (ts = {}));
88975 /*@internal*/
88976 var ts;
88977 (function (ts) {
88978     function transformModule(context) {
88979         function getTransformModuleDelegate(moduleKind) {
88980             switch (moduleKind) {
88981                 case ts.ModuleKind.AMD: return transformAMDModule;
88982                 case ts.ModuleKind.UMD: return transformUMDModule;
88983                 default: return transformCommonJSModule;
88984             }
88985         }
88986         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
88987         var compilerOptions = context.getCompilerOptions();
88988         var resolver = context.getEmitResolver();
88989         var host = context.getEmitHost();
88990         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
88991         var moduleKind = ts.getEmitModuleKind(compilerOptions);
88992         var previousOnSubstituteNode = context.onSubstituteNode;
88993         var previousOnEmitNode = context.onEmitNode;
88994         context.onSubstituteNode = onSubstituteNode;
88995         context.onEmitNode = onEmitNode;
88996         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
88997         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
88998         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
88999         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
89000         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
89001         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
89002         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
89003         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
89004         var currentSourceFile; // The current file.
89005         var currentModuleInfo; // The ExternalModuleInfo for the current file.
89006         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
89007         var needUMDDynamicImportHelper;
89008         return ts.chainBundle(transformSourceFile);
89009         /**
89010          * Transforms the module aspects of a SourceFile.
89011          *
89012          * @param node The SourceFile node.
89013          */
89014         function transformSourceFile(node) {
89015             if (node.isDeclarationFile ||
89016                 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
89017                     node.transformFlags & 2097152 /* ContainsDynamicImport */ ||
89018                     (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
89019                 return node;
89020             }
89021             currentSourceFile = node;
89022             currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
89023             moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
89024             // Perform the transformation.
89025             var transformModule = getTransformModuleDelegate(moduleKind);
89026             var updated = transformModule(node);
89027             currentSourceFile = undefined;
89028             currentModuleInfo = undefined;
89029             needUMDDynamicImportHelper = false;
89030             return ts.aggregateTransformFlags(updated);
89031         }
89032         function shouldEmitUnderscoreUnderscoreESModule() {
89033             if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
89034                 return true;
89035             }
89036             return false;
89037         }
89038         /**
89039          * Transforms a SourceFile into a CommonJS module.
89040          *
89041          * @param node The SourceFile node.
89042          */
89043         function transformCommonJSModule(node) {
89044             startLexicalEnvironment();
89045             var statements = [];
89046             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
89047             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict && !ts.isJsonSourceFile(node), sourceElementVisitor);
89048             if (shouldEmitUnderscoreUnderscoreESModule()) {
89049                 ts.append(statements, createUnderscoreUnderscoreESModule());
89050             }
89051             if (ts.length(currentModuleInfo.exportedNames)) {
89052                 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())));
89053             }
89054             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89055             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89056             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
89057             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89058             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
89059             ts.addEmitHelpers(updated, context.readEmitHelpers());
89060             return updated;
89061         }
89062         /**
89063          * Transforms a SourceFile into an AMD module.
89064          *
89065          * @param node The SourceFile node.
89066          */
89067         function transformAMDModule(node) {
89068             var define = ts.createIdentifier("define");
89069             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89070             var jsonSourceFile = ts.isJsonSourceFile(node) && node;
89071             // An AMD define function has the following shape:
89072             //
89073             //     define(id?, dependencies?, factory);
89074             //
89075             // This has the shape of the following:
89076             //
89077             //     define(name, ["module1", "module2"], function (module1Alias) { ... }
89078             //
89079             // The location of the alias in the parameter list in the factory function needs to
89080             // match the position of the module name in the dependency list.
89081             //
89082             // To ensure this is true in cases of modules with no aliases, e.g.:
89083             //
89084             //     import "module"
89085             //
89086             // or
89087             //
89088             //     /// <amd-dependency path= "a.css" />
89089             //
89090             // we need to add modules without alias names to the end of the dependencies list
89091             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89092             // Create an updated SourceFile:
89093             //
89094             //     define(moduleName?, ["module1", "module2"], function ...
89095             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89096                 ts.createExpressionStatement(ts.createCall(define, 
89097                 /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89098                     // Add the dependency array argument:
89099                     //
89100                     //     ["require", "exports", module1", "module2", ...]
89101                     ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : __spreadArrays([
89102                         ts.createLiteral("require"),
89103                         ts.createLiteral("exports")
89104                     ], aliasedModuleNames, unaliasedModuleNames)),
89105                     // Add the module body function argument:
89106                     //
89107                     //     function (require, exports, module1, module2) ...
89108                     jsonSourceFile ?
89109                         jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() :
89110                         ts.createFunctionExpression(
89111                         /*modifiers*/ undefined, 
89112                         /*asteriskToken*/ undefined, 
89113                         /*name*/ undefined, 
89114                         /*typeParameters*/ undefined, __spreadArrays([
89115                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89116                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89117                         ], importAliasNames), 
89118                         /*type*/ undefined, transformAsynchronousModuleBody(node))
89119                 ])))
89120             ]), 
89121             /*location*/ node.statements));
89122             ts.addEmitHelpers(updated, context.readEmitHelpers());
89123             return updated;
89124         }
89125         /**
89126          * Transforms a SourceFile into a UMD module.
89127          *
89128          * @param node The SourceFile node.
89129          */
89130         function transformUMDModule(node) {
89131             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89132             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89133             var umdHeader = ts.createFunctionExpression(
89134             /*modifiers*/ undefined, 
89135             /*asteriskToken*/ undefined, 
89136             /*name*/ undefined, 
89137             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], 
89138             /*type*/ undefined, ts.setTextRange(ts.createBlock([
89139                 ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([
89140                     ts.createVariableStatement(
89141                     /*modifiers*/ undefined, [
89142                         ts.createVariableDeclaration("v", 
89143                         /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), 
89144                         /*typeArguments*/ undefined, [
89145                             ts.createIdentifier("require"),
89146                             ts.createIdentifier("exports")
89147                         ]))
89148                     ]),
89149                     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 */)
89150                 ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([
89151                     ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), 
89152                     /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89153                         ts.createArrayLiteral(__spreadArrays([
89154                             ts.createLiteral("require"),
89155                             ts.createLiteral("exports")
89156                         ], aliasedModuleNames, unaliasedModuleNames)),
89157                         ts.createIdentifier("factory")
89158                     ])))
89159                 ])))
89160             ], 
89161             /*multiLine*/ true), 
89162             /*location*/ undefined));
89163             // Create an updated SourceFile:
89164             //
89165             //  (function (factory) {
89166             //      if (typeof module === "object" && typeof module.exports === "object") {
89167             //          var v = factory(require, exports);
89168             //          if (v !== undefined) module.exports = v;
89169             //      }
89170             //      else if (typeof define === 'function' && define.amd) {
89171             //          define(["require", "exports"], factory);
89172             //      }
89173             //  })(function ...)
89174             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89175                 ts.createExpressionStatement(ts.createCall(umdHeader, 
89176                 /*typeArguments*/ undefined, [
89177                     // Add the module body function argument:
89178                     //
89179                     //     function (require, exports) ...
89180                     ts.createFunctionExpression(
89181                     /*modifiers*/ undefined, 
89182                     /*asteriskToken*/ undefined, 
89183                     /*name*/ undefined, 
89184                     /*typeParameters*/ undefined, __spreadArrays([
89185                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89186                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89187                     ], importAliasNames), 
89188                     /*type*/ undefined, transformAsynchronousModuleBody(node))
89189                 ]))
89190             ]), 
89191             /*location*/ node.statements));
89192             ts.addEmitHelpers(updated, context.readEmitHelpers());
89193             return updated;
89194         }
89195         /**
89196          * Collect the additional asynchronous dependencies for the module.
89197          *
89198          * @param node The source file.
89199          * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
89200          */
89201         function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
89202             // names of modules with corresponding parameter in the factory function
89203             var aliasedModuleNames = [];
89204             // names of modules with no corresponding parameters in factory function
89205             var unaliasedModuleNames = [];
89206             // names of the parameters in the factory function; these
89207             // parameters need to match the indexes of the corresponding
89208             // module names in aliasedModuleNames.
89209             var importAliasNames = [];
89210             // Fill in amd-dependency tags
89211             for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
89212                 var amdDependency = _a[_i];
89213                 if (amdDependency.name) {
89214                     aliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89215                     importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
89216                 }
89217                 else {
89218                     unaliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89219                 }
89220             }
89221             for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
89222                 var importNode = _c[_b];
89223                 // Find the name of the external module
89224                 var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89225                 // Find the name of the module alias, if there is one
89226                 var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile);
89227                 // It is possible that externalModuleName is undefined if it is not string literal.
89228                 // This can happen in the invalid import syntax.
89229                 // E.g : "import * from alias from 'someLib';"
89230                 if (externalModuleName) {
89231                     if (includeNonAmdDependencies && importAliasName) {
89232                         // Set emitFlags on the name of the classDeclaration
89233                         // This is so that when printer will not substitute the identifier
89234                         ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
89235                         aliasedModuleNames.push(externalModuleName);
89236                         importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
89237                     }
89238                     else {
89239                         unaliasedModuleNames.push(externalModuleName);
89240                     }
89241                 }
89242             }
89243             return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
89244         }
89245         function getAMDImportExpressionForImport(node) {
89246             if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) {
89247                 return undefined;
89248             }
89249             var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217
89250             var expr = getHelperExpressionForImport(node, name);
89251             if (expr === name) {
89252                 return undefined;
89253             }
89254             return ts.createExpressionStatement(ts.createAssignment(name, expr));
89255         }
89256         /**
89257          * Transforms a SourceFile into an AMD or UMD module body.
89258          *
89259          * @param node The SourceFile node.
89260          */
89261         function transformAsynchronousModuleBody(node) {
89262             startLexicalEnvironment();
89263             var statements = [];
89264             var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
89265             if (shouldEmitUnderscoreUnderscoreESModule()) {
89266                 ts.append(statements, createUnderscoreUnderscoreESModule());
89267             }
89268             if (ts.length(currentModuleInfo.exportedNames)) {
89269                 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())));
89270             }
89271             // Visit each statement of the module body.
89272             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89273             if (moduleKind === ts.ModuleKind.AMD) {
89274                 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
89275             }
89276             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89277             // Append the 'export =' statement if provided.
89278             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
89279             // End the lexical environment for the module body
89280             // and merge any new lexical declarations.
89281             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89282             var body = ts.createBlock(statements, /*multiLine*/ true);
89283             if (needUMDDynamicImportHelper) {
89284                 ts.addEmitHelper(body, dynamicImportUMDHelper);
89285             }
89286             return body;
89287         }
89288         /**
89289          * Adds the down-level representation of `export=` to the statement list if one exists
89290          * in the source file.
89291          *
89292          * @param statements The Statement list to modify.
89293          * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
89294          * return statement.
89295          */
89296         function addExportEqualsIfNeeded(statements, emitAsReturn) {
89297             if (currentModuleInfo.exportEquals) {
89298                 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
89299                 if (expressionResult) {
89300                     if (emitAsReturn) {
89301                         var statement = ts.createReturn(expressionResult);
89302                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89303                         ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
89304                         statements.push(statement);
89305                     }
89306                     else {
89307                         var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult));
89308                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89309                         ts.setEmitFlags(statement, 1536 /* NoComments */);
89310                         statements.push(statement);
89311                     }
89312                 }
89313             }
89314         }
89315         //
89316         // Top-Level Source Element Visitors
89317         //
89318         /**
89319          * Visits a node at the top level of the source file.
89320          *
89321          * @param node The node to visit.
89322          */
89323         function sourceElementVisitor(node) {
89324             switch (node.kind) {
89325                 case 254 /* ImportDeclaration */:
89326                     return visitImportDeclaration(node);
89327                 case 253 /* ImportEqualsDeclaration */:
89328                     return visitImportEqualsDeclaration(node);
89329                 case 260 /* ExportDeclaration */:
89330                     return visitExportDeclaration(node);
89331                 case 259 /* ExportAssignment */:
89332                     return visitExportAssignment(node);
89333                 case 225 /* VariableStatement */:
89334                     return visitVariableStatement(node);
89335                 case 244 /* FunctionDeclaration */:
89336                     return visitFunctionDeclaration(node);
89337                 case 245 /* ClassDeclaration */:
89338                     return visitClassDeclaration(node);
89339                 case 328 /* MergeDeclarationMarker */:
89340                     return visitMergeDeclarationMarker(node);
89341                 case 329 /* EndOfDeclarationMarker */:
89342                     return visitEndOfDeclarationMarker(node);
89343                 default:
89344                     return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89345             }
89346         }
89347         function moduleExpressionElementVisitor(node) {
89348             // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
89349             // as export/import statements are only transformed at the top level of a file.
89350             if (!(node.transformFlags & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) {
89351                 return node;
89352             }
89353             if (ts.isImportCall(node)) {
89354                 return visitImportCallExpression(node);
89355             }
89356             else if (ts.isDestructuringAssignment(node)) {
89357                 return visitDestructuringAssignment(node);
89358             }
89359             else {
89360                 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89361             }
89362         }
89363         function destructuringNeedsFlattening(node) {
89364             if (ts.isObjectLiteralExpression(node)) {
89365                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
89366                     var elem = _a[_i];
89367                     switch (elem.kind) {
89368                         case 281 /* PropertyAssignment */:
89369                             if (destructuringNeedsFlattening(elem.initializer)) {
89370                                 return true;
89371                             }
89372                             break;
89373                         case 282 /* ShorthandPropertyAssignment */:
89374                             if (destructuringNeedsFlattening(elem.name)) {
89375                                 return true;
89376                             }
89377                             break;
89378                         case 283 /* SpreadAssignment */:
89379                             if (destructuringNeedsFlattening(elem.expression)) {
89380                                 return true;
89381                             }
89382                             break;
89383                         case 161 /* MethodDeclaration */:
89384                         case 163 /* GetAccessor */:
89385                         case 164 /* SetAccessor */:
89386                             return false;
89387                         default: ts.Debug.assertNever(elem, "Unhandled object member kind");
89388                     }
89389                 }
89390             }
89391             else if (ts.isArrayLiteralExpression(node)) {
89392                 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
89393                     var elem = _c[_b];
89394                     if (ts.isSpreadElement(elem)) {
89395                         if (destructuringNeedsFlattening(elem.expression)) {
89396                             return true;
89397                         }
89398                     }
89399                     else if (destructuringNeedsFlattening(elem)) {
89400                         return true;
89401                     }
89402                 }
89403             }
89404             else if (ts.isIdentifier(node)) {
89405                 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
89406             }
89407             return false;
89408         }
89409         function visitDestructuringAssignment(node) {
89410             if (destructuringNeedsFlattening(node.left)) {
89411                 return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
89412             }
89413             return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89414         }
89415         function visitImportCallExpression(node) {
89416             var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
89417             var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
89418             switch (compilerOptions.module) {
89419                 case ts.ModuleKind.AMD:
89420                     return createImportCallExpressionAMD(argument, containsLexicalThis);
89421                 case ts.ModuleKind.UMD:
89422                     return createImportCallExpressionUMD(argument, containsLexicalThis);
89423                 case ts.ModuleKind.CommonJS:
89424                 default:
89425                     return createImportCallExpressionCommonJS(argument, containsLexicalThis);
89426             }
89427         }
89428         function createImportCallExpressionUMD(arg, containsLexicalThis) {
89429             // (function (factory) {
89430             //      ... (regular UMD)
89431             // }
89432             // })(function (require, exports, useSyncRequire) {
89433             //      "use strict";
89434             //      Object.defineProperty(exports, "__esModule", { value: true });
89435             //      var __syncRequire = typeof module === "object" && typeof module.exports === "object";
89436             //      var __resolved = new Promise(function (resolve) { resolve(); });
89437             //      .....
89438             //      __syncRequire
89439             //          ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
89440             //          : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89441             // });
89442             needUMDDynamicImportHelper = true;
89443             if (ts.isSimpleCopiableExpression(arg)) {
89444                 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */);
89445                 return ts.createConditional(
89446                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89447                 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), 
89448                 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
89449             }
89450             else {
89451                 var temp = ts.createTempVariable(hoistVariableDeclaration);
89452                 return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(
89453                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89454                 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), 
89455                 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
89456             }
89457         }
89458         function createImportCallExpressionAMD(arg, containsLexicalThis) {
89459             // improt("./blah")
89460             // emit as
89461             // define(["require", "exports", "blah"], function (require, exports) {
89462             //     ...
89463             //     new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89464             // });
89465             var resolve = ts.createUniqueName("resolve");
89466             var reject = ts.createUniqueName("reject");
89467             var parameters = [
89468                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
89469                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
89470             ];
89471             var body = ts.createBlock([
89472                 ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), 
89473                 /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject]))
89474             ]);
89475             var func;
89476             if (languageVersion >= 2 /* ES2015 */) {
89477                 func = ts.createArrowFunction(
89478                 /*modifiers*/ undefined, 
89479                 /*typeParameters*/ undefined, parameters, 
89480                 /*type*/ undefined, 
89481                 /*equalsGreaterThanToken*/ undefined, body);
89482             }
89483             else {
89484                 func = ts.createFunctionExpression(
89485                 /*modifiers*/ undefined, 
89486                 /*asteriskToken*/ undefined, 
89487                 /*name*/ undefined, 
89488                 /*typeParameters*/ undefined, parameters, 
89489                 /*type*/ undefined, body);
89490                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89491                 // that this new function expression indicates it captures 'this' so that the
89492                 // es2015 transformer will properly substitute 'this' with '_this'.
89493                 if (containsLexicalThis) {
89494                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89495                 }
89496             }
89497             var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
89498             if (compilerOptions.esModuleInterop) {
89499                 context.requestEmitHelper(ts.importStarHelper);
89500                 return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getUnscopedHelperName("__importStar")]);
89501             }
89502             return promise;
89503         }
89504         function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
89505             // import("./blah")
89506             // emit as
89507             // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
89508             // We have to wrap require in then callback so that require is done in asynchronously
89509             // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
89510             var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
89511             var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
89512             if (compilerOptions.esModuleInterop) {
89513                 context.requestEmitHelper(ts.importStarHelper);
89514                 requireCall = ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
89515             }
89516             var func;
89517             if (languageVersion >= 2 /* ES2015 */) {
89518                 func = ts.createArrowFunction(
89519                 /*modifiers*/ undefined, 
89520                 /*typeParameters*/ undefined, 
89521                 /*parameters*/ [], 
89522                 /*type*/ undefined, 
89523                 /*equalsGreaterThanToken*/ undefined, requireCall);
89524             }
89525             else {
89526                 func = ts.createFunctionExpression(
89527                 /*modifiers*/ undefined, 
89528                 /*asteriskToken*/ undefined, 
89529                 /*name*/ undefined, 
89530                 /*typeParameters*/ undefined, 
89531                 /*parameters*/ [], 
89532                 /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)]));
89533                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89534                 // that this new function expression indicates it captures 'this' so that the
89535                 // es2015 transformer will properly substitute 'this' with '_this'.
89536                 if (containsLexicalThis) {
89537                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89538                 }
89539             }
89540             return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
89541         }
89542         function getHelperExpressionForExport(node, innerExpr) {
89543             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89544                 return innerExpr;
89545             }
89546             if (ts.getExportNeedsImportStarHelper(node)) {
89547                 context.requestEmitHelper(ts.importStarHelper);
89548                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89549             }
89550             return innerExpr;
89551         }
89552         function getHelperExpressionForImport(node, innerExpr) {
89553             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89554                 return innerExpr;
89555             }
89556             if (ts.getImportNeedsImportStarHelper(node)) {
89557                 context.requestEmitHelper(ts.importStarHelper);
89558                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89559             }
89560             if (ts.getImportNeedsImportDefaultHelper(node)) {
89561                 context.requestEmitHelper(ts.importDefaultHelper);
89562                 return ts.createCall(ts.getUnscopedHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
89563             }
89564             return innerExpr;
89565         }
89566         /**
89567          * Visits an ImportDeclaration node.
89568          *
89569          * @param node The node to visit.
89570          */
89571         function visitImportDeclaration(node) {
89572             var statements;
89573             var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
89574             if (moduleKind !== ts.ModuleKind.AMD) {
89575                 if (!node.importClause) {
89576                     // import "mod";
89577                     return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node);
89578                 }
89579                 else {
89580                     var variables = [];
89581                     if (namespaceDeclaration && !ts.isDefaultImport(node)) {
89582                         // import * as n from "mod";
89583                         variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89584                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89585                     }
89586                     else {
89587                         // import d from "mod";
89588                         // import { x, y } from "mod";
89589                         // import d, { x, y } from "mod";
89590                         // import d, * as n from "mod";
89591                         variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), 
89592                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89593                         if (namespaceDeclaration && ts.isDefaultImport(node)) {
89594                             variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89595                             /*type*/ undefined, ts.getGeneratedNameForNode(node)));
89596                         }
89597                     }
89598                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89599                     /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), 
89600                     /*location*/ node), 
89601                     /*original*/ node));
89602                 }
89603             }
89604             else if (namespaceDeclaration && ts.isDefaultImport(node)) {
89605                 // import d, * as n from "mod";
89606                 statements = ts.append(statements, ts.createVariableStatement(
89607                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
89608                     ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89609                     /*type*/ undefined, ts.getGeneratedNameForNode(node)), 
89610                     /*location*/ node), 
89611                     /*original*/ node)
89612                 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
89613             }
89614             if (hasAssociatedEndOfDeclarationMarker(node)) {
89615                 // Defer exports until we encounter an EndOfDeclarationMarker node
89616                 var id = ts.getOriginalNodeId(node);
89617                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
89618             }
89619             else {
89620                 statements = appendExportsOfImportDeclaration(statements, node);
89621             }
89622             return ts.singleOrMany(statements);
89623         }
89624         /**
89625          * Creates a `require()` call to import an external module.
89626          *
89627          * @param importNode The declararation to import.
89628          */
89629         function createRequireCall(importNode) {
89630             var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89631             var args = [];
89632             if (moduleName) {
89633                 args.push(moduleName);
89634             }
89635             return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args);
89636         }
89637         /**
89638          * Visits an ImportEqualsDeclaration node.
89639          *
89640          * @param node The node to visit.
89641          */
89642         function visitImportEqualsDeclaration(node) {
89643             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
89644             var statements;
89645             if (moduleKind !== ts.ModuleKind.AMD) {
89646                 if (ts.hasModifier(node, 1 /* Export */)) {
89647                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
89648                 }
89649                 else {
89650                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89651                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89652                         ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), 
89653                         /*type*/ undefined, createRequireCall(node))
89654                     ], 
89655                     /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
89656                 }
89657             }
89658             else {
89659                 if (ts.hasModifier(node, 1 /* Export */)) {
89660                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node));
89661                 }
89662             }
89663             if (hasAssociatedEndOfDeclarationMarker(node)) {
89664                 // Defer exports until we encounter an EndOfDeclarationMarker node
89665                 var id = ts.getOriginalNodeId(node);
89666                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
89667             }
89668             else {
89669                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
89670             }
89671             return ts.singleOrMany(statements);
89672         }
89673         /**
89674          * Visits an ExportDeclaration node.
89675          *
89676          * @param The node to visit.
89677          */
89678         function visitExportDeclaration(node) {
89679             if (!node.moduleSpecifier) {
89680                 // Elide export declarations with no module specifier as they are handled
89681                 // elsewhere.
89682                 return undefined;
89683             }
89684             var generatedName = ts.getGeneratedNameForNode(node);
89685             if (node.exportClause && ts.isNamedExports(node.exportClause)) {
89686                 var statements = [];
89687                 // export { x, y } from "mod";
89688                 if (moduleKind !== ts.ModuleKind.AMD) {
89689                     statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89690                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89691                         ts.createVariableDeclaration(generatedName, 
89692                         /*type*/ undefined, createRequireCall(node))
89693                     ])), 
89694                     /*location*/ node), 
89695                     /* original */ node));
89696                 }
89697                 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
89698                     var specifier = _a[_i];
89699                     if (languageVersion === 0 /* ES3 */) {
89700                         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));
89701                     }
89702                     else {
89703                         var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name);
89704                         statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier));
89705                     }
89706                 }
89707                 return ts.singleOrMany(statements);
89708             }
89709             else if (node.exportClause) {
89710                 var statements = [];
89711                 // export * as ns from "mod";
89712                 statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getSynthesizedClone(node.exportClause.name), moduleKind !== ts.ModuleKind.AMD ?
89713                     getHelperExpressionForExport(node, createRequireCall(node)) :
89714                     ts.createIdentifier(ts.idText(node.exportClause.name)))), node), node));
89715                 return ts.singleOrMany(statements);
89716             }
89717             else {
89718                 // export * from "mod";
89719                 return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
89720             }
89721         }
89722         /**
89723          * Visits an ExportAssignment node.
89724          *
89725          * @param node The node to visit.
89726          */
89727         function visitExportAssignment(node) {
89728             if (node.isExportEquals) {
89729                 return undefined;
89730             }
89731             var statements;
89732             var original = node.original;
89733             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
89734                 // Defer exports until we encounter an EndOfDeclarationMarker node
89735                 var id = ts.getOriginalNodeId(node);
89736                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89737             }
89738             else {
89739                 statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89740             }
89741             return ts.singleOrMany(statements);
89742         }
89743         /**
89744          * Visits a FunctionDeclaration node.
89745          *
89746          * @param node The node to visit.
89747          */
89748         function visitFunctionDeclaration(node) {
89749             var statements;
89750             if (ts.hasModifier(node, 1 /* Export */)) {
89751                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
89752                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89753                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), 
89754                 /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), 
89755                 /*location*/ node), 
89756                 /*original*/ node));
89757             }
89758             else {
89759                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89760             }
89761             if (hasAssociatedEndOfDeclarationMarker(node)) {
89762                 // Defer exports until we encounter an EndOfDeclarationMarker node
89763                 var id = ts.getOriginalNodeId(node);
89764                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89765             }
89766             else {
89767                 statements = appendExportsOfHoistedDeclaration(statements, node);
89768             }
89769             return ts.singleOrMany(statements);
89770         }
89771         /**
89772          * Visits a ClassDeclaration node.
89773          *
89774          * @param node The node to visit.
89775          */
89776         function visitClassDeclaration(node) {
89777             var statements;
89778             if (ts.hasModifier(node, 1 /* Export */)) {
89779                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
89780                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89781                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
89782             }
89783             else {
89784                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89785             }
89786             if (hasAssociatedEndOfDeclarationMarker(node)) {
89787                 // Defer exports until we encounter an EndOfDeclarationMarker node
89788                 var id = ts.getOriginalNodeId(node);
89789                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89790             }
89791             else {
89792                 statements = appendExportsOfHoistedDeclaration(statements, node);
89793             }
89794             return ts.singleOrMany(statements);
89795         }
89796         /**
89797          * Visits a VariableStatement node.
89798          *
89799          * @param node The node to visit.
89800          */
89801         function visitVariableStatement(node) {
89802             var statements;
89803             var variables;
89804             var expressions;
89805             if (ts.hasModifier(node, 1 /* Export */)) {
89806                 var modifiers = void 0;
89807                 // If we're exporting these variables, then these just become assignments to 'exports.x'.
89808                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89809                     var variable = _a[_i];
89810                     if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
89811                         if (!modifiers) {
89812                             modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
89813                         }
89814                         variables = ts.append(variables, variable);
89815                     }
89816                     else if (variable.initializer) {
89817                         expressions = ts.append(expressions, transformInitializedVariable(variable));
89818                     }
89819                 }
89820                 if (variables) {
89821                     statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables)));
89822                 }
89823                 if (expressions) {
89824                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node));
89825                 }
89826             }
89827             else {
89828                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89829             }
89830             if (hasAssociatedEndOfDeclarationMarker(node)) {
89831                 // Defer exports until we encounter an EndOfDeclarationMarker node
89832                 var id = ts.getOriginalNodeId(node);
89833                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
89834             }
89835             else {
89836                 statements = appendExportsOfVariableStatement(statements, node);
89837             }
89838             return ts.singleOrMany(statements);
89839         }
89840         function createAllExportExpressions(name, value, location) {
89841             var exportedNames = getExports(name);
89842             if (exportedNames) {
89843                 // For each additional export of the declaration, apply an export assignment.
89844                 var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
89845                 for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
89846                     var exportName = exportedNames_1[_i];
89847                     // Mark the node to prevent triggering substitution.
89848                     ts.setEmitFlags(expression, 4 /* NoSubstitution */);
89849                     expression = createExportExpression(exportName, expression, /*location*/ location);
89850                 }
89851                 return expression;
89852             }
89853             return ts.createAssignment(name, value);
89854         }
89855         /**
89856          * Transforms an exported variable with an initializer into an expression.
89857          *
89858          * @param node The node to transform.
89859          */
89860         function transformInitializedVariable(node) {
89861             if (ts.isBindingPattern(node.name)) {
89862                 return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), 
89863                 /*visitor*/ undefined, context, 0 /* All */, 
89864                 /*needsValue*/ false, createAllExportExpressions);
89865             }
89866             else {
89867                 return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), 
89868                 /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, moduleExpressionElementVisitor) : ts.createVoidZero());
89869             }
89870         }
89871         /**
89872          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
89873          * and transformed declaration.
89874          *
89875          * @param node The node to visit.
89876          */
89877         function visitMergeDeclarationMarker(node) {
89878             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
89879             // declaration we do not emit a leading variable declaration. To preserve the
89880             // begin/end semantics of the declararation and to properly handle exports
89881             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
89882             //
89883             // To balance the declaration, add the exports of the elided variable
89884             // statement.
89885             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
89886                 var id = ts.getOriginalNodeId(node);
89887                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
89888             }
89889             return node;
89890         }
89891         /**
89892          * Determines whether a node has an associated EndOfDeclarationMarker.
89893          *
89894          * @param node The node to test.
89895          */
89896         function hasAssociatedEndOfDeclarationMarker(node) {
89897             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
89898         }
89899         /**
89900          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
89901          * declaration.
89902          *
89903          * @param node The node to visit.
89904          */
89905         function visitEndOfDeclarationMarker(node) {
89906             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
89907             // end of the transformed declaration. We use this marker to emit any deferred exports
89908             // of the declaration.
89909             var id = ts.getOriginalNodeId(node);
89910             var statements = deferredExports[id];
89911             if (statements) {
89912                 delete deferredExports[id];
89913                 return ts.append(statements, node);
89914             }
89915             return node;
89916         }
89917         /**
89918          * Appends the exports of an ImportDeclaration to a statement list, returning the
89919          * statement list.
89920          *
89921          * @param statements A statement list to which the down-level export statements are to be
89922          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89923          * appended.
89924          * @param decl The declaration whose exports are to be recorded.
89925          */
89926         function appendExportsOfImportDeclaration(statements, decl) {
89927             if (currentModuleInfo.exportEquals) {
89928                 return statements;
89929             }
89930             var importClause = decl.importClause;
89931             if (!importClause) {
89932                 return statements;
89933             }
89934             if (importClause.name) {
89935                 statements = appendExportsOfDeclaration(statements, importClause);
89936             }
89937             var namedBindings = importClause.namedBindings;
89938             if (namedBindings) {
89939                 switch (namedBindings.kind) {
89940                     case 256 /* NamespaceImport */:
89941                         statements = appendExportsOfDeclaration(statements, namedBindings);
89942                         break;
89943                     case 257 /* NamedImports */:
89944                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
89945                             var importBinding = _a[_i];
89946                             statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
89947                         }
89948                         break;
89949                 }
89950             }
89951             return statements;
89952         }
89953         /**
89954          * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
89955          * statement list.
89956          *
89957          * @param statements A statement list to which the down-level export statements are to be
89958          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89959          * appended.
89960          * @param decl The declaration whose exports are to be recorded.
89961          */
89962         function appendExportsOfImportEqualsDeclaration(statements, decl) {
89963             if (currentModuleInfo.exportEquals) {
89964                 return statements;
89965             }
89966             return appendExportsOfDeclaration(statements, decl);
89967         }
89968         /**
89969          * Appends the exports of a VariableStatement to a statement list, returning the statement
89970          * list.
89971          *
89972          * @param statements A statement list to which the down-level export statements are to be
89973          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89974          * appended.
89975          * @param node The VariableStatement whose exports are to be recorded.
89976          */
89977         function appendExportsOfVariableStatement(statements, node) {
89978             if (currentModuleInfo.exportEquals) {
89979                 return statements;
89980             }
89981             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89982                 var decl = _a[_i];
89983                 statements = appendExportsOfBindingElement(statements, decl);
89984             }
89985             return statements;
89986         }
89987         /**
89988          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
89989          * returning the statement list.
89990          *
89991          * @param statements A statement list to which the down-level export statements are to be
89992          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89993          * appended.
89994          * @param decl The declaration whose exports are to be recorded.
89995          */
89996         function appendExportsOfBindingElement(statements, decl) {
89997             if (currentModuleInfo.exportEquals) {
89998                 return statements;
89999             }
90000             if (ts.isBindingPattern(decl.name)) {
90001                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
90002                     var element = _a[_i];
90003                     if (!ts.isOmittedExpression(element)) {
90004                         statements = appendExportsOfBindingElement(statements, element);
90005                     }
90006                 }
90007             }
90008             else if (!ts.isGeneratedIdentifier(decl.name)) {
90009                 statements = appendExportsOfDeclaration(statements, decl);
90010             }
90011             return statements;
90012         }
90013         /**
90014          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
90015          * returning the statement list.
90016          *
90017          * @param statements A statement list to which the down-level export statements are to be
90018          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90019          * appended.
90020          * @param decl The declaration whose exports are to be recorded.
90021          */
90022         function appendExportsOfHoistedDeclaration(statements, decl) {
90023             if (currentModuleInfo.exportEquals) {
90024                 return statements;
90025             }
90026             if (ts.hasModifier(decl, 1 /* Export */)) {
90027                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl);
90028                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl);
90029             }
90030             if (decl.name) {
90031                 statements = appendExportsOfDeclaration(statements, decl);
90032             }
90033             return statements;
90034         }
90035         /**
90036          * Appends the exports of a declaration to a statement list, returning the statement list.
90037          *
90038          * @param statements A statement list to which the down-level export statements are to be
90039          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90040          * appended.
90041          * @param decl The declaration to export.
90042          */
90043         function appendExportsOfDeclaration(statements, decl, liveBinding) {
90044             var name = ts.getDeclarationName(decl);
90045             var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
90046             if (exportSpecifiers) {
90047                 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
90048                     var exportSpecifier = exportSpecifiers_1[_i];
90049                     statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
90050                 }
90051             }
90052             return statements;
90053         }
90054         /**
90055          * Appends the down-level representation of an export to a statement list, returning the
90056          * statement list.
90057          *
90058          * @param statements A statement list to which the down-level export statements are to be
90059          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90060          * appended.
90061          * @param exportName The name of the export.
90062          * @param expression The expression to export.
90063          * @param location The location to use for source maps and comments for the export.
90064          * @param allowComments Whether to allow comments on the export.
90065          */
90066         function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
90067             statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
90068             return statements;
90069         }
90070         function createUnderscoreUnderscoreESModule() {
90071             var statement;
90072             if (languageVersion === 0 /* ES3 */) {
90073                 statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true)));
90074             }
90075             else {
90076                 statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90077                 /*typeArguments*/ undefined, [
90078                     ts.createIdentifier("exports"),
90079                     ts.createLiteral("__esModule"),
90080                     ts.createObjectLiteral([
90081                         ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true))
90082                     ])
90083                 ]));
90084             }
90085             ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
90086             return statement;
90087         }
90088         /**
90089          * Creates a call to the current file's export function to export a value.
90090          *
90091          * @param name The bound name of the export.
90092          * @param value The exported value.
90093          * @param location The location to use for source maps and comments for the export.
90094          * @param allowComments An optional value indicating whether to emit comments for the statement.
90095          */
90096         function createExportStatement(name, value, location, allowComments, liveBinding) {
90097             var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
90098             ts.startOnNewLine(statement);
90099             if (!allowComments) {
90100                 ts.setEmitFlags(statement, 1536 /* NoComments */);
90101             }
90102             return statement;
90103         }
90104         /**
90105          * Creates a call to the current file's export function to export a value.
90106          *
90107          * @param name The bound name of the export.
90108          * @param value The exported value.
90109          * @param location The location to use for source maps and comments for the export.
90110          */
90111         function createExportExpression(name, value, location, liveBinding) {
90112             return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90113             /*typeArguments*/ undefined, [
90114                 ts.createIdentifier("exports"),
90115                 ts.createLiteral(name),
90116                 ts.createObjectLiteral([
90117                     ts.createPropertyAssignment("enumerable", ts.createLiteral(/*value*/ true)),
90118                     ts.createPropertyAssignment("get", ts.createFunctionExpression(
90119                     /*modifiers*/ undefined, 
90120                     /*asteriskToken*/ undefined, 
90121                     /*name*/ undefined, 
90122                     /*typeParameters*/ undefined, 
90123                     /*parameters*/ [], 
90124                     /*type*/ undefined, ts.createBlock([ts.createReturn(value)])))
90125                 ])
90126             ]) : ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location);
90127         }
90128         //
90129         // Modifier Visitors
90130         //
90131         /**
90132          * Visit nodes to elide module-specific modifiers.
90133          *
90134          * @param node The node to visit.
90135          */
90136         function modifierVisitor(node) {
90137             // Elide module-specific modifiers.
90138             switch (node.kind) {
90139                 case 89 /* ExportKeyword */:
90140                 case 84 /* DefaultKeyword */:
90141                     return undefined;
90142             }
90143             return node;
90144         }
90145         //
90146         // Emit Notification
90147         //
90148         /**
90149          * Hook for node emit notifications.
90150          *
90151          * @param hint A hint as to the intended usage of the node.
90152          * @param node The node to emit.
90153          * @param emit A callback used to emit the node in the printer.
90154          */
90155         function onEmitNode(hint, node, emitCallback) {
90156             if (node.kind === 290 /* SourceFile */) {
90157                 currentSourceFile = node;
90158                 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
90159                 noSubstitution = [];
90160                 previousOnEmitNode(hint, node, emitCallback);
90161                 currentSourceFile = undefined;
90162                 currentModuleInfo = undefined;
90163                 noSubstitution = undefined;
90164             }
90165             else {
90166                 previousOnEmitNode(hint, node, emitCallback);
90167             }
90168         }
90169         //
90170         // Substitutions
90171         //
90172         /**
90173          * Hooks node substitutions.
90174          *
90175          * @param hint A hint as to the intended usage of the node.
90176          * @param node The node to substitute.
90177          */
90178         function onSubstituteNode(hint, node) {
90179             node = previousOnSubstituteNode(hint, node);
90180             if (node.id && noSubstitution[node.id]) {
90181                 return node;
90182             }
90183             if (hint === 1 /* Expression */) {
90184                 return substituteExpression(node);
90185             }
90186             else if (ts.isShorthandPropertyAssignment(node)) {
90187                 return substituteShorthandPropertyAssignment(node);
90188             }
90189             return node;
90190         }
90191         /**
90192          * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
90193          * or exported symbol.
90194          *
90195          * @param node The node to substitute.
90196          */
90197         function substituteShorthandPropertyAssignment(node) {
90198             var name = node.name;
90199             var exportedOrImportedName = substituteExpressionIdentifier(name);
90200             if (exportedOrImportedName !== name) {
90201                 // A shorthand property with an assignment initializer is probably part of a
90202                 // destructuring assignment
90203                 if (node.objectAssignmentInitializer) {
90204                     var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
90205                     return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
90206                 }
90207                 return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node);
90208             }
90209             return node;
90210         }
90211         /**
90212          * Substitution for an Expression that may contain an imported or exported symbol.
90213          *
90214          * @param node The node to substitute.
90215          */
90216         function substituteExpression(node) {
90217             switch (node.kind) {
90218                 case 75 /* Identifier */:
90219                     return substituteExpressionIdentifier(node);
90220                 case 209 /* BinaryExpression */:
90221                     return substituteBinaryExpression(node);
90222                 case 208 /* PostfixUnaryExpression */:
90223                 case 207 /* PrefixUnaryExpression */:
90224                     return substituteUnaryExpression(node);
90225             }
90226             return node;
90227         }
90228         /**
90229          * Substitution for an Identifier expression that may contain an imported or exported
90230          * symbol.
90231          *
90232          * @param node The node to substitute.
90233          */
90234         function substituteExpressionIdentifier(node) {
90235             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
90236                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
90237                 if (externalHelpersModuleName) {
90238                     return ts.createPropertyAccess(externalHelpersModuleName, node);
90239                 }
90240                 return node;
90241             }
90242             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
90243                 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
90244                 if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
90245                     return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), 
90246                     /*location*/ node);
90247                 }
90248                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
90249                 if (importDeclaration) {
90250                     if (ts.isImportClause(importDeclaration)) {
90251                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
90252                         /*location*/ node);
90253                     }
90254                     else if (ts.isImportSpecifier(importDeclaration)) {
90255                         var name = importDeclaration.propertyName || importDeclaration.name;
90256                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), 
90257                         /*location*/ node);
90258                     }
90259                 }
90260             }
90261             return node;
90262         }
90263         /**
90264          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
90265          *
90266          * @param node The node to substitute.
90267          */
90268         function substituteBinaryExpression(node) {
90269             // When we see an assignment expression whose left-hand side is an exported symbol,
90270             // we should ensure all exports of that symbol are updated with the correct value.
90271             //
90272             // - We do not substitute generated identifiers for any reason.
90273             // - We do not substitute identifiers tagged with the LocalName flag.
90274             // - We do not substitute identifiers that were originally the name of an enum or
90275             //   namespace due to how they are transformed in TypeScript.
90276             // - We only substitute identifiers that are exported at the top level.
90277             if (ts.isAssignmentOperator(node.operatorToken.kind)
90278                 && ts.isIdentifier(node.left)
90279                 && !ts.isGeneratedIdentifier(node.left)
90280                 && !ts.isLocalName(node.left)
90281                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
90282                 var exportedNames = getExports(node.left);
90283                 if (exportedNames) {
90284                     // For each additional export of the declaration, apply an export assignment.
90285                     var expression = node;
90286                     for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
90287                         var exportName = exportedNames_2[_i];
90288                         // Mark the node to prevent triggering this rule again.
90289                         noSubstitution[ts.getNodeId(expression)] = true;
90290                         expression = createExportExpression(exportName, expression, /*location*/ node);
90291                     }
90292                     return expression;
90293                 }
90294             }
90295             return node;
90296         }
90297         /**
90298          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
90299          *
90300          * @param node The node to substitute.
90301          */
90302         function substituteUnaryExpression(node) {
90303             // When we see a prefix or postfix increment expression whose operand is an exported
90304             // symbol, we should ensure all exports of that symbol are updated with the correct
90305             // value.
90306             //
90307             // - We do not substitute generated identifiers for any reason.
90308             // - We do not substitute identifiers tagged with the LocalName flag.
90309             // - We do not substitute identifiers that were originally the name of an enum or
90310             //   namespace due to how they are transformed in TypeScript.
90311             // - We only substitute identifiers that are exported at the top level.
90312             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
90313                 && ts.isIdentifier(node.operand)
90314                 && !ts.isGeneratedIdentifier(node.operand)
90315                 && !ts.isLocalName(node.operand)
90316                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
90317                 var exportedNames = getExports(node.operand);
90318                 if (exportedNames) {
90319                     var expression = node.kind === 208 /* PostfixUnaryExpression */
90320                         ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), ts.createLiteral(1)), 
90321                         /*location*/ node)
90322                         : node;
90323                     for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
90324                         var exportName = exportedNames_3[_i];
90325                         // Mark the node to prevent triggering this rule again.
90326                         noSubstitution[ts.getNodeId(expression)] = true;
90327                         expression = createExportExpression(exportName, expression);
90328                     }
90329                     return expression;
90330                 }
90331             }
90332             return node;
90333         }
90334         /**
90335          * Gets the additional exports of a name.
90336          *
90337          * @param name The name.
90338          */
90339         function getExports(name) {
90340             if (!ts.isGeneratedIdentifier(name)) {
90341                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
90342                     || resolver.getReferencedValueDeclaration(name);
90343                 if (valueDeclaration) {
90344                     return currentModuleInfo
90345                         && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
90346                 }
90347             }
90348         }
90349     }
90350     ts.transformModule = transformModule;
90351     ts.createBindingHelper = {
90352         name: "typescript:commonjscreatebinding",
90353         importName: "__createBinding",
90354         scoped: false,
90355         priority: 1,
90356         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}));"
90357     };
90358     function createCreateBindingHelper(context, module, inputName, outputName) {
90359         context.requestEmitHelper(ts.createBindingHelper);
90360         return ts.createCall(ts.getUnscopedHelperName("__createBinding"), /*typeArguments*/ undefined, __spreadArrays([ts.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
90361     }
90362     ts.setModuleDefaultHelper = {
90363         name: "typescript:commonjscreatevalue",
90364         importName: "__setModuleDefault",
90365         scoped: false,
90366         priority: 1,
90367         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});"
90368     };
90369     // emit output for the __export helper function
90370     var exportStarHelper = {
90371         name: "typescript:export-star",
90372         importName: "__exportStar",
90373         scoped: false,
90374         dependencies: [ts.createBindingHelper],
90375         priority: 2,
90376         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            };"
90377     };
90378     function createExportStarHelper(context, module) {
90379         context.requestEmitHelper(exportStarHelper);
90380         return ts.createCall(ts.getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]);
90381     }
90382     // emit helper for dynamic import
90383     var dynamicImportUMDHelper = {
90384         name: "typescript:dynamicimport-sync-require",
90385         scoped: true,
90386         text: "\n            var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
90387     };
90388     // emit helper for `import * as Name from "foo"`
90389     ts.importStarHelper = {
90390         name: "typescript:commonjsimportstar",
90391         importName: "__importStar",
90392         scoped: false,
90393         dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
90394         priority: 2,
90395         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};"
90396     };
90397     // emit helper for `import Name from "foo"`
90398     ts.importDefaultHelper = {
90399         name: "typescript:commonjsimportdefault",
90400         importName: "__importDefault",
90401         scoped: false,
90402         text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
90403     };
90404 })(ts || (ts = {}));
90405 /*@internal*/
90406 var ts;
90407 (function (ts) {
90408     function transformSystemModule(context) {
90409         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
90410         var compilerOptions = context.getCompilerOptions();
90411         var resolver = context.getEmitResolver();
90412         var host = context.getEmitHost();
90413         var previousOnSubstituteNode = context.onSubstituteNode;
90414         var previousOnEmitNode = context.onEmitNode;
90415         context.onSubstituteNode = onSubstituteNode;
90416         context.onEmitNode = onEmitNode;
90417         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers for imported symbols.
90418         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
90419         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
90420         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
90421         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
90422         context.enableSubstitution(219 /* MetaProperty */); // Substitutes 'import.meta'
90423         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
90424         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
90425         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
90426         var exportFunctionsMap = []; // The export function associated with a source file.
90427         var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
90428         var contextObjectMap = []; // The context object associated with a source file.
90429         var currentSourceFile; // The current file.
90430         var moduleInfo; // ExternalModuleInfo for the current file.
90431         var exportFunction; // The export function for the current file.
90432         var contextObject; // The context object for the current file.
90433         var hoistedStatements;
90434         var enclosingBlockScopedContainer;
90435         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
90436         return ts.chainBundle(transformSourceFile);
90437         /**
90438          * Transforms the module aspects of a SourceFile.
90439          *
90440          * @param node The SourceFile node.
90441          */
90442         function transformSourceFile(node) {
90443             if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
90444                 return node;
90445             }
90446             var id = ts.getOriginalNodeId(node);
90447             currentSourceFile = node;
90448             enclosingBlockScopedContainer = node;
90449             // System modules have the following shape:
90450             //
90451             //     System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
90452             //
90453             // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
90454             // is used to publish exported values. 'exports' returns its 'value' argument so in
90455             // most cases expressions that mutate exported values can be rewritten as:
90456             //
90457             //     expr -> exports('name', expr)
90458             //
90459             // The only exception in this rule is postfix unary operators,
90460             // see comment to 'substitutePostfixUnaryExpression' for more details
90461             // Collect information about the external module and dependency groups.
90462             moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
90463             // Make sure that the name of the 'exports' function does not conflict with
90464             // existing identifiers.
90465             exportFunction = ts.createUniqueName("exports");
90466             exportFunctionsMap[id] = exportFunction;
90467             contextObject = contextObjectMap[id] = ts.createUniqueName("context");
90468             // Add the body of the module.
90469             var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
90470             var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
90471             var moduleBodyFunction = ts.createFunctionExpression(
90472             /*modifiers*/ undefined, 
90473             /*asteriskToken*/ undefined, 
90474             /*name*/ undefined, 
90475             /*typeParameters*/ undefined, [
90476                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
90477                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
90478             ], 
90479             /*type*/ undefined, moduleBodyBlock);
90480             // Write the call to `System.register`
90481             // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
90482             // So the helper will be emit at the correct position instead of at the top of the source-file
90483             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
90484             var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
90485             var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
90486                 ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), 
90487                 /*typeArguments*/ undefined, moduleName
90488                     ? [moduleName, dependencies, moduleBodyFunction]
90489                     : [dependencies, moduleBodyFunction]))
90490             ]), node.statements)), 1024 /* NoTrailingComments */);
90491             if (!(compilerOptions.outFile || compilerOptions.out)) {
90492                 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
90493             }
90494             if (noSubstitution) {
90495                 noSubstitutionMap[id] = noSubstitution;
90496                 noSubstitution = undefined;
90497             }
90498             currentSourceFile = undefined;
90499             moduleInfo = undefined;
90500             exportFunction = undefined;
90501             contextObject = undefined;
90502             hoistedStatements = undefined;
90503             enclosingBlockScopedContainer = undefined;
90504             return ts.aggregateTransformFlags(updated);
90505         }
90506         /**
90507          * Collects the dependency groups for this files imports.
90508          *
90509          * @param externalImports The imports for the file.
90510          */
90511         function collectDependencyGroups(externalImports) {
90512             var groupIndices = ts.createMap();
90513             var dependencyGroups = [];
90514             for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
90515                 var externalImport = externalImports_1[_i];
90516                 var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
90517                 if (externalModuleName) {
90518                     var text = externalModuleName.text;
90519                     var groupIndex = groupIndices.get(text);
90520                     if (groupIndex !== undefined) {
90521                         // deduplicate/group entries in dependency list by the dependency name
90522                         dependencyGroups[groupIndex].externalImports.push(externalImport);
90523                     }
90524                     else {
90525                         groupIndices.set(text, dependencyGroups.length);
90526                         dependencyGroups.push({
90527                             name: externalModuleName,
90528                             externalImports: [externalImport]
90529                         });
90530                     }
90531                 }
90532             }
90533             return dependencyGroups;
90534         }
90535         /**
90536          * Adds the statements for the module body function for the source file.
90537          *
90538          * @param node The source file for the module.
90539          * @param dependencyGroups The grouped dependencies of the module.
90540          */
90541         function createSystemModuleBody(node, dependencyGroups) {
90542             // Shape of the body in system modules:
90543             //
90544             //  function (exports) {
90545             //      <list of local aliases for imports>
90546             //      <hoisted variable declarations>
90547             //      <hoisted function declarations>
90548             //      return {
90549             //          setters: [
90550             //              <list of setter function for imports>
90551             //          ],
90552             //          execute: function() {
90553             //              <module statements>
90554             //          }
90555             //      }
90556             //      <temp declarations>
90557             //  }
90558             //
90559             // i.e:
90560             //
90561             //   import {x} from 'file1'
90562             //   var y = 1;
90563             //   export function foo() { return y + x(); }
90564             //   console.log(y);
90565             //
90566             // Will be transformed to:
90567             //
90568             //  function(exports) {
90569             //      function foo() { return y + file_1.x(); }
90570             //      exports("foo", foo);
90571             //      var file_1, y;
90572             //      return {
90573             //          setters: [
90574             //              function(v) { file_1 = v }
90575             //          ],
90576             //          execute(): function() {
90577             //              y = 1;
90578             //              console.log(y);
90579             //          }
90580             //      };
90581             //  }
90582             var statements = [];
90583             // We start a new lexical environment in this function body, but *not* in the
90584             // body of the execute function. This allows us to emit temporary declarations
90585             // only in the outer module body and not in the inner one.
90586             startLexicalEnvironment();
90587             // Add any prologue directives.
90588             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
90589             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
90590             // var __moduleName = context_1 && context_1.id;
90591             statements.push(ts.createVariableStatement(
90592             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90593                 ts.createVariableDeclaration("__moduleName", 
90594                 /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id")))
90595             ])));
90596             // Visit the synthetic external helpers import declaration if present
90597             ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
90598             // Visit the statements of the source file, emitting any transformations into
90599             // the `executeStatements` array. We do this *before* we fill the `setters` array
90600             // as we both emit transformations as well as aggregate some data used when creating
90601             // setters. This allows us to reduce the number of times we need to loop through the
90602             // statements of the source file.
90603             var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
90604             // Emit early exports for function declarations.
90605             ts.addRange(statements, hoistedStatements);
90606             // We emit hoisted variables early to align roughly with our previous emit output.
90607             // Two key differences in this approach are:
90608             // - Temporary variables will appear at the top rather than at the bottom of the file
90609             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
90610             var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
90611             var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ?
90612                 ts.createModifiersFromModifierFlags(256 /* Async */) :
90613                 undefined;
90614             var moduleObject = ts.createObjectLiteral([
90615                 ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
90616                 ts.createPropertyAssignment("execute", ts.createFunctionExpression(modifiers, 
90617                 /*asteriskToken*/ undefined, 
90618                 /*name*/ undefined, 
90619                 /*typeParameters*/ undefined, 
90620                 /*parameters*/ [], 
90621                 /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true)))
90622             ]);
90623             moduleObject.multiLine = true;
90624             statements.push(ts.createReturn(moduleObject));
90625             return ts.createBlock(statements, /*multiLine*/ true);
90626         }
90627         /**
90628          * Adds an exportStar function to a statement list if it is needed for the file.
90629          *
90630          * @param statements A statement list.
90631          */
90632         function addExportStarIfNeeded(statements) {
90633             if (!moduleInfo.hasExportStarsToExportValues) {
90634                 return;
90635             }
90636             // when resolving exports local exported entries/indirect exported entries in the module
90637             // should always win over entries with similar names that were added via star exports
90638             // to support this we store names of local/indirect exported entries in a set.
90639             // this set is used to filter names brought by star expors.
90640             // local names set should only be added if we have anything exported
90641             if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
90642                 // no exported declarations (export var ...) or export specifiers (export {x})
90643                 // check if we have any non star export declarations.
90644                 var hasExportDeclarationWithExportClause = false;
90645                 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
90646                     var externalImport = _a[_i];
90647                     if (externalImport.kind === 260 /* ExportDeclaration */ && externalImport.exportClause) {
90648                         hasExportDeclarationWithExportClause = true;
90649                         break;
90650                     }
90651                 }
90652                 if (!hasExportDeclarationWithExportClause) {
90653                     // we still need to emit exportStar helper
90654                     var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
90655                     statements.push(exportStarFunction_1);
90656                     return exportStarFunction_1.name;
90657                 }
90658             }
90659             var exportedNames = [];
90660             if (moduleInfo.exportedNames) {
90661                 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
90662                     var exportedLocalName = _c[_b];
90663                     if (exportedLocalName.escapedText === "default") {
90664                         continue;
90665                     }
90666                     // write name of exported declaration, i.e 'export var x...'
90667                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue()));
90668                 }
90669             }
90670             for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) {
90671                 var externalImport = _e[_d];
90672                 if (externalImport.kind !== 260 /* ExportDeclaration */) {
90673                     continue;
90674                 }
90675                 if (!externalImport.exportClause) {
90676                     // export * from ...
90677                     continue;
90678                 }
90679                 if (ts.isNamedExports(externalImport.exportClause)) {
90680                     for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) {
90681                         var element = _g[_f];
90682                         // write name of indirectly exported entry, i.e. 'export {x} from ...'
90683                         exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue()));
90684                     }
90685                 }
90686                 else {
90687                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(externalImport.exportClause.name)), ts.createTrue()));
90688                 }
90689             }
90690             var exportedNamesStorageRef = ts.createUniqueName("exportedNames");
90691             statements.push(ts.createVariableStatement(
90692             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90693                 ts.createVariableDeclaration(exportedNamesStorageRef, 
90694                 /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true))
90695             ])));
90696             var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
90697             statements.push(exportStarFunction);
90698             return exportStarFunction.name;
90699         }
90700         /**
90701          * Creates an exportStar function for the file, with an optional set of excluded local
90702          * names.
90703          *
90704          * @param localNames An optional reference to an object containing a set of excluded local
90705          * names.
90706          */
90707         function createExportStarFunction(localNames) {
90708             var exportStarFunction = ts.createUniqueName("exportStar");
90709             var m = ts.createIdentifier("m");
90710             var n = ts.createIdentifier("n");
90711             var exports = ts.createIdentifier("exports");
90712             var condition = ts.createStrictInequality(n, ts.createLiteral("default"));
90713             if (localNames) {
90714                 condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), 
90715                 /*typeArguments*/ undefined, [n])));
90716             }
90717             return ts.createFunctionDeclaration(
90718             /*decorators*/ undefined, 
90719             /*modifiers*/ undefined, 
90720             /*asteriskToken*/ undefined, exportStarFunction, 
90721             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], 
90722             /*type*/ undefined, ts.createBlock([
90723                 ts.createVariableStatement(
90724                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
90725                     ts.createVariableDeclaration(exports, 
90726                     /*type*/ undefined, ts.createObjectLiteral([]))
90727                 ])),
90728                 ts.createForIn(ts.createVariableDeclarationList([
90729                     ts.createVariableDeclaration(n, /*type*/ undefined)
90730                 ]), m, ts.createBlock([
90731                     ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */)
90732                 ])),
90733                 ts.createExpressionStatement(ts.createCall(exportFunction, 
90734                 /*typeArguments*/ undefined, [exports]))
90735             ], /*multiline*/ true));
90736         }
90737         /**
90738          * Creates an array setter callbacks for each dependency group.
90739          *
90740          * @param exportStarFunction A reference to an exportStarFunction for the file.
90741          * @param dependencyGroups An array of grouped dependencies.
90742          */
90743         function createSettersArray(exportStarFunction, dependencyGroups) {
90744             var setters = [];
90745             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
90746                 var group_2 = dependencyGroups_1[_i];
90747                 // derive a unique name for parameter from the first named entry in the group
90748                 var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
90749                 var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
90750                 var statements = [];
90751                 for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
90752                     var entry = _b[_a];
90753                     var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217
90754                     switch (entry.kind) {
90755                         case 254 /* ImportDeclaration */:
90756                             if (!entry.importClause) {
90757                                 // 'import "..."' case
90758                                 // module is imported only for side-effects, no emit required
90759                                 break;
90760                             }
90761                         // falls through
90762                         case 253 /* ImportEqualsDeclaration */:
90763                             ts.Debug.assert(importVariableName !== undefined);
90764                             // save import into the local
90765                             statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName)));
90766                             break;
90767                         case 260 /* ExportDeclaration */:
90768                             ts.Debug.assert(importVariableName !== undefined);
90769                             if (entry.exportClause) {
90770                                 if (ts.isNamedExports(entry.exportClause)) {
90771                                     //  export {a, b as c} from 'foo'
90772                                     //
90773                                     // emit as:
90774                                     //
90775                                     //  exports_({
90776                                     //     "a": _["a"],
90777                                     //     "c": _["b"]
90778                                     //  });
90779                                     var properties = [];
90780                                     for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
90781                                         var e = _d[_c];
90782                                         properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name)))));
90783                                     }
90784                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90785                                     /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)])));
90786                                 }
90787                                 else {
90788                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90789                                     /*typeArguments*/ undefined, [
90790                                         ts.createLiteral(ts.idText(entry.exportClause.name)),
90791                                         parameterName
90792                                     ])));
90793                                 }
90794                             }
90795                             else {
90796                                 //  export * from 'foo'
90797                                 //
90798                                 // emit as:
90799                                 //
90800                                 //  exportStar(foo_1_1);
90801                                 statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, 
90802                                 /*typeArguments*/ undefined, [parameterName])));
90803                             }
90804                             break;
90805                     }
90806                 }
90807                 setters.push(ts.createFunctionExpression(
90808                 /*modifiers*/ undefined, 
90809                 /*asteriskToken*/ undefined, 
90810                 /*name*/ undefined, 
90811                 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
90812                 /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true)));
90813             }
90814             return ts.createArrayLiteral(setters, /*multiLine*/ true);
90815         }
90816         //
90817         // Top-level Source Element Visitors
90818         //
90819         /**
90820          * Visit source elements at the top-level of a module.
90821          *
90822          * @param node The node to visit.
90823          */
90824         function sourceElementVisitor(node) {
90825             switch (node.kind) {
90826                 case 254 /* ImportDeclaration */:
90827                     return visitImportDeclaration(node);
90828                 case 253 /* ImportEqualsDeclaration */:
90829                     return visitImportEqualsDeclaration(node);
90830                 case 260 /* ExportDeclaration */:
90831                     return visitExportDeclaration(node);
90832                 case 259 /* ExportAssignment */:
90833                     return visitExportAssignment(node);
90834                 default:
90835                     return nestedElementVisitor(node);
90836             }
90837         }
90838         /**
90839          * Visits an ImportDeclaration node.
90840          *
90841          * @param node The node to visit.
90842          */
90843         function visitImportDeclaration(node) {
90844             var statements;
90845             if (node.importClause) {
90846                 hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
90847             }
90848             if (hasAssociatedEndOfDeclarationMarker(node)) {
90849                 // Defer exports until we encounter an EndOfDeclarationMarker node
90850                 var id = ts.getOriginalNodeId(node);
90851                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
90852             }
90853             else {
90854                 statements = appendExportsOfImportDeclaration(statements, node);
90855             }
90856             return ts.singleOrMany(statements);
90857         }
90858         function visitExportDeclaration(node) {
90859             ts.Debug.assertIsDefined(node);
90860             return undefined;
90861         }
90862         /**
90863          * Visits an ImportEqualsDeclaration node.
90864          *
90865          * @param node The node to visit.
90866          */
90867         function visitImportEqualsDeclaration(node) {
90868             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
90869             var statements;
90870             hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
90871             if (hasAssociatedEndOfDeclarationMarker(node)) {
90872                 // Defer exports until we encounter an EndOfDeclarationMarker node
90873                 var id = ts.getOriginalNodeId(node);
90874                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
90875             }
90876             else {
90877                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
90878             }
90879             return ts.singleOrMany(statements);
90880         }
90881         /**
90882          * Visits an ExportAssignment node.
90883          *
90884          * @param node The node to visit.
90885          */
90886         function visitExportAssignment(node) {
90887             if (node.isExportEquals) {
90888                 // Elide `export=` as it is illegal in a SystemJS module.
90889                 return undefined;
90890             }
90891             var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
90892             var original = node.original;
90893             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
90894                 // Defer exports until we encounter an EndOfDeclarationMarker node
90895                 var id = ts.getOriginalNodeId(node);
90896                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true);
90897             }
90898             else {
90899                 return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true);
90900             }
90901         }
90902         /**
90903          * Visits a FunctionDeclaration, hoisting it to the outer module body function.
90904          *
90905          * @param node The node to visit.
90906          */
90907         function visitFunctionDeclaration(node) {
90908             if (ts.hasModifier(node, 1 /* Export */)) {
90909                 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), 
90910                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), 
90911                 /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
90912             }
90913             else {
90914                 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
90915             }
90916             if (hasAssociatedEndOfDeclarationMarker(node)) {
90917                 // Defer exports until we encounter an EndOfDeclarationMarker node
90918                 var id = ts.getOriginalNodeId(node);
90919                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
90920             }
90921             else {
90922                 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
90923             }
90924             return undefined;
90925         }
90926         /**
90927          * Visits a ClassDeclaration, hoisting its name to the outer module body function.
90928          *
90929          * @param node The node to visit.
90930          */
90931         function visitClassDeclaration(node) {
90932             var statements;
90933             // Hoist the name of the class declaration to the outer module body function.
90934             var name = ts.getLocalName(node);
90935             hoistVariableDeclaration(name);
90936             // Rewrite the class declaration into an assignment of a class expression.
90937             statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(
90938             /*modifiers*/ undefined, node.name, 
90939             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
90940             if (hasAssociatedEndOfDeclarationMarker(node)) {
90941                 // Defer exports until we encounter an EndOfDeclarationMarker node
90942                 var id = ts.getOriginalNodeId(node);
90943                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
90944             }
90945             else {
90946                 statements = appendExportsOfHoistedDeclaration(statements, node);
90947             }
90948             return ts.singleOrMany(statements);
90949         }
90950         /**
90951          * Visits a variable statement, hoisting declared names to the top-level module body.
90952          * Each declaration is rewritten into an assignment expression.
90953          *
90954          * @param node The node to visit.
90955          */
90956         function visitVariableStatement(node) {
90957             if (!shouldHoistVariableDeclarationList(node.declarationList)) {
90958                 return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
90959             }
90960             var expressions;
90961             var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */);
90962             var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
90963             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
90964                 var variable = _a[_i];
90965                 if (variable.initializer) {
90966                     expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
90967                 }
90968                 else {
90969                     hoistBindingElement(variable);
90970                 }
90971             }
90972             var statements;
90973             if (expressions) {
90974                 statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node));
90975             }
90976             if (isMarkedDeclaration) {
90977                 // Defer exports until we encounter an EndOfDeclarationMarker node
90978                 var id = ts.getOriginalNodeId(node);
90979                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
90980             }
90981             else {
90982                 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
90983             }
90984             return ts.singleOrMany(statements);
90985         }
90986         /**
90987          * Hoists the declared names of a VariableDeclaration or BindingElement.
90988          *
90989          * @param node The declaration to hoist.
90990          */
90991         function hoistBindingElement(node) {
90992             if (ts.isBindingPattern(node.name)) {
90993                 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
90994                     var element = _a[_i];
90995                     if (!ts.isOmittedExpression(element)) {
90996                         hoistBindingElement(element);
90997                     }
90998                 }
90999             }
91000             else {
91001                 hoistVariableDeclaration(ts.getSynthesizedClone(node.name));
91002             }
91003         }
91004         /**
91005          * Determines whether a VariableDeclarationList should be hoisted.
91006          *
91007          * @param node The node to test.
91008          */
91009         function shouldHoistVariableDeclarationList(node) {
91010             // hoist only non-block scoped declarations or block scoped declarations parented by source file
91011             return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
91012                 && (enclosingBlockScopedContainer.kind === 290 /* SourceFile */
91013                     || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
91014         }
91015         /**
91016          * Transform an initialized variable declaration into an expression.
91017          *
91018          * @param node The node to transform.
91019          * @param isExportedDeclaration A value indicating whether the variable is exported.
91020          */
91021         function transformInitializedVariable(node, isExportedDeclaration) {
91022             var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
91023             return ts.isBindingPattern(node.name)
91024                 ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91025                 /*needsValue*/ false, createAssignment)
91026                 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
91027         }
91028         /**
91029          * Creates an assignment expression for an exported variable declaration.
91030          *
91031          * @param name The name of the variable.
91032          * @param value The value of the variable's initializer.
91033          * @param location The source map location for the assignment.
91034          */
91035         function createExportedVariableAssignment(name, value, location) {
91036             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
91037         }
91038         /**
91039          * Creates an assignment expression for a non-exported variable declaration.
91040          *
91041          * @param name The name of the variable.
91042          * @param value The value of the variable's initializer.
91043          * @param location The source map location for the assignment.
91044          */
91045         function createNonExportedVariableAssignment(name, value, location) {
91046             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
91047         }
91048         /**
91049          * Creates an assignment expression for a variable declaration.
91050          *
91051          * @param name The name of the variable.
91052          * @param value The value of the variable's initializer.
91053          * @param location The source map location for the assignment.
91054          * @param isExportedDeclaration A value indicating whether the variable is exported.
91055          */
91056         function createVariableAssignment(name, value, location, isExportedDeclaration) {
91057             hoistVariableDeclaration(ts.getSynthesizedClone(name));
91058             return isExportedDeclaration
91059                 ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)))
91060                 : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location));
91061         }
91062         /**
91063          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
91064          * and transformed declaration.
91065          *
91066          * @param node The node to visit.
91067          */
91068         function visitMergeDeclarationMarker(node) {
91069             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
91070             // declaration we do not emit a leading variable declaration. To preserve the
91071             // begin/end semantics of the declararation and to properly handle exports
91072             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
91073             //
91074             // To balance the declaration, we defer the exports of the elided variable
91075             // statement until we visit this declaration's `EndOfDeclarationMarker`.
91076             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
91077                 var id = ts.getOriginalNodeId(node);
91078                 var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */);
91079                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
91080             }
91081             return node;
91082         }
91083         /**
91084          * Determines whether a node has an associated EndOfDeclarationMarker.
91085          *
91086          * @param node The node to test.
91087          */
91088         function hasAssociatedEndOfDeclarationMarker(node) {
91089             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
91090         }
91091         /**
91092          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
91093          * declaration.
91094          *
91095          * @param node The node to visit.
91096          */
91097         function visitEndOfDeclarationMarker(node) {
91098             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
91099             // end of the transformed declaration. We use this marker to emit any deferred exports
91100             // of the declaration.
91101             var id = ts.getOriginalNodeId(node);
91102             var statements = deferredExports[id];
91103             if (statements) {
91104                 delete deferredExports[id];
91105                 return ts.append(statements, node);
91106             }
91107             else {
91108                 var original = ts.getOriginalNode(node);
91109                 if (ts.isModuleOrEnumDeclaration(original)) {
91110                     return ts.append(appendExportsOfDeclaration(statements, original), node);
91111                 }
91112             }
91113             return node;
91114         }
91115         /**
91116          * Appends the exports of an ImportDeclaration to a statement list, returning the
91117          * statement list.
91118          *
91119          * @param statements A statement list to which the down-level export statements are to be
91120          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91121          * appended.
91122          * @param decl The declaration whose exports are to be recorded.
91123          */
91124         function appendExportsOfImportDeclaration(statements, decl) {
91125             if (moduleInfo.exportEquals) {
91126                 return statements;
91127             }
91128             var importClause = decl.importClause;
91129             if (!importClause) {
91130                 return statements;
91131             }
91132             if (importClause.name) {
91133                 statements = appendExportsOfDeclaration(statements, importClause);
91134             }
91135             var namedBindings = importClause.namedBindings;
91136             if (namedBindings) {
91137                 switch (namedBindings.kind) {
91138                     case 256 /* NamespaceImport */:
91139                         statements = appendExportsOfDeclaration(statements, namedBindings);
91140                         break;
91141                     case 257 /* NamedImports */:
91142                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
91143                             var importBinding = _a[_i];
91144                             statements = appendExportsOfDeclaration(statements, importBinding);
91145                         }
91146                         break;
91147                 }
91148             }
91149             return statements;
91150         }
91151         /**
91152          * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
91153          * statement list.
91154          *
91155          * @param statements A statement list to which the down-level export statements are to be
91156          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91157          * appended.
91158          * @param decl The declaration whose exports are to be recorded.
91159          */
91160         function appendExportsOfImportEqualsDeclaration(statements, decl) {
91161             if (moduleInfo.exportEquals) {
91162                 return statements;
91163             }
91164             return appendExportsOfDeclaration(statements, decl);
91165         }
91166         /**
91167          * Appends the exports of a VariableStatement to a statement list, returning the statement
91168          * 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 node The VariableStatement whose exports are to be recorded.
91174          * @param exportSelf A value indicating whether to also export each VariableDeclaration of
91175          * `nodes` declaration list.
91176          */
91177         function appendExportsOfVariableStatement(statements, node, exportSelf) {
91178             if (moduleInfo.exportEquals) {
91179                 return statements;
91180             }
91181             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
91182                 var decl = _a[_i];
91183                 if (decl.initializer || exportSelf) {
91184                     statements = appendExportsOfBindingElement(statements, decl, exportSelf);
91185                 }
91186             }
91187             return statements;
91188         }
91189         /**
91190          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
91191          * returning the statement list.
91192          *
91193          * @param statements A statement list to which the down-level export statements are to be
91194          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91195          * appended.
91196          * @param decl The declaration whose exports are to be recorded.
91197          * @param exportSelf A value indicating whether to also export the declaration itself.
91198          */
91199         function appendExportsOfBindingElement(statements, decl, exportSelf) {
91200             if (moduleInfo.exportEquals) {
91201                 return statements;
91202             }
91203             if (ts.isBindingPattern(decl.name)) {
91204                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
91205                     var element = _a[_i];
91206                     if (!ts.isOmittedExpression(element)) {
91207                         statements = appendExportsOfBindingElement(statements, element, exportSelf);
91208                     }
91209                 }
91210             }
91211             else if (!ts.isGeneratedIdentifier(decl.name)) {
91212                 var excludeName = void 0;
91213                 if (exportSelf) {
91214                     statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl));
91215                     excludeName = ts.idText(decl.name);
91216                 }
91217                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91218             }
91219             return statements;
91220         }
91221         /**
91222          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
91223          * 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 whose exports are to be recorded.
91229          */
91230         function appendExportsOfHoistedDeclaration(statements, decl) {
91231             if (moduleInfo.exportEquals) {
91232                 return statements;
91233             }
91234             var excludeName;
91235             if (ts.hasModifier(decl, 1 /* Export */)) {
91236                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name;
91237                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl));
91238                 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
91239             }
91240             if (decl.name) {
91241                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91242             }
91243             return statements;
91244         }
91245         /**
91246          * Appends the exports of a declaration to a statement list, returning the statement list.
91247          *
91248          * @param statements A statement list to which the down-level export statements are to be
91249          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91250          * appended.
91251          * @param decl The declaration to export.
91252          * @param excludeName An optional name to exclude from exports.
91253          */
91254         function appendExportsOfDeclaration(statements, decl, excludeName) {
91255             if (moduleInfo.exportEquals) {
91256                 return statements;
91257             }
91258             var name = ts.getDeclarationName(decl);
91259             var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
91260             if (exportSpecifiers) {
91261                 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
91262                     var exportSpecifier = exportSpecifiers_2[_i];
91263                     if (exportSpecifier.name.escapedText !== excludeName) {
91264                         statements = appendExportStatement(statements, exportSpecifier.name, name);
91265                     }
91266                 }
91267             }
91268             return statements;
91269         }
91270         /**
91271          * Appends the down-level representation of an export to a statement list, returning the
91272          * statement list.
91273          *
91274          * @param statements A statement list to which the down-level export statements are to be
91275          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91276          * appended.
91277          * @param exportName The name of the export.
91278          * @param expression The expression to export.
91279          * @param allowComments Whether to allow comments on the export.
91280          */
91281         function appendExportStatement(statements, exportName, expression, allowComments) {
91282             statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
91283             return statements;
91284         }
91285         /**
91286          * Creates a call to the current file's export function to export a value.
91287          *
91288          * @param name The bound name of the export.
91289          * @param value The exported value.
91290          * @param allowComments An optional value indicating whether to emit comments for the statement.
91291          */
91292         function createExportStatement(name, value, allowComments) {
91293             var statement = ts.createExpressionStatement(createExportExpression(name, value));
91294             ts.startOnNewLine(statement);
91295             if (!allowComments) {
91296                 ts.setEmitFlags(statement, 1536 /* NoComments */);
91297             }
91298             return statement;
91299         }
91300         /**
91301          * Creates a call to the current file's export function to export a value.
91302          *
91303          * @param name The bound name of the export.
91304          * @param value The exported value.
91305          */
91306         function createExportExpression(name, value) {
91307             var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name;
91308             ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
91309             return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
91310         }
91311         //
91312         // Top-Level or Nested Source Element Visitors
91313         //
91314         /**
91315          * Visit nested elements at the top-level of a module.
91316          *
91317          * @param node The node to visit.
91318          */
91319         function nestedElementVisitor(node) {
91320             switch (node.kind) {
91321                 case 225 /* VariableStatement */:
91322                     return visitVariableStatement(node);
91323                 case 244 /* FunctionDeclaration */:
91324                     return visitFunctionDeclaration(node);
91325                 case 245 /* ClassDeclaration */:
91326                     return visitClassDeclaration(node);
91327                 case 230 /* ForStatement */:
91328                     return visitForStatement(node);
91329                 case 231 /* ForInStatement */:
91330                     return visitForInStatement(node);
91331                 case 232 /* ForOfStatement */:
91332                     return visitForOfStatement(node);
91333                 case 228 /* DoStatement */:
91334                     return visitDoStatement(node);
91335                 case 229 /* WhileStatement */:
91336                     return visitWhileStatement(node);
91337                 case 238 /* LabeledStatement */:
91338                     return visitLabeledStatement(node);
91339                 case 236 /* WithStatement */:
91340                     return visitWithStatement(node);
91341                 case 237 /* SwitchStatement */:
91342                     return visitSwitchStatement(node);
91343                 case 251 /* CaseBlock */:
91344                     return visitCaseBlock(node);
91345                 case 277 /* CaseClause */:
91346                     return visitCaseClause(node);
91347                 case 278 /* DefaultClause */:
91348                     return visitDefaultClause(node);
91349                 case 240 /* TryStatement */:
91350                     return visitTryStatement(node);
91351                 case 280 /* CatchClause */:
91352                     return visitCatchClause(node);
91353                 case 223 /* Block */:
91354                     return visitBlock(node);
91355                 case 328 /* MergeDeclarationMarker */:
91356                     return visitMergeDeclarationMarker(node);
91357                 case 329 /* EndOfDeclarationMarker */:
91358                     return visitEndOfDeclarationMarker(node);
91359                 default:
91360                     return destructuringAndImportCallVisitor(node);
91361             }
91362         }
91363         /**
91364          * Visits the body of a ForStatement to hoist declarations.
91365          *
91366          * @param node The node to visit.
91367          */
91368         function visitForStatement(node) {
91369             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91370             enclosingBlockScopedContainer = node;
91371             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));
91372             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91373             return node;
91374         }
91375         /**
91376          * Visits the body of a ForInStatement to hoist declarations.
91377          *
91378          * @param node The node to visit.
91379          */
91380         function visitForInStatement(node) {
91381             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91382             enclosingBlockScopedContainer = node;
91383             node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91384             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91385             return node;
91386         }
91387         /**
91388          * Visits the body of a ForOfStatement to hoist declarations.
91389          *
91390          * @param node The node to visit.
91391          */
91392         function visitForOfStatement(node) {
91393             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91394             enclosingBlockScopedContainer = node;
91395             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));
91396             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91397             return node;
91398         }
91399         /**
91400          * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
91401          * ForOfStatement.
91402          *
91403          * @param node The node to test.
91404          */
91405         function shouldHoistForInitializer(node) {
91406             return ts.isVariableDeclarationList(node)
91407                 && shouldHoistVariableDeclarationList(node);
91408         }
91409         /**
91410          * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
91411          *
91412          * @param node The node to visit.
91413          */
91414         function visitForInitializer(node) {
91415             if (shouldHoistForInitializer(node)) {
91416                 var expressions = void 0;
91417                 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
91418                     var variable = _a[_i];
91419                     expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
91420                     if (!variable.initializer) {
91421                         hoistBindingElement(variable);
91422                     }
91423                 }
91424                 return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression();
91425             }
91426             else {
91427                 return ts.visitEachChild(node, nestedElementVisitor, context);
91428             }
91429         }
91430         /**
91431          * Visits the body of a DoStatement to hoist declarations.
91432          *
91433          * @param node The node to visit.
91434          */
91435         function visitDoStatement(node) {
91436             return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
91437         }
91438         /**
91439          * Visits the body of a WhileStatement to hoist declarations.
91440          *
91441          * @param node The node to visit.
91442          */
91443         function visitWhileStatement(node) {
91444             return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91445         }
91446         /**
91447          * Visits the body of a LabeledStatement to hoist declarations.
91448          *
91449          * @param node The node to visit.
91450          */
91451         function visitLabeledStatement(node) {
91452             return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91453         }
91454         /**
91455          * Visits the body of a WithStatement to hoist declarations.
91456          *
91457          * @param node The node to visit.
91458          */
91459         function visitWithStatement(node) {
91460             return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91461         }
91462         /**
91463          * Visits the body of a SwitchStatement to hoist declarations.
91464          *
91465          * @param node The node to visit.
91466          */
91467         function visitSwitchStatement(node) {
91468             return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
91469         }
91470         /**
91471          * Visits the body of a CaseBlock to hoist declarations.
91472          *
91473          * @param node The node to visit.
91474          */
91475         function visitCaseBlock(node) {
91476             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91477             enclosingBlockScopedContainer = node;
91478             node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
91479             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91480             return node;
91481         }
91482         /**
91483          * Visits the body of a CaseClause to hoist declarations.
91484          *
91485          * @param node The node to visit.
91486          */
91487         function visitCaseClause(node) {
91488             return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
91489         }
91490         /**
91491          * Visits the body of a DefaultClause to hoist declarations.
91492          *
91493          * @param node The node to visit.
91494          */
91495         function visitDefaultClause(node) {
91496             return ts.visitEachChild(node, nestedElementVisitor, context);
91497         }
91498         /**
91499          * Visits the body of a TryStatement to hoist declarations.
91500          *
91501          * @param node The node to visit.
91502          */
91503         function visitTryStatement(node) {
91504             return ts.visitEachChild(node, nestedElementVisitor, context);
91505         }
91506         /**
91507          * Visits the body of a CatchClause to hoist declarations.
91508          *
91509          * @param node The node to visit.
91510          */
91511         function visitCatchClause(node) {
91512             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91513             enclosingBlockScopedContainer = node;
91514             node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
91515             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91516             return node;
91517         }
91518         /**
91519          * Visits the body of a Block to hoist declarations.
91520          *
91521          * @param node The node to visit.
91522          */
91523         function visitBlock(node) {
91524             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91525             enclosingBlockScopedContainer = node;
91526             node = ts.visitEachChild(node, nestedElementVisitor, context);
91527             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91528             return node;
91529         }
91530         //
91531         // Destructuring Assignment Visitors
91532         //
91533         /**
91534          * Visit nodes to flatten destructuring assignments to exported symbols.
91535          *
91536          * @param node The node to visit.
91537          */
91538         function destructuringAndImportCallVisitor(node) {
91539             if (ts.isDestructuringAssignment(node)) {
91540                 return visitDestructuringAssignment(node);
91541             }
91542             else if (ts.isImportCall(node)) {
91543                 return visitImportCallExpression(node);
91544             }
91545             else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
91546                 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91547             }
91548             else {
91549                 return node;
91550             }
91551         }
91552         function visitImportCallExpression(node) {
91553             // import("./blah")
91554             // emit as
91555             // System.register([], function (_export, _context) {
91556             //     return {
91557             //         setters: [],
91558             //         execute: () => {
91559             //             _context.import('./blah');
91560             //         }
91561             //     };
91562             // });
91563             return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), 
91564             /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
91565         }
91566         /**
91567          * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
91568          *
91569          * @param node The node to visit.
91570          */
91571         function visitDestructuringAssignment(node) {
91572             if (hasExportedReferenceInDestructuringTarget(node.left)) {
91573                 return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91574                 /*needsValue*/ true);
91575             }
91576             return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91577         }
91578         /**
91579          * Determines whether the target of a destructuring assigment refers to an exported symbol.
91580          *
91581          * @param node The destructuring target.
91582          */
91583         function hasExportedReferenceInDestructuringTarget(node) {
91584             if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
91585                 return hasExportedReferenceInDestructuringTarget(node.left);
91586             }
91587             else if (ts.isSpreadElement(node)) {
91588                 return hasExportedReferenceInDestructuringTarget(node.expression);
91589             }
91590             else if (ts.isObjectLiteralExpression(node)) {
91591                 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
91592             }
91593             else if (ts.isArrayLiteralExpression(node)) {
91594                 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
91595             }
91596             else if (ts.isShorthandPropertyAssignment(node)) {
91597                 return hasExportedReferenceInDestructuringTarget(node.name);
91598             }
91599             else if (ts.isPropertyAssignment(node)) {
91600                 return hasExportedReferenceInDestructuringTarget(node.initializer);
91601             }
91602             else if (ts.isIdentifier(node)) {
91603                 var container = resolver.getReferencedExportContainer(node);
91604                 return container !== undefined && container.kind === 290 /* SourceFile */;
91605             }
91606             else {
91607                 return false;
91608             }
91609         }
91610         //
91611         // Modifier Visitors
91612         //
91613         /**
91614          * Visit nodes to elide module-specific modifiers.
91615          *
91616          * @param node The node to visit.
91617          */
91618         function modifierVisitor(node) {
91619             switch (node.kind) {
91620                 case 89 /* ExportKeyword */:
91621                 case 84 /* DefaultKeyword */:
91622                     return undefined;
91623             }
91624             return node;
91625         }
91626         //
91627         // Emit Notification
91628         //
91629         /**
91630          * Hook for node emit notifications.
91631          *
91632          * @param hint A hint as to the intended usage of the node.
91633          * @param node The node to emit.
91634          * @param emitCallback A callback used to emit the node in the printer.
91635          */
91636         function onEmitNode(hint, node, emitCallback) {
91637             if (node.kind === 290 /* SourceFile */) {
91638                 var id = ts.getOriginalNodeId(node);
91639                 currentSourceFile = node;
91640                 moduleInfo = moduleInfoMap[id];
91641                 exportFunction = exportFunctionsMap[id];
91642                 noSubstitution = noSubstitutionMap[id];
91643                 contextObject = contextObjectMap[id];
91644                 if (noSubstitution) {
91645                     delete noSubstitutionMap[id];
91646                 }
91647                 previousOnEmitNode(hint, node, emitCallback);
91648                 currentSourceFile = undefined;
91649                 moduleInfo = undefined;
91650                 exportFunction = undefined;
91651                 contextObject = undefined;
91652                 noSubstitution = undefined;
91653             }
91654             else {
91655                 previousOnEmitNode(hint, node, emitCallback);
91656             }
91657         }
91658         //
91659         // Substitutions
91660         //
91661         /**
91662          * Hooks node substitutions.
91663          *
91664          * @param hint A hint as to the intended usage of the node.
91665          * @param node The node to substitute.
91666          */
91667         function onSubstituteNode(hint, node) {
91668             node = previousOnSubstituteNode(hint, node);
91669             if (isSubstitutionPrevented(node)) {
91670                 return node;
91671             }
91672             if (hint === 1 /* Expression */) {
91673                 return substituteExpression(node);
91674             }
91675             else if (hint === 4 /* Unspecified */) {
91676                 return substituteUnspecified(node);
91677             }
91678             return node;
91679         }
91680         /**
91681          * Substitute the node, if necessary.
91682          *
91683          * @param node The node to substitute.
91684          */
91685         function substituteUnspecified(node) {
91686             switch (node.kind) {
91687                 case 282 /* ShorthandPropertyAssignment */:
91688                     return substituteShorthandPropertyAssignment(node);
91689             }
91690             return node;
91691         }
91692         /**
91693          * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
91694          *
91695          * @param node The node to substitute.
91696          */
91697         function substituteShorthandPropertyAssignment(node) {
91698             var name = node.name;
91699             if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
91700                 var importDeclaration = resolver.getReferencedImportDeclaration(name);
91701                 if (importDeclaration) {
91702                     if (ts.isImportClause(importDeclaration)) {
91703                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), 
91704                         /*location*/ node);
91705                     }
91706                     else if (ts.isImportSpecifier(importDeclaration)) {
91707                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), 
91708                         /*location*/ node);
91709                     }
91710                 }
91711             }
91712             return node;
91713         }
91714         /**
91715          * Substitute the expression, if necessary.
91716          *
91717          * @param node The node to substitute.
91718          */
91719         function substituteExpression(node) {
91720             switch (node.kind) {
91721                 case 75 /* Identifier */:
91722                     return substituteExpressionIdentifier(node);
91723                 case 209 /* BinaryExpression */:
91724                     return substituteBinaryExpression(node);
91725                 case 207 /* PrefixUnaryExpression */:
91726                 case 208 /* PostfixUnaryExpression */:
91727                     return substituteUnaryExpression(node);
91728                 case 219 /* MetaProperty */:
91729                     return substituteMetaProperty(node);
91730             }
91731             return node;
91732         }
91733         /**
91734          * Substitution for an Identifier expression that may contain an imported or exported symbol.
91735          *
91736          * @param node The node to substitute.
91737          */
91738         function substituteExpressionIdentifier(node) {
91739             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
91740                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
91741                 if (externalHelpersModuleName) {
91742                     return ts.createPropertyAccess(externalHelpersModuleName, node);
91743                 }
91744                 return node;
91745             }
91746             // When we see an identifier in an expression position that
91747             // points to an imported symbol, we should substitute a qualified
91748             // reference to the imported symbol if one is needed.
91749             //
91750             // - We do not substitute generated identifiers for any reason.
91751             // - We do not substitute identifiers tagged with the LocalName flag.
91752             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
91753                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
91754                 if (importDeclaration) {
91755                     if (ts.isImportClause(importDeclaration)) {
91756                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
91757                         /*location*/ node);
91758                     }
91759                     else if (ts.isImportSpecifier(importDeclaration)) {
91760                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), 
91761                         /*location*/ node);
91762                     }
91763                 }
91764             }
91765             return node;
91766         }
91767         /**
91768          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
91769          *
91770          * @param node The node to substitute.
91771          */
91772         function substituteBinaryExpression(node) {
91773             // When we see an assignment expression whose left-hand side is an exported symbol,
91774             // we should ensure all exports of that symbol are updated with the correct value.
91775             //
91776             // - We do not substitute generated identifiers for any reason.
91777             // - We do not substitute identifiers tagged with the LocalName flag.
91778             // - We do not substitute identifiers that were originally the name of an enum or
91779             //   namespace due to how they are transformed in TypeScript.
91780             // - We only substitute identifiers that are exported at the top level.
91781             if (ts.isAssignmentOperator(node.operatorToken.kind)
91782                 && ts.isIdentifier(node.left)
91783                 && !ts.isGeneratedIdentifier(node.left)
91784                 && !ts.isLocalName(node.left)
91785                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
91786                 var exportedNames = getExports(node.left);
91787                 if (exportedNames) {
91788                     // For each additional export of the declaration, apply an export assignment.
91789                     var expression = node;
91790                     for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
91791                         var exportName = exportedNames_4[_i];
91792                         expression = createExportExpression(exportName, preventSubstitution(expression));
91793                     }
91794                     return expression;
91795                 }
91796             }
91797             return node;
91798         }
91799         /**
91800          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
91801          *
91802          * @param node The node to substitute.
91803          */
91804         function substituteUnaryExpression(node) {
91805             // When we see a prefix or postfix increment expression whose operand is an exported
91806             // symbol, we should ensure all exports of that symbol are updated with the correct
91807             // value.
91808             //
91809             // - We do not substitute generated identifiers for any reason.
91810             // - We do not substitute identifiers tagged with the LocalName flag.
91811             // - We do not substitute identifiers that were originally the name of an enum or
91812             //   namespace due to how they are transformed in TypeScript.
91813             // - We only substitute identifiers that are exported at the top level.
91814             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
91815                 && ts.isIdentifier(node.operand)
91816                 && !ts.isGeneratedIdentifier(node.operand)
91817                 && !ts.isLocalName(node.operand)
91818                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
91819                 var exportedNames = getExports(node.operand);
91820                 if (exportedNames) {
91821                     var expression = node.kind === 208 /* PostfixUnaryExpression */
91822                         ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
91823                         : node;
91824                     for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
91825                         var exportName = exportedNames_5[_i];
91826                         expression = createExportExpression(exportName, preventSubstitution(expression));
91827                     }
91828                     if (node.kind === 208 /* PostfixUnaryExpression */) {
91829                         expression = node.operator === 45 /* PlusPlusToken */
91830                             ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1))
91831                             : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1));
91832                     }
91833                     return expression;
91834                 }
91835             }
91836             return node;
91837         }
91838         function substituteMetaProperty(node) {
91839             if (ts.isImportMeta(node)) {
91840                 return ts.createPropertyAccess(contextObject, ts.createIdentifier("meta"));
91841             }
91842             return node;
91843         }
91844         /**
91845          * Gets the exports of a name.
91846          *
91847          * @param name The name.
91848          */
91849         function getExports(name) {
91850             var exportedNames;
91851             if (!ts.isGeneratedIdentifier(name)) {
91852                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
91853                     || resolver.getReferencedValueDeclaration(name);
91854                 if (valueDeclaration) {
91855                     var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
91856                     if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
91857                         exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
91858                     }
91859                     exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
91860                 }
91861             }
91862             return exportedNames;
91863         }
91864         /**
91865          * Prevent substitution of a node for this transformer.
91866          *
91867          * @param node The node which should not be substituted.
91868          */
91869         function preventSubstitution(node) {
91870             if (noSubstitution === undefined)
91871                 noSubstitution = [];
91872             noSubstitution[ts.getNodeId(node)] = true;
91873             return node;
91874         }
91875         /**
91876          * Determines whether a node should not be substituted.
91877          *
91878          * @param node The node to test.
91879          */
91880         function isSubstitutionPrevented(node) {
91881             return noSubstitution && node.id && noSubstitution[node.id];
91882         }
91883     }
91884     ts.transformSystemModule = transformSystemModule;
91885 })(ts || (ts = {}));
91886 /*@internal*/
91887 var ts;
91888 (function (ts) {
91889     function transformECMAScriptModule(context) {
91890         var compilerOptions = context.getCompilerOptions();
91891         var previousOnEmitNode = context.onEmitNode;
91892         var previousOnSubstituteNode = context.onSubstituteNode;
91893         context.onEmitNode = onEmitNode;
91894         context.onSubstituteNode = onSubstituteNode;
91895         context.enableEmitNotification(290 /* SourceFile */);
91896         context.enableSubstitution(75 /* Identifier */);
91897         var helperNameSubstitutions;
91898         return ts.chainBundle(transformSourceFile);
91899         function transformSourceFile(node) {
91900             if (node.isDeclarationFile) {
91901                 return node;
91902             }
91903             if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
91904                 var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(node, compilerOptions);
91905                 if (externalHelpersImportDeclaration) {
91906                     var statements = [];
91907                     var statementOffset = ts.addPrologue(statements, node.statements);
91908                     ts.append(statements, externalHelpersImportDeclaration);
91909                     ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
91910                     return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
91911                 }
91912                 else {
91913                     return ts.visitEachChild(node, visitor, context);
91914                 }
91915             }
91916             return node;
91917         }
91918         function visitor(node) {
91919             switch (node.kind) {
91920                 case 253 /* ImportEqualsDeclaration */:
91921                     // Elide `import=` as it is not legal with --module ES6
91922                     return undefined;
91923                 case 259 /* ExportAssignment */:
91924                     return visitExportAssignment(node);
91925                 case 260 /* ExportDeclaration */:
91926                     var exportDecl = node;
91927                     return visitExportDeclaration(exportDecl);
91928             }
91929             return node;
91930         }
91931         function visitExportAssignment(node) {
91932             // Elide `export=` as it is not legal with --module ES6
91933             return node.isExportEquals ? undefined : node;
91934         }
91935         function visitExportDeclaration(node) {
91936             // `export * as ns` only needs to be transformed in ES2015
91937             if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
91938                 return node;
91939             }
91940             // Either ill-formed or don't need to be tranformed.
91941             if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
91942                 return node;
91943             }
91944             var oldIdentifier = node.exportClause.name;
91945             var synthName = ts.getGeneratedNameForNode(oldIdentifier);
91946             var importDecl = ts.createImportDeclaration(
91947             /*decorators*/ undefined, 
91948             /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(synthName)), node.moduleSpecifier);
91949             ts.setOriginalNode(importDecl, node.exportClause);
91950             var exportDecl = ts.createExportDeclaration(
91951             /*decorators*/ undefined, 
91952             /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(synthName, oldIdentifier)]));
91953             ts.setOriginalNode(exportDecl, node);
91954             return [importDecl, exportDecl];
91955         }
91956         //
91957         // Emit Notification
91958         //
91959         /**
91960          * Hook for node emit.
91961          *
91962          * @param hint A hint as to the intended usage of the node.
91963          * @param node The node to emit.
91964          * @param emit A callback used to emit the node in the printer.
91965          */
91966         function onEmitNode(hint, node, emitCallback) {
91967             if (ts.isSourceFile(node)) {
91968                 if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
91969                     helperNameSubstitutions = ts.createMap();
91970                 }
91971                 previousOnEmitNode(hint, node, emitCallback);
91972                 helperNameSubstitutions = undefined;
91973             }
91974             else {
91975                 previousOnEmitNode(hint, node, emitCallback);
91976             }
91977         }
91978         //
91979         // Substitutions
91980         //
91981         /**
91982          * Hooks node substitutions.
91983          *
91984          * @param hint A hint as to the intended usage of the node.
91985          * @param node The node to substitute.
91986          */
91987         function onSubstituteNode(hint, node) {
91988             node = previousOnSubstituteNode(hint, node);
91989             if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
91990                 return substituteHelperName(node);
91991             }
91992             return node;
91993         }
91994         function substituteHelperName(node) {
91995             var name = ts.idText(node);
91996             var substitution = helperNameSubstitutions.get(name);
91997             if (!substitution) {
91998                 helperNameSubstitutions.set(name, substitution = ts.createFileLevelUniqueName(name));
91999             }
92000             return substitution;
92001         }
92002     }
92003     ts.transformECMAScriptModule = transformECMAScriptModule;
92004 })(ts || (ts = {}));
92005 /* @internal */
92006 var ts;
92007 (function (ts) {
92008     function canProduceDiagnostics(node) {
92009         return ts.isVariableDeclaration(node) ||
92010             ts.isPropertyDeclaration(node) ||
92011             ts.isPropertySignature(node) ||
92012             ts.isBindingElement(node) ||
92013             ts.isSetAccessor(node) ||
92014             ts.isGetAccessor(node) ||
92015             ts.isConstructSignatureDeclaration(node) ||
92016             ts.isCallSignatureDeclaration(node) ||
92017             ts.isMethodDeclaration(node) ||
92018             ts.isMethodSignature(node) ||
92019             ts.isFunctionDeclaration(node) ||
92020             ts.isParameter(node) ||
92021             ts.isTypeParameterDeclaration(node) ||
92022             ts.isExpressionWithTypeArguments(node) ||
92023             ts.isImportEqualsDeclaration(node) ||
92024             ts.isTypeAliasDeclaration(node) ||
92025             ts.isConstructorDeclaration(node) ||
92026             ts.isIndexSignatureDeclaration(node) ||
92027             ts.isPropertyAccessExpression(node);
92028     }
92029     ts.canProduceDiagnostics = canProduceDiagnostics;
92030     function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
92031         if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92032             return getAccessorNameVisibilityError;
92033         }
92034         else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
92035             return getMethodNameVisibilityError;
92036         }
92037         else {
92038             return createGetSymbolAccessibilityDiagnosticForNode(node);
92039         }
92040         function getAccessorNameVisibilityError(symbolAccessibilityResult) {
92041             var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92042             return diagnosticMessage !== undefined ? {
92043                 diagnosticMessage: diagnosticMessage,
92044                 errorNode: node,
92045                 typeName: node.name
92046             } : undefined;
92047         }
92048         function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92049             if (ts.hasModifier(node, 32 /* Static */)) {
92050                 return symbolAccessibilityResult.errorModuleName ?
92051                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92052                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92053                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92054                     ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92055             }
92056             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92057                 return symbolAccessibilityResult.errorModuleName ?
92058                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92059                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92060                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92061                     ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92062             }
92063             else {
92064                 return symbolAccessibilityResult.errorModuleName ?
92065                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92066                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92067             }
92068         }
92069         function getMethodNameVisibilityError(symbolAccessibilityResult) {
92070             var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92071             return diagnosticMessage !== undefined ? {
92072                 diagnosticMessage: diagnosticMessage,
92073                 errorNode: node,
92074                 typeName: node.name
92075             } : undefined;
92076         }
92077         function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92078             if (ts.hasModifier(node, 32 /* Static */)) {
92079                 return symbolAccessibilityResult.errorModuleName ?
92080                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92081                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92082                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92083                     ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
92084             }
92085             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92086                 return symbolAccessibilityResult.errorModuleName ?
92087                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92088                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92089                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92090                     ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
92091             }
92092             else {
92093                 return symbolAccessibilityResult.errorModuleName ?
92094                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92095                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
92096             }
92097         }
92098     }
92099     ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
92100     function createGetSymbolAccessibilityDiagnosticForNode(node) {
92101         if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
92102             return getVariableDeclarationTypeVisibilityError;
92103         }
92104         else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92105             return getAccessorDeclarationTypeVisibilityError;
92106         }
92107         else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
92108             return getReturnTypeVisibilityError;
92109         }
92110         else if (ts.isParameter(node)) {
92111             if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasModifier(node.parent, 8 /* Private */)) {
92112                 return getVariableDeclarationTypeVisibilityError;
92113             }
92114             return getParameterDeclarationTypeVisibilityError;
92115         }
92116         else if (ts.isTypeParameterDeclaration(node)) {
92117             return getTypeParameterConstraintVisibilityError;
92118         }
92119         else if (ts.isExpressionWithTypeArguments(node)) {
92120             return getHeritageClauseVisibilityError;
92121         }
92122         else if (ts.isImportEqualsDeclaration(node)) {
92123             return getImportEntityNameVisibilityError;
92124         }
92125         else if (ts.isTypeAliasDeclaration(node)) {
92126             return getTypeAliasDeclarationVisibilityError;
92127         }
92128         else {
92129             return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
92130         }
92131         function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92132             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
92133                 return symbolAccessibilityResult.errorModuleName ?
92134                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92135                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92136                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
92137                     ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
92138             }
92139             // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
92140             // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
92141             else if (node.kind === 159 /* PropertyDeclaration */ || node.kind === 194 /* PropertyAccessExpression */ || node.kind === 158 /* PropertySignature */ ||
92142                 (node.kind === 156 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
92143                 // TODO(jfreeman): Deal with computed properties in error reporting.
92144                 if (ts.hasModifier(node, 32 /* Static */)) {
92145                     return symbolAccessibilityResult.errorModuleName ?
92146                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92147                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92148                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92149                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92150                 }
92151                 else if (node.parent.kind === 245 /* ClassDeclaration */ || node.kind === 156 /* Parameter */) {
92152                     return symbolAccessibilityResult.errorModuleName ?
92153                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92154                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92155                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92156                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92157                 }
92158                 else {
92159                     // Interfaces cannot have types that cannot be named
92160                     return symbolAccessibilityResult.errorModuleName ?
92161                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92162                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92163                 }
92164             }
92165         }
92166         function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92167             var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92168             return diagnosticMessage !== undefined ? {
92169                 diagnosticMessage: diagnosticMessage,
92170                 errorNode: node,
92171                 typeName: node.name
92172             } : undefined;
92173         }
92174         function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92175             var diagnosticMessage;
92176             if (node.kind === 164 /* SetAccessor */) {
92177                 // Getters can infer the return type from the returned expression, but setters cannot, so the
92178                 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
92179                 if (ts.hasModifier(node, 32 /* Static */)) {
92180                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92181                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92182                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
92183                 }
92184                 else {
92185                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92186                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92187                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
92188                 }
92189             }
92190             else {
92191                 if (ts.hasModifier(node, 32 /* Static */)) {
92192                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92193                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92194                             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 :
92195                             ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92196                         ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
92197                 }
92198                 else {
92199                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92200                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92201                             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 :
92202                             ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92203                         ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
92204                 }
92205             }
92206             return {
92207                 diagnosticMessage: diagnosticMessage,
92208                 errorNode: node.name,
92209                 typeName: node.name
92210             };
92211         }
92212         function getReturnTypeVisibilityError(symbolAccessibilityResult) {
92213             var diagnosticMessage;
92214             switch (node.kind) {
92215                 case 166 /* ConstructSignature */:
92216                     // Interfaces cannot have return types that cannot be named
92217                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92218                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92219                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
92220                     break;
92221                 case 165 /* CallSignature */:
92222                     // Interfaces cannot have return types that cannot be named
92223                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92224                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92225                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
92226                     break;
92227                 case 167 /* IndexSignature */:
92228                     // Interfaces cannot have return types that cannot be named
92229                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92230                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92231                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
92232                     break;
92233                 case 161 /* MethodDeclaration */:
92234                 case 160 /* MethodSignature */:
92235                     if (ts.hasModifier(node, 32 /* Static */)) {
92236                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92237                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92238                                 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 :
92239                                 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92240                             ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
92241                     }
92242                     else if (node.parent.kind === 245 /* ClassDeclaration */) {
92243                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92244                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92245                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92246                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92247                             ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
92248                     }
92249                     else {
92250                         // Interfaces cannot have return types that cannot be named
92251                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92252                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92253                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
92254                     }
92255                     break;
92256                 case 244 /* FunctionDeclaration */:
92257                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92258                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92259                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92260                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
92261                         ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
92262                     break;
92263                 default:
92264                     return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
92265             }
92266             return {
92267                 diagnosticMessage: diagnosticMessage,
92268                 errorNode: node.name || node
92269             };
92270         }
92271         function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92272             var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92273             return diagnosticMessage !== undefined ? {
92274                 diagnosticMessage: diagnosticMessage,
92275                 errorNode: node,
92276                 typeName: node.name
92277             } : undefined;
92278         }
92279         function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92280             switch (node.parent.kind) {
92281                 case 162 /* Constructor */:
92282                     return symbolAccessibilityResult.errorModuleName ?
92283                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92284                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92285                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92286                         ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
92287                 case 166 /* ConstructSignature */:
92288                 case 171 /* ConstructorType */:
92289                     // Interfaces cannot have parameter types that cannot be named
92290                     return symbolAccessibilityResult.errorModuleName ?
92291                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92292                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92293                 case 165 /* CallSignature */:
92294                     // Interfaces cannot have parameter types that cannot be named
92295                     return symbolAccessibilityResult.errorModuleName ?
92296                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92297                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92298                 case 167 /* IndexSignature */:
92299                     // Interfaces cannot have parameter types that cannot be named
92300                     return symbolAccessibilityResult.errorModuleName ?
92301                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92302                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
92303                 case 161 /* MethodDeclaration */:
92304                 case 160 /* MethodSignature */:
92305                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92306                         return symbolAccessibilityResult.errorModuleName ?
92307                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92308                                 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 :
92309                                 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92310                             ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92311                     }
92312                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92313                         return symbolAccessibilityResult.errorModuleName ?
92314                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92315                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92316                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92317                             ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92318                     }
92319                     else {
92320                         // Interfaces cannot have parameter types that cannot be named
92321                         return symbolAccessibilityResult.errorModuleName ?
92322                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92323                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92324                     }
92325                 case 244 /* FunctionDeclaration */:
92326                 case 170 /* FunctionType */:
92327                     return symbolAccessibilityResult.errorModuleName ?
92328                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92329                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92330                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
92331                         ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
92332                 case 164 /* SetAccessor */:
92333                 case 163 /* GetAccessor */:
92334                     return symbolAccessibilityResult.errorModuleName ?
92335                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92336                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92337                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
92338                         ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
92339                 default:
92340                     return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
92341             }
92342         }
92343         function getTypeParameterConstraintVisibilityError() {
92344             // Type parameter constraints are named by user so we should always be able to name it
92345             var diagnosticMessage;
92346             switch (node.parent.kind) {
92347                 case 245 /* ClassDeclaration */:
92348                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
92349                     break;
92350                 case 246 /* InterfaceDeclaration */:
92351                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
92352                     break;
92353                 case 186 /* MappedType */:
92354                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
92355                     break;
92356                 case 171 /* ConstructorType */:
92357                 case 166 /* ConstructSignature */:
92358                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92359                     break;
92360                 case 165 /* CallSignature */:
92361                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92362                     break;
92363                 case 161 /* MethodDeclaration */:
92364                 case 160 /* MethodSignature */:
92365                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92366                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92367                     }
92368                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92369                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92370                     }
92371                     else {
92372                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92373                     }
92374                     break;
92375                 case 170 /* FunctionType */:
92376                 case 244 /* FunctionDeclaration */:
92377                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
92378                     break;
92379                 case 247 /* TypeAliasDeclaration */:
92380                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
92381                     break;
92382                 default:
92383                     return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
92384             }
92385             return {
92386                 diagnosticMessage: diagnosticMessage,
92387                 errorNode: node,
92388                 typeName: node.name
92389             };
92390         }
92391         function getHeritageClauseVisibilityError() {
92392             var diagnosticMessage;
92393             // Heritage clause is written by user so it can always be named
92394             if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92395                 // Class or Interface implemented/extended is inaccessible
92396                 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 113 /* ImplementsKeyword */ ?
92397                     ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
92398                     ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1;
92399             }
92400             else {
92401                 // interface is inaccessible
92402                 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
92403             }
92404             return {
92405                 diagnosticMessage: diagnosticMessage,
92406                 errorNode: node,
92407                 typeName: ts.getNameOfDeclaration(node.parent.parent)
92408             };
92409         }
92410         function getImportEntityNameVisibilityError() {
92411             return {
92412                 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
92413                 errorNode: node,
92414                 typeName: node.name
92415             };
92416         }
92417         function getTypeAliasDeclarationVisibilityError() {
92418             return {
92419                 diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
92420                 errorNode: node.type,
92421                 typeName: node.name
92422             };
92423         }
92424     }
92425     ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
92426 })(ts || (ts = {}));
92427 /*@internal*/
92428 var ts;
92429 (function (ts) {
92430     function getDeclarationDiagnostics(host, resolver, file) {
92431         if (file && ts.isJsonSourceFile(file)) {
92432             return []; // No declaration diagnostics for json for now
92433         }
92434         var compilerOptions = host.getCompilerOptions();
92435         var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
92436         return result.diagnostics;
92437     }
92438     ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
92439     function hasInternalAnnotation(range, currentSourceFile) {
92440         var comment = currentSourceFile.text.substring(range.pos, range.end);
92441         return ts.stringContains(comment, "@internal");
92442     }
92443     function isInternalDeclaration(node, currentSourceFile) {
92444         var parseTreeNode = ts.getParseTreeNode(node);
92445         if (parseTreeNode && parseTreeNode.kind === 156 /* Parameter */) {
92446             var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
92447             var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
92448             var text = currentSourceFile.text;
92449             var commentRanges = previousSibling
92450                 ? ts.concatenate(
92451                 // to handle
92452                 // ... parameters, /* @internal */
92453                 // public param: string
92454                 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
92455                 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
92456             return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
92457         }
92458         var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
92459         return !!ts.forEach(leadingCommentRanges, function (range) {
92460             return hasInternalAnnotation(range, currentSourceFile);
92461         });
92462     }
92463     ts.isInternalDeclaration = isInternalDeclaration;
92464     var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
92465         2048 /* WriteClassExpressionAsTypeLiteral */ |
92466         4096 /* UseTypeOfFunction */ |
92467         8 /* UseStructuralFallback */ |
92468         524288 /* AllowEmptyTuple */ |
92469         4 /* GenerateNamesForShadowedTypeParams */ |
92470         1 /* NoTruncation */;
92471     /**
92472      * Transforms a ts file into a .d.ts file
92473      * This process requires type information, which is retrieved through the emit resolver. Because of this,
92474      * in many places this transformer assumes it will be operating on parse tree nodes directly.
92475      * This means that _no transforms should be allowed to occur before this one_.
92476      */
92477     function transformDeclarations(context) {
92478         var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
92479         var getSymbolAccessibilityDiagnostic = throwDiagnostic;
92480         var needsDeclare = true;
92481         var isBundledEmit = false;
92482         var resultHasExternalModuleIndicator = false;
92483         var needsScopeFixMarker = false;
92484         var resultHasScopeMarker = false;
92485         var enclosingDeclaration;
92486         var necessaryTypeReferences;
92487         var lateMarkedStatements;
92488         var lateStatementReplacementMap;
92489         var suppressNewDiagnosticContexts;
92490         var exportedModulesFromDeclarationEmit;
92491         var host = context.getEmitHost();
92492         var symbolTracker = {
92493             trackSymbol: trackSymbol,
92494             reportInaccessibleThisError: reportInaccessibleThisError,
92495             reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
92496             reportCyclicStructureError: reportCyclicStructureError,
92497             reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
92498             reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
92499             moduleResolverHost: host,
92500             trackReferencedAmbientModule: trackReferencedAmbientModule,
92501             trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode,
92502             reportNonlocalAugmentation: reportNonlocalAugmentation
92503         };
92504         var errorNameNode;
92505         var currentSourceFile;
92506         var refs;
92507         var libs;
92508         var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
92509         var resolver = context.getEmitResolver();
92510         var options = context.getCompilerOptions();
92511         var noResolve = options.noResolve, stripInternal = options.stripInternal;
92512         return transformRoot;
92513         function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
92514             if (!typeReferenceDirectives) {
92515                 return;
92516             }
92517             necessaryTypeReferences = necessaryTypeReferences || ts.createMap();
92518             for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
92519                 var ref = typeReferenceDirectives_2[_i];
92520                 necessaryTypeReferences.set(ref, true);
92521             }
92522         }
92523         function trackReferencedAmbientModule(node, symbol) {
92524             // If it is visible via `// <reference types="..."/>`, then we should just use that
92525             var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
92526             if (ts.length(directives)) {
92527                 return recordTypeReferenceDirectivesIfNecessary(directives);
92528             }
92529             // Otherwise we should emit a path-based reference
92530             var container = ts.getSourceFileOfNode(node);
92531             refs.set("" + ts.getOriginalNodeId(container), container);
92532         }
92533         function handleSymbolAccessibilityError(symbolAccessibilityResult) {
92534             if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
92535                 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
92536                 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
92537                     if (!lateMarkedStatements) {
92538                         lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
92539                     }
92540                     else {
92541                         for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
92542                             var ref = _a[_i];
92543                             ts.pushIfUnique(lateMarkedStatements, ref);
92544                         }
92545                     }
92546                 }
92547                 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
92548             }
92549             else {
92550                 // Report error
92551                 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
92552                 if (errorInfo) {
92553                     if (errorInfo.typeName) {
92554                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92555                     }
92556                     else {
92557                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92558                     }
92559                 }
92560             }
92561         }
92562         function trackExternalModuleSymbolOfImportTypeNode(symbol) {
92563             if (!isBundledEmit) {
92564                 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
92565             }
92566         }
92567         function trackSymbol(symbol, enclosingDeclaration, meaning) {
92568             if (symbol.flags & 262144 /* TypeParameter */)
92569                 return;
92570             handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
92571             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
92572         }
92573         function reportPrivateInBaseOfClassExpression(propertyName) {
92574             if (errorNameNode) {
92575                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
92576             }
92577         }
92578         function reportInaccessibleUniqueSymbolError() {
92579             if (errorNameNode) {
92580                 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"));
92581             }
92582         }
92583         function reportCyclicStructureError() {
92584             if (errorNameNode) {
92585                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode)));
92586             }
92587         }
92588         function reportInaccessibleThisError() {
92589             if (errorNameNode) {
92590                 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"));
92591             }
92592         }
92593         function reportLikelyUnsafeImportRequiredError(specifier) {
92594             if (errorNameNode) {
92595                 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));
92596             }
92597         }
92598         function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
92599             var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; });
92600             var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; });
92601             for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) {
92602                 var augmentations = augmentingDeclarations_1[_i];
92603                 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)));
92604             }
92605         }
92606         function transformDeclarationsForJS(sourceFile, bundled) {
92607             var oldDiag = getSymbolAccessibilityDiagnostic;
92608             getSymbolAccessibilityDiagnostic = function (s) { return ({
92609                 diagnosticMessage: s.errorModuleName
92610                     ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
92611                     : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
92612                 errorNode: s.errorNode || sourceFile
92613             }); };
92614             var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
92615             getSymbolAccessibilityDiagnostic = oldDiag;
92616             return result;
92617         }
92618         function transformRoot(node) {
92619             if (node.kind === 290 /* SourceFile */ && node.isDeclarationFile) {
92620                 return node;
92621             }
92622             if (node.kind === 291 /* Bundle */) {
92623                 isBundledEmit = true;
92624                 refs = ts.createMap();
92625                 libs = ts.createMap();
92626                 var hasNoDefaultLib_1 = false;
92627                 var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
92628                     if (sourceFile.isDeclarationFile)
92629                         return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
92630                     hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
92631                     currentSourceFile = sourceFile;
92632                     enclosingDeclaration = sourceFile;
92633                     lateMarkedStatements = undefined;
92634                     suppressNewDiagnosticContexts = false;
92635                     lateStatementReplacementMap = ts.createMap();
92636                     getSymbolAccessibilityDiagnostic = throwDiagnostic;
92637                     needsScopeFixMarker = false;
92638                     resultHasScopeMarker = false;
92639                     collectReferences(sourceFile, refs);
92640                     collectLibs(sourceFile, libs);
92641                     if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
92642                         resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
92643                         needsDeclare = false;
92644                         var statements = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92645                         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*/ []);
92646                         return newFile;
92647                     }
92648                     needsDeclare = true;
92649                     var updated = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92650                     return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
92651                 }), ts.mapDefined(node.prepends, function (prepend) {
92652                     if (prepend.kind === 293 /* InputFiles */) {
92653                         var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
92654                         hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
92655                         collectReferences(sourceFile, refs);
92656                         recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
92657                         collectLibs(sourceFile, libs);
92658                         return sourceFile;
92659                     }
92660                     return prepend;
92661                 }));
92662                 bundle.syntheticFileReferences = [];
92663                 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
92664                 bundle.syntheticLibReferences = getLibReferences();
92665                 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
92666                 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92667                 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
92668                 refs.forEach(referenceVisitor_1);
92669                 return bundle;
92670             }
92671             // Single source file
92672             needsDeclare = true;
92673             needsScopeFixMarker = false;
92674             resultHasScopeMarker = false;
92675             enclosingDeclaration = node;
92676             currentSourceFile = node;
92677             getSymbolAccessibilityDiagnostic = throwDiagnostic;
92678             isBundledEmit = false;
92679             resultHasExternalModuleIndicator = false;
92680             suppressNewDiagnosticContexts = false;
92681             lateMarkedStatements = undefined;
92682             lateStatementReplacementMap = ts.createMap();
92683             necessaryTypeReferences = undefined;
92684             refs = collectReferences(currentSourceFile, ts.createMap());
92685             libs = collectLibs(currentSourceFile, ts.createMap());
92686             var references = [];
92687             var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92688             var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
92689             var combinedStatements;
92690             if (ts.isSourceFileJS(currentSourceFile)) {
92691                 combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node));
92692                 refs.forEach(referenceVisitor);
92693                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92694             }
92695             else {
92696                 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
92697                 combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
92698                 refs.forEach(referenceVisitor);
92699                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92700                 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
92701                     combinedStatements = ts.setTextRange(ts.createNodeArray(__spreadArrays(combinedStatements, [ts.createEmptyExports()])), combinedStatements);
92702                 }
92703             }
92704             var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
92705             updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
92706             return updated;
92707             function getLibReferences() {
92708                 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
92709             }
92710             function getFileReferencesForUsedTypeReferences() {
92711                 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
92712             }
92713             function getFileReferenceForTypeName(typeName) {
92714                 // Elide type references for which we have imports
92715                 if (emittedImports) {
92716                     for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
92717                         var importStatement = emittedImports_1[_i];
92718                         if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
92719                             var expr = importStatement.moduleReference.expression;
92720                             if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
92721                                 return undefined;
92722                             }
92723                         }
92724                         else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
92725                             return undefined;
92726                         }
92727                     }
92728                 }
92729                 return { fileName: typeName, pos: -1, end: -1 };
92730             }
92731             function mapReferencesIntoArray(references, outputFilePath) {
92732                 return function (file) {
92733                     var declFileName;
92734                     if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
92735                         declFileName = file.fileName;
92736                     }
92737                     else {
92738                         if (isBundledEmit && ts.contains(node.sourceFiles, file))
92739                             return; // Omit references to files which are being merged
92740                         var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
92741                         declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
92742                     }
92743                     if (declFileName) {
92744                         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, 
92745                         /*preferences*/ undefined);
92746                         if (!ts.pathIsRelative(specifier)) {
92747                             // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
92748                             // via a non-relative name, emit a type reference directive to that non-relative name, rather than
92749                             // a relative path to the declaration file
92750                             recordTypeReferenceDirectivesIfNecessary([specifier]);
92751                             return;
92752                         }
92753                         var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
92754                         /*isAbsolutePathAnUrl*/ false);
92755                         if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
92756                             fileName = fileName.substring(2);
92757                         }
92758                         // omit references to files from node_modules (npm may disambiguate module
92759                         // references when installing this package, making the path is unreliable).
92760                         if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) {
92761                             return;
92762                         }
92763                         references.push({ pos: -1, end: -1, fileName: fileName });
92764                     }
92765                 };
92766             }
92767         }
92768         function collectReferences(sourceFile, ret) {
92769             if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
92770                 return ret;
92771             ts.forEach(sourceFile.referencedFiles, function (f) {
92772                 var elem = host.getSourceFileFromReference(sourceFile, f);
92773                 if (elem) {
92774                     ret.set("" + ts.getOriginalNodeId(elem), elem);
92775                 }
92776             });
92777             return ret;
92778         }
92779         function collectLibs(sourceFile, ret) {
92780             ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
92781                 var lib = host.getLibFileFromReference(ref);
92782                 if (lib) {
92783                     ret.set(ts.toFileNameLowerCase(ref.fileName), true);
92784                 }
92785             });
92786             return ret;
92787         }
92788         function filterBindingPatternInitializers(name) {
92789             if (name.kind === 75 /* Identifier */) {
92790                 return name;
92791             }
92792             else {
92793                 if (name.kind === 190 /* ArrayBindingPattern */) {
92794                     return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92795                 }
92796                 else {
92797                     return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92798                 }
92799             }
92800             function visitBindingElement(elem) {
92801                 if (elem.kind === 215 /* OmittedExpression */) {
92802                     return elem;
92803                 }
92804                 return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
92805             }
92806         }
92807         function ensureParameter(p, modifierMask, type) {
92808             var oldDiag;
92809             if (!suppressNewDiagnosticContexts) {
92810                 oldDiag = getSymbolAccessibilityDiagnostic;
92811                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
92812             }
92813             var newParam = ts.updateParameter(p, 
92814             /*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
92815             ensureNoInitializer(p));
92816             if (!suppressNewDiagnosticContexts) {
92817                 getSymbolAccessibilityDiagnostic = oldDiag;
92818             }
92819             return newParam;
92820         }
92821         function shouldPrintWithInitializer(node) {
92822             return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
92823         }
92824         function ensureNoInitializer(node) {
92825             if (shouldPrintWithInitializer(node)) {
92826                 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
92827             }
92828             return undefined;
92829         }
92830         function ensureType(node, type, ignorePrivate) {
92831             if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) {
92832                 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
92833                 return;
92834             }
92835             if (shouldPrintWithInitializer(node)) {
92836                 // Literal const declarations will have an initializer ensured rather than a type
92837                 return;
92838             }
92839             var shouldUseResolverType = node.kind === 156 /* Parameter */ &&
92840                 (resolver.isRequiredInitializedParameter(node) ||
92841                     resolver.isOptionalUninitializedParameterProperty(node));
92842             if (type && !shouldUseResolverType) {
92843                 return ts.visitNode(type, visitDeclarationSubtree);
92844             }
92845             if (!ts.getParseTreeNode(node)) {
92846                 return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
92847             }
92848             if (node.kind === 164 /* SetAccessor */) {
92849                 // 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
92850                 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
92851                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
92852             }
92853             errorNameNode = node.name;
92854             var oldDiag;
92855             if (!suppressNewDiagnosticContexts) {
92856                 oldDiag = getSymbolAccessibilityDiagnostic;
92857                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
92858             }
92859             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
92860                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92861             }
92862             if (node.kind === 156 /* Parameter */
92863                 || node.kind === 159 /* PropertyDeclaration */
92864                 || node.kind === 158 /* PropertySignature */) {
92865                 if (!node.initializer)
92866                     return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
92867                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92868             }
92869             return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92870             function cleanup(returnValue) {
92871                 errorNameNode = undefined;
92872                 if (!suppressNewDiagnosticContexts) {
92873                     getSymbolAccessibilityDiagnostic = oldDiag;
92874                 }
92875                 return returnValue || ts.createKeywordTypeNode(125 /* AnyKeyword */);
92876             }
92877         }
92878         function isDeclarationAndNotVisible(node) {
92879             node = ts.getParseTreeNode(node);
92880             switch (node.kind) {
92881                 case 244 /* FunctionDeclaration */:
92882                 case 249 /* ModuleDeclaration */:
92883                 case 246 /* InterfaceDeclaration */:
92884                 case 245 /* ClassDeclaration */:
92885                 case 247 /* TypeAliasDeclaration */:
92886                 case 248 /* EnumDeclaration */:
92887                     return !resolver.isDeclarationVisible(node);
92888                 // The following should be doing their own visibility checks based on filtering their members
92889                 case 242 /* VariableDeclaration */:
92890                     return !getBindingNameVisible(node);
92891                 case 253 /* ImportEqualsDeclaration */:
92892                 case 254 /* ImportDeclaration */:
92893                 case 260 /* ExportDeclaration */:
92894                 case 259 /* ExportAssignment */:
92895                     return false;
92896             }
92897             return false;
92898         }
92899         function getBindingNameVisible(elem) {
92900             if (ts.isOmittedExpression(elem)) {
92901                 return false;
92902             }
92903             if (ts.isBindingPattern(elem.name)) {
92904                 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
92905                 return ts.some(elem.name.elements, getBindingNameVisible);
92906             }
92907             else {
92908                 return resolver.isDeclarationVisible(elem);
92909             }
92910         }
92911         function updateParamsList(node, params, modifierMask) {
92912             if (ts.hasModifier(node, 8 /* Private */)) {
92913                 return undefined; // TODO: GH#18217
92914             }
92915             var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
92916             if (!newParams) {
92917                 return undefined; // TODO: GH#18217
92918             }
92919             return ts.createNodeArray(newParams, params.hasTrailingComma);
92920         }
92921         function updateAccessorParamsList(input, isPrivate) {
92922             var newParams;
92923             if (!isPrivate) {
92924                 var thisParameter = ts.getThisParameter(input);
92925                 if (thisParameter) {
92926                     newParams = [ensureParameter(thisParameter)];
92927                 }
92928             }
92929             if (ts.isSetAccessorDeclaration(input)) {
92930                 var newValueParameter = void 0;
92931                 if (!isPrivate) {
92932                     var valueParameter = ts.getSetAccessorValueParameter(input);
92933                     if (valueParameter) {
92934                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
92935                         newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
92936                     }
92937                 }
92938                 if (!newValueParameter) {
92939                     newValueParameter = ts.createParameter(
92940                     /*decorators*/ undefined, 
92941                     /*modifiers*/ undefined, 
92942                     /*dotDotDotToken*/ undefined, "value");
92943                 }
92944                 newParams = ts.append(newParams, newValueParameter);
92945             }
92946             return ts.createNodeArray(newParams || ts.emptyArray);
92947         }
92948         function ensureTypeParams(node, params) {
92949             return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
92950         }
92951         function isEnclosingDeclaration(node) {
92952             return ts.isSourceFile(node)
92953                 || ts.isTypeAliasDeclaration(node)
92954                 || ts.isModuleDeclaration(node)
92955                 || ts.isClassDeclaration(node)
92956                 || ts.isInterfaceDeclaration(node)
92957                 || ts.isFunctionLike(node)
92958                 || ts.isIndexSignatureDeclaration(node)
92959                 || ts.isMappedTypeNode(node);
92960         }
92961         function checkEntityNameVisibility(entityName, enclosingDeclaration) {
92962             var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
92963             handleSymbolAccessibilityError(visibilityResult);
92964             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
92965         }
92966         function preserveJsDoc(updated, original) {
92967             if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
92968                 updated.jsDoc = original.jsDoc;
92969             }
92970             return ts.setCommentRange(updated, ts.getCommentRange(original));
92971         }
92972         function rewriteModuleSpecifier(parent, input) {
92973             if (!input)
92974                 return undefined; // TODO: GH#18217
92975             resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 249 /* ModuleDeclaration */ && parent.kind !== 188 /* ImportType */);
92976             if (ts.isStringLiteralLike(input)) {
92977                 if (isBundledEmit) {
92978                     var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
92979                     if (newName) {
92980                         return ts.createLiteral(newName);
92981                     }
92982                 }
92983                 else {
92984                     var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
92985                     if (symbol) {
92986                         (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
92987                     }
92988                 }
92989             }
92990             return input;
92991         }
92992         function transformImportEqualsDeclaration(decl) {
92993             if (!resolver.isDeclarationVisible(decl))
92994                 return;
92995             if (decl.moduleReference.kind === 265 /* ExternalModuleReference */) {
92996                 // Rewrite external module names if necessary
92997                 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
92998                 return ts.updateImportEqualsDeclaration(decl, 
92999                 /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
93000             }
93001             else {
93002                 var oldDiag = getSymbolAccessibilityDiagnostic;
93003                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
93004                 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
93005                 getSymbolAccessibilityDiagnostic = oldDiag;
93006                 return decl;
93007             }
93008         }
93009         function transformImportDeclaration(decl) {
93010             if (!decl.importClause) {
93011                 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
93012                 return ts.updateImportDeclaration(decl, 
93013                 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93014             }
93015             // The `importClause` visibility corresponds to the default's visibility.
93016             var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
93017             if (!decl.importClause.namedBindings) {
93018                 // No named bindings (either namespace or list), meaning the import is just default or should be elided
93019                 return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, 
93020                 /*namedBindings*/ undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93021             }
93022             if (decl.importClause.namedBindings.kind === 256 /* NamespaceImport */) {
93023                 // Namespace import (optionally with visible default)
93024                 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
93025                 return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
93026             }
93027             // Named imports (optionally with visible default)
93028             var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
93029             if ((bindingList && bindingList.length) || visibleDefaultBinding) {
93030                 return ts.updateImportDeclaration(decl, 
93031                 /*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));
93032             }
93033             // Augmentation of export depends on import
93034             if (resolver.isImportRequiredByAugmentation(decl)) {
93035                 return ts.updateImportDeclaration(decl, 
93036                 /*decorators*/ undefined, decl.modifiers, 
93037                 /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93038             }
93039             // Nothing visible
93040         }
93041         function transformAndReplaceLatePaintedStatements(statements) {
93042             // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
93043             // error handling which must now be included in the output and themselves checked for errors.
93044             // For example:
93045             // ```
93046             // module A {
93047             //   export module Q {}
93048             //   import B = Q;
93049             //   import C = B;
93050             //   export import D = C;
93051             // }
93052             // ```
93053             // 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
93054             // 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
93055             // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
93056             while (ts.length(lateMarkedStatements)) {
93057                 var i = lateMarkedStatements.shift();
93058                 if (!ts.isLateVisibilityPaintedStatement(i)) {
93059                     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));
93060                 }
93061                 var priorNeedsDeclare = needsDeclare;
93062                 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
93063                 var result = transformTopLevelDeclaration(i);
93064                 needsDeclare = priorNeedsDeclare;
93065                 lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
93066             }
93067             // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
93068             // (and remove them from the set to examine for outter declarations)
93069             return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
93070             function visitLateVisibilityMarkedStatements(statement) {
93071                 if (ts.isLateVisibilityPaintedStatement(statement)) {
93072                     var key = "" + ts.getOriginalNodeId(statement);
93073                     if (lateStatementReplacementMap.has(key)) {
93074                         var result = lateStatementReplacementMap.get(key);
93075                         lateStatementReplacementMap.delete(key);
93076                         if (result) {
93077                             if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
93078                                 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
93079                                 needsScopeFixMarker = true;
93080                             }
93081                             if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
93082                                 resultHasExternalModuleIndicator = true;
93083                             }
93084                         }
93085                         return result;
93086                     }
93087                 }
93088                 return statement;
93089             }
93090         }
93091         function visitDeclarationSubtree(input) {
93092             if (shouldStripInternal(input))
93093                 return;
93094             if (ts.isDeclaration(input)) {
93095                 if (isDeclarationAndNotVisible(input))
93096                     return;
93097                 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
93098                     return;
93099                 }
93100             }
93101             // Elide implementation signatures from overload sets
93102             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93103                 return;
93104             // Elide semicolon class statements
93105             if (ts.isSemicolonClassElement(input))
93106                 return;
93107             var previousEnclosingDeclaration;
93108             if (isEnclosingDeclaration(input)) {
93109                 previousEnclosingDeclaration = enclosingDeclaration;
93110                 enclosingDeclaration = input;
93111             }
93112             var oldDiag = getSymbolAccessibilityDiagnostic;
93113             // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
93114             // We'd see a TDZ violation at runtime
93115             var canProduceDiagnostic = ts.canProduceDiagnostics(input);
93116             var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
93117             var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 173 /* TypeLiteral */ || input.kind === 186 /* MappedType */) && input.parent.kind !== 247 /* TypeAliasDeclaration */);
93118             // Emit methods which are private as properties with no type information
93119             if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
93120                 if (ts.hasModifier(input, 8 /* Private */)) {
93121                     if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
93122                         return; // Elide all but the first overload
93123                     return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
93124                 }
93125             }
93126             if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93127                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93128             }
93129             if (ts.isTypeQueryNode(input)) {
93130                 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
93131             }
93132             if (shouldEnterSuppressNewDiagnosticsContextContext) {
93133                 // 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.
93134                 suppressNewDiagnosticContexts = true;
93135             }
93136             if (isProcessedComponent(input)) {
93137                 switch (input.kind) {
93138                     case 216 /* ExpressionWithTypeArguments */: {
93139                         if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
93140                             checkEntityNameVisibility(input.expression, enclosingDeclaration);
93141                         }
93142                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93143                         return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression));
93144                     }
93145                     case 169 /* TypeReference */: {
93146                         checkEntityNameVisibility(input.typeName, enclosingDeclaration);
93147                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93148                         return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments)));
93149                     }
93150                     case 166 /* ConstructSignature */:
93151                         return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93152                     case 162 /* Constructor */: {
93153                         // A constructor declaration may not have a type annotation
93154                         var ctor = ts.createSignatureDeclaration(162 /* Constructor */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters, 0 /* None */), 
93155                         /*type*/ undefined);
93156                         ctor.modifiers = ts.createNodeArray(ensureModifiers(input));
93157                         return cleanup(ctor);
93158                     }
93159                     case 161 /* MethodDeclaration */: {
93160                         if (ts.isPrivateIdentifier(input.name)) {
93161                             return cleanup(/*returnValue*/ undefined);
93162                         }
93163                         var sig = ts.createSignatureDeclaration(160 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type));
93164                         sig.name = input.name;
93165                         sig.modifiers = ts.createNodeArray(ensureModifiers(input));
93166                         sig.questionToken = input.questionToken;
93167                         return cleanup(sig);
93168                     }
93169                     case 163 /* GetAccessor */: {
93170                         if (ts.isPrivateIdentifier(input.name)) {
93171                             return cleanup(/*returnValue*/ undefined);
93172                         }
93173                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
93174                         return cleanup(ts.updateGetAccessor(input, 
93175                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), ensureType(input, accessorType), 
93176                         /*body*/ undefined));
93177                     }
93178                     case 164 /* SetAccessor */: {
93179                         if (ts.isPrivateIdentifier(input.name)) {
93180                             return cleanup(/*returnValue*/ undefined);
93181                         }
93182                         return cleanup(ts.updateSetAccessor(input, 
93183                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), 
93184                         /*body*/ undefined));
93185                     }
93186                     case 159 /* PropertyDeclaration */:
93187                         if (ts.isPrivateIdentifier(input.name)) {
93188                             return cleanup(/*returnValue*/ undefined);
93189                         }
93190                         return cleanup(ts.updateProperty(input, 
93191                         /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93192                     case 158 /* PropertySignature */:
93193                         if (ts.isPrivateIdentifier(input.name)) {
93194                             return cleanup(/*returnValue*/ undefined);
93195                         }
93196                         return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93197                     case 160 /* MethodSignature */: {
93198                         if (ts.isPrivateIdentifier(input.name)) {
93199                             return cleanup(/*returnValue*/ undefined);
93200                         }
93201                         return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken));
93202                     }
93203                     case 165 /* CallSignature */: {
93204                         return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93205                     }
93206                     case 167 /* IndexSignature */: {
93207                         return cleanup(ts.updateIndexSignature(input, 
93208                         /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(125 /* AnyKeyword */)));
93209                     }
93210                     case 242 /* VariableDeclaration */: {
93211                         if (ts.isBindingPattern(input.name)) {
93212                             return recreateBindingPattern(input.name);
93213                         }
93214                         shouldEnterSuppressNewDiagnosticsContextContext = true;
93215                         suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
93216                         return cleanup(ts.updateTypeScriptVariableDeclaration(input, input.name, /*exclaimationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
93217                     }
93218                     case 155 /* TypeParameter */: {
93219                         if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
93220                             return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
93221                         }
93222                         return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93223                     }
93224                     case 180 /* ConditionalType */: {
93225                         // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
93226                         // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
93227                         var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
93228                         var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
93229                         var oldEnclosingDecl = enclosingDeclaration;
93230                         enclosingDeclaration = input.trueType;
93231                         var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
93232                         enclosingDeclaration = oldEnclosingDecl;
93233                         var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
93234                         return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
93235                     }
93236                     case 170 /* FunctionType */: {
93237                         return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93238                     }
93239                     case 171 /* ConstructorType */: {
93240                         return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93241                     }
93242                     case 188 /* ImportType */: {
93243                         if (!ts.isLiteralImportTypeNode(input))
93244                             return cleanup(input);
93245                         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));
93246                     }
93247                     default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
93248                 }
93249             }
93250             return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93251             function cleanup(returnValue) {
93252                 if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
93253                     checkName(input);
93254                 }
93255                 if (isEnclosingDeclaration(input)) {
93256                     enclosingDeclaration = previousEnclosingDeclaration;
93257                 }
93258                 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93259                     getSymbolAccessibilityDiagnostic = oldDiag;
93260                 }
93261                 if (shouldEnterSuppressNewDiagnosticsContextContext) {
93262                     suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
93263                 }
93264                 if (returnValue === input) {
93265                     return returnValue;
93266                 }
93267                 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
93268             }
93269         }
93270         function isPrivateMethodTypeParameter(node) {
93271             return node.parent.kind === 161 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */);
93272         }
93273         function visitDeclarationStatements(input) {
93274             if (!isPreservedDeclarationStatement(input)) {
93275                 // return undefined for unmatched kinds to omit them from the tree
93276                 return;
93277             }
93278             if (shouldStripInternal(input))
93279                 return;
93280             switch (input.kind) {
93281                 case 260 /* ExportDeclaration */: {
93282                     if (ts.isSourceFile(input.parent)) {
93283                         resultHasExternalModuleIndicator = true;
93284                     }
93285                     resultHasScopeMarker = true;
93286                     // Always visible if the parent node isn't dropped for being not visible
93287                     // Rewrite external module names if necessary
93288                     return ts.updateExportDeclaration(input, 
93289                     /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), input.isTypeOnly);
93290                 }
93291                 case 259 /* ExportAssignment */: {
93292                     // Always visible if the parent node isn't dropped for being not visible
93293                     if (ts.isSourceFile(input.parent)) {
93294                         resultHasExternalModuleIndicator = true;
93295                     }
93296                     resultHasScopeMarker = true;
93297                     if (input.expression.kind === 75 /* Identifier */) {
93298                         return input;
93299                     }
93300                     else {
93301                         var newId = ts.createOptimisticUniqueName("_default");
93302                         getSymbolAccessibilityDiagnostic = function () { return ({
93303                             diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
93304                             errorNode: input
93305                         }); };
93306                         var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93307                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93308                         return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
93309                     }
93310                 }
93311             }
93312             var result = transformTopLevelDeclaration(input);
93313             // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
93314             lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
93315             return input;
93316         }
93317         function stripExportModifiers(statement) {
93318             if (ts.isImportEqualsDeclaration(statement) || ts.hasModifier(statement, 512 /* Default */)) {
93319                 // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
93320                 // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
93321                 return statement;
93322             }
93323             var clone = ts.getMutableClone(statement);
93324             var modifiers = ts.createModifiersFromModifierFlags(ts.getModifierFlags(statement) & (3071 /* All */ ^ 1 /* Export */));
93325             clone.modifiers = modifiers.length ? ts.createNodeArray(modifiers) : undefined;
93326             return clone;
93327         }
93328         function transformTopLevelDeclaration(input) {
93329             if (shouldStripInternal(input))
93330                 return;
93331             switch (input.kind) {
93332                 case 253 /* ImportEqualsDeclaration */: {
93333                     return transformImportEqualsDeclaration(input);
93334                 }
93335                 case 254 /* ImportDeclaration */: {
93336                     return transformImportDeclaration(input);
93337                 }
93338             }
93339             if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
93340                 return;
93341             // Elide implementation signatures from overload sets
93342             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93343                 return;
93344             var previousEnclosingDeclaration;
93345             if (isEnclosingDeclaration(input)) {
93346                 previousEnclosingDeclaration = enclosingDeclaration;
93347                 enclosingDeclaration = input;
93348             }
93349             var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
93350             var oldDiag = getSymbolAccessibilityDiagnostic;
93351             if (canProdiceDiagnostic) {
93352                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93353             }
93354             var previousNeedsDeclare = needsDeclare;
93355             switch (input.kind) {
93356                 case 247 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
93357                     return cleanup(ts.updateTypeAliasDeclaration(input, 
93358                     /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
93359                 case 246 /* InterfaceDeclaration */: {
93360                     return cleanup(ts.updateInterfaceDeclaration(input, 
93361                     /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
93362                 }
93363                 case 244 /* FunctionDeclaration */: {
93364                     // Generators lose their generator-ness, excepting their return type
93365                     var clean = cleanup(ts.updateFunctionDeclaration(input, 
93366                     /*decorators*/ undefined, ensureModifiers(input), 
93367                     /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
93368                     /*body*/ undefined));
93369                     if (clean && resolver.isExpandoFunctionDeclaration(input)) {
93370                         var props = resolver.getPropertiesOfContainerFunction(input);
93371                         var fakespace_1 = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || ts.createIdentifier("_default"), ts.createModuleBlock([]), 16 /* Namespace */);
93372                         fakespace_1.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
93373                         fakespace_1.parent = enclosingDeclaration;
93374                         fakespace_1.locals = ts.createSymbolTable(props);
93375                         fakespace_1.symbol = props[0].parent;
93376                         var declarations = ts.mapDefined(props, function (p) {
93377                             if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
93378                                 return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
93379                             }
93380                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
93381                             var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
93382                             getSymbolAccessibilityDiagnostic = oldDiag;
93383                             var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
93384                             return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
93385                         });
93386                         var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */);
93387                         if (!ts.hasModifier(clean, 512 /* Default */)) {
93388                             return [clean, namespaceDecl];
93389                         }
93390                         var modifiers = ts.createModifiersFromModifierFlags((ts.getModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
93391                         var cleanDeclaration = ts.updateFunctionDeclaration(clean, 
93392                         /*decorators*/ undefined, modifiers, 
93393                         /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, 
93394                         /*body*/ undefined);
93395                         var namespaceDeclaration = ts.updateModuleDeclaration(namespaceDecl, 
93396                         /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
93397                         var exportDefaultDeclaration = ts.createExportAssignment(
93398                         /*decorators*/ undefined, 
93399                         /*modifiers*/ undefined, 
93400                         /*isExportEquals*/ false, namespaceDecl.name);
93401                         if (ts.isSourceFile(input.parent)) {
93402                             resultHasExternalModuleIndicator = true;
93403                         }
93404                         resultHasScopeMarker = true;
93405                         return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
93406                     }
93407                     else {
93408                         return clean;
93409                     }
93410                 }
93411                 case 249 /* ModuleDeclaration */: {
93412                     needsDeclare = false;
93413                     var inner = input.body;
93414                     if (inner && inner.kind === 250 /* ModuleBlock */) {
93415                         var oldNeedsScopeFix = needsScopeFixMarker;
93416                         var oldHasScopeFix = resultHasScopeMarker;
93417                         resultHasScopeMarker = false;
93418                         needsScopeFixMarker = false;
93419                         var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
93420                         var lateStatements = transformAndReplaceLatePaintedStatements(statements);
93421                         if (input.flags & 8388608 /* Ambient */) {
93422                             needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
93423                         }
93424                         // With the final list of statements, there are 3 possibilities:
93425                         // 1. There's an export assignment or export declaration in the namespace - do nothing
93426                         // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
93427                         // 3. Some things are exported, some are not, and there's no marker - add an empty marker
93428                         if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
93429                             if (needsScopeFixMarker) {
93430                                 lateStatements = ts.createNodeArray(__spreadArrays(lateStatements, [ts.createEmptyExports()]));
93431                             }
93432                             else {
93433                                 lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
93434                             }
93435                         }
93436                         var body = ts.updateModuleBlock(inner, lateStatements);
93437                         needsDeclare = previousNeedsDeclare;
93438                         needsScopeFixMarker = oldNeedsScopeFix;
93439                         resultHasScopeMarker = oldHasScopeFix;
93440                         var mods = ensureModifiers(input);
93441                         return cleanup(ts.updateModuleDeclaration(input, 
93442                         /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
93443                     }
93444                     else {
93445                         needsDeclare = previousNeedsDeclare;
93446                         var mods = ensureModifiers(input);
93447                         needsDeclare = false;
93448                         ts.visitNode(inner, visitDeclarationStatements);
93449                         // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
93450                         var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217
93451                         var body = lateStatementReplacementMap.get(id);
93452                         lateStatementReplacementMap.delete(id);
93453                         return cleanup(ts.updateModuleDeclaration(input, 
93454                         /*decorators*/ undefined, mods, input.name, body));
93455                     }
93456                 }
93457                 case 245 /* ClassDeclaration */: {
93458                     var modifiers = ts.createNodeArray(ensureModifiers(input));
93459                     var typeParameters = ensureTypeParams(input, input.typeParameters);
93460                     var ctor = ts.getFirstConstructorWithBody(input);
93461                     var parameterProperties = void 0;
93462                     if (ctor) {
93463                         var oldDiag_1 = getSymbolAccessibilityDiagnostic;
93464                         parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
93465                             if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
93466                                 return;
93467                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
93468                             if (param.name.kind === 75 /* Identifier */) {
93469                                 return preserveJsDoc(ts.createProperty(
93470                                 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
93471                             }
93472                             else {
93473                                 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
93474                                 return walkBindingPattern(param.name);
93475                             }
93476                             function walkBindingPattern(pattern) {
93477                                 var elems;
93478                                 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
93479                                     var elem = _a[_i];
93480                                     if (ts.isOmittedExpression(elem))
93481                                         continue;
93482                                     if (ts.isBindingPattern(elem.name)) {
93483                                         elems = ts.concatenate(elems, walkBindingPattern(elem.name));
93484                                     }
93485                                     elems = elems || [];
93486                                     elems.push(ts.createProperty(
93487                                     /*decorators*/ undefined, ensureModifiers(param), elem.name, 
93488                                     /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), 
93489                                     /*initializer*/ undefined));
93490                                 }
93491                                 return elems;
93492                             }
93493                         }));
93494                         getSymbolAccessibilityDiagnostic = oldDiag_1;
93495                     }
93496                     var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
93497                     var privateIdentifier = hasPrivateIdentifier ? [
93498                         ts.createProperty(
93499                         /*decorators*/ undefined, 
93500                         /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
93501                         /*questionToken*/ undefined, 
93502                         /*type*/ undefined, 
93503                         /*initializer*/ undefined)
93504                     ] : undefined;
93505                     var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
93506                     var members = ts.createNodeArray(memberNodes);
93507                     var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
93508                     if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 100 /* NullKeyword */) {
93509                         // We must add a temporary declaration for the extends clause expression
93510                         var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
93511                         var newId_1 = ts.createOptimisticUniqueName(oldId + "_base");
93512                         getSymbolAccessibilityDiagnostic = function () { return ({
93513                             diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
93514                             errorNode: extendsClause_1,
93515                             typeName: input.name
93516                         }); };
93517                         var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93518                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93519                         var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) {
93520                             if (clause.token === 90 /* ExtendsKeyword */) {
93521                                 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
93522                                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
93523                                 var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); }));
93524                                 getSymbolAccessibilityDiagnostic = oldDiag_2;
93525                                 return newClause;
93526                             }
93527                             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));
93528                         }));
93529                         return [statement, cleanup(ts.updateClassDeclaration(input, 
93530                             /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
93531                     }
93532                     else {
93533                         var heritageClauses = transformHeritageClauses(input.heritageClauses);
93534                         return cleanup(ts.updateClassDeclaration(input, 
93535                         /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
93536                     }
93537                 }
93538                 case 225 /* VariableStatement */: {
93539                     return cleanup(transformVariableStatement(input));
93540                 }
93541                 case 248 /* EnumDeclaration */: {
93542                     return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
93543                         if (shouldStripInternal(m))
93544                             return;
93545                         // Rewrite enum values to their constants, if available
93546                         var constValue = resolver.getConstantValue(m);
93547                         return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m);
93548                     }))));
93549                 }
93550             }
93551             // Anything left unhandled is an error, so this should be unreachable
93552             return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
93553             function cleanup(node) {
93554                 if (isEnclosingDeclaration(input)) {
93555                     enclosingDeclaration = previousEnclosingDeclaration;
93556                 }
93557                 if (canProdiceDiagnostic) {
93558                     getSymbolAccessibilityDiagnostic = oldDiag;
93559                 }
93560                 if (input.kind === 249 /* ModuleDeclaration */) {
93561                     needsDeclare = previousNeedsDeclare;
93562                 }
93563                 if (node === input) {
93564                     return node;
93565                 }
93566                 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
93567             }
93568         }
93569         function transformVariableStatement(input) {
93570             if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
93571                 return;
93572             var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
93573             if (!ts.length(nodes))
93574                 return;
93575             return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes));
93576         }
93577         function recreateBindingPattern(d) {
93578             return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
93579         }
93580         function recreateBindingElement(e) {
93581             if (e.kind === 215 /* OmittedExpression */) {
93582                 return;
93583             }
93584             if (e.name) {
93585                 if (!getBindingNameVisible(e))
93586                     return;
93587                 if (ts.isBindingPattern(e.name)) {
93588                     return recreateBindingPattern(e.name);
93589                 }
93590                 else {
93591                     return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
93592                 }
93593             }
93594         }
93595         function checkName(node) {
93596             var oldDiag;
93597             if (!suppressNewDiagnosticContexts) {
93598                 oldDiag = getSymbolAccessibilityDiagnostic;
93599                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
93600             }
93601             errorNameNode = node.name;
93602             ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
93603             var decl = node;
93604             var entityName = decl.name.expression;
93605             checkEntityNameVisibility(entityName, enclosingDeclaration);
93606             if (!suppressNewDiagnosticContexts) {
93607                 getSymbolAccessibilityDiagnostic = oldDiag;
93608             }
93609             errorNameNode = undefined;
93610         }
93611         function shouldStripInternal(node) {
93612             return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
93613         }
93614         function isScopeMarker(node) {
93615             return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
93616         }
93617         function hasScopeMarker(statements) {
93618             return ts.some(statements, isScopeMarker);
93619         }
93620         function ensureModifiers(node) {
93621             var currentFlags = ts.getModifierFlags(node);
93622             var newFlags = ensureModifierFlags(node);
93623             if (currentFlags === newFlags) {
93624                 return node.modifiers;
93625             }
93626             return ts.createModifiersFromModifierFlags(newFlags);
93627         }
93628         function ensureModifierFlags(node) {
93629             var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
93630             var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
93631             var parentIsFile = node.parent.kind === 290 /* SourceFile */;
93632             if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
93633                 mask ^= 2 /* Ambient */;
93634                 additions = 0 /* None */;
93635             }
93636             return maskModifierFlags(node, mask, additions);
93637         }
93638         function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
93639             var accessorType = getTypeAnnotationFromAccessor(node);
93640             if (!accessorType && node !== accessors.firstAccessor) {
93641                 accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
93642                 // 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
93643                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
93644             }
93645             if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
93646                 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
93647                 // 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
93648                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
93649             }
93650             return accessorType;
93651         }
93652         function transformHeritageClauses(nodes) {
93653             return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) {
93654                 return ts.isEntityNameExpression(t.expression) || (clause.token === 90 /* ExtendsKeyword */ && t.expression.kind === 100 /* NullKeyword */);
93655             })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
93656         }
93657     }
93658     ts.transformDeclarations = transformDeclarations;
93659     function isAlwaysType(node) {
93660         if (node.kind === 246 /* InterfaceDeclaration */) {
93661             return true;
93662         }
93663         return false;
93664     }
93665     // Elide "public" modifier, as it is the default
93666     function maskModifiers(node, modifierMask, modifierAdditions) {
93667         return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
93668     }
93669     function maskModifierFlags(node, modifierMask, modifierAdditions) {
93670         if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; }
93671         if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
93672         var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions;
93673         if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
93674             // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
93675             // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
93676             flags ^= 1 /* Export */;
93677         }
93678         if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
93679             flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
93680         }
93681         return flags;
93682     }
93683     function getTypeAnnotationFromAccessor(accessor) {
93684         if (accessor) {
93685             return accessor.kind === 163 /* GetAccessor */
93686                 ? accessor.type // Getter - return type
93687                 : accessor.parameters.length > 0
93688                     ? accessor.parameters[0].type // Setter parameter type
93689                     : undefined;
93690         }
93691     }
93692     function canHaveLiteralInitializer(node) {
93693         switch (node.kind) {
93694             case 159 /* PropertyDeclaration */:
93695             case 158 /* PropertySignature */:
93696                 return !ts.hasModifier(node, 8 /* Private */);
93697             case 156 /* Parameter */:
93698             case 242 /* VariableDeclaration */:
93699                 return true;
93700         }
93701         return false;
93702     }
93703     function isPreservedDeclarationStatement(node) {
93704         switch (node.kind) {
93705             case 244 /* FunctionDeclaration */:
93706             case 249 /* ModuleDeclaration */:
93707             case 253 /* ImportEqualsDeclaration */:
93708             case 246 /* InterfaceDeclaration */:
93709             case 245 /* ClassDeclaration */:
93710             case 247 /* TypeAliasDeclaration */:
93711             case 248 /* EnumDeclaration */:
93712             case 225 /* VariableStatement */:
93713             case 254 /* ImportDeclaration */:
93714             case 260 /* ExportDeclaration */:
93715             case 259 /* ExportAssignment */:
93716                 return true;
93717         }
93718         return false;
93719     }
93720     function isProcessedComponent(node) {
93721         switch (node.kind) {
93722             case 166 /* ConstructSignature */:
93723             case 162 /* Constructor */:
93724             case 161 /* MethodDeclaration */:
93725             case 163 /* GetAccessor */:
93726             case 164 /* SetAccessor */:
93727             case 159 /* PropertyDeclaration */:
93728             case 158 /* PropertySignature */:
93729             case 160 /* MethodSignature */:
93730             case 165 /* CallSignature */:
93731             case 167 /* IndexSignature */:
93732             case 242 /* VariableDeclaration */:
93733             case 155 /* TypeParameter */:
93734             case 216 /* ExpressionWithTypeArguments */:
93735             case 169 /* TypeReference */:
93736             case 180 /* ConditionalType */:
93737             case 170 /* FunctionType */:
93738             case 171 /* ConstructorType */:
93739             case 188 /* ImportType */:
93740                 return true;
93741         }
93742         return false;
93743     }
93744 })(ts || (ts = {}));
93745 /* @internal */
93746 var ts;
93747 (function (ts) {
93748     function getModuleTransformer(moduleKind) {
93749         switch (moduleKind) {
93750             case ts.ModuleKind.ESNext:
93751             case ts.ModuleKind.ES2020:
93752             case ts.ModuleKind.ES2015:
93753                 return ts.transformECMAScriptModule;
93754             case ts.ModuleKind.System:
93755                 return ts.transformSystemModule;
93756             default:
93757                 return ts.transformModule;
93758         }
93759     }
93760     var TransformationState;
93761     (function (TransformationState) {
93762         TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
93763         TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
93764         TransformationState[TransformationState["Completed"] = 2] = "Completed";
93765         TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
93766     })(TransformationState || (TransformationState = {}));
93767     var SyntaxKindFeatureFlags;
93768     (function (SyntaxKindFeatureFlags) {
93769         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
93770         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
93771     })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
93772     ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
93773     function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93774         return {
93775             scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
93776             declarationTransformers: getDeclarationTransformers(customTransformers),
93777         };
93778     }
93779     ts.getTransformers = getTransformers;
93780     function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93781         if (emitOnlyDtsFiles)
93782             return ts.emptyArray;
93783         var jsx = compilerOptions.jsx;
93784         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
93785         var moduleKind = ts.getEmitModuleKind(compilerOptions);
93786         var transformers = [];
93787         ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
93788         transformers.push(ts.transformTypeScript);
93789         transformers.push(ts.transformClassFields);
93790         if (jsx === 2 /* React */) {
93791             transformers.push(ts.transformJsx);
93792         }
93793         if (languageVersion < 99 /* ESNext */) {
93794             transformers.push(ts.transformESNext);
93795         }
93796         if (languageVersion < 7 /* ES2020 */) {
93797             transformers.push(ts.transformES2020);
93798         }
93799         if (languageVersion < 6 /* ES2019 */) {
93800             transformers.push(ts.transformES2019);
93801         }
93802         if (languageVersion < 5 /* ES2018 */) {
93803             transformers.push(ts.transformES2018);
93804         }
93805         if (languageVersion < 4 /* ES2017 */) {
93806             transformers.push(ts.transformES2017);
93807         }
93808         if (languageVersion < 3 /* ES2016 */) {
93809             transformers.push(ts.transformES2016);
93810         }
93811         if (languageVersion < 2 /* ES2015 */) {
93812             transformers.push(ts.transformES2015);
93813             transformers.push(ts.transformGenerators);
93814         }
93815         transformers.push(getModuleTransformer(moduleKind));
93816         // The ES5 transformer is last so that it can substitute expressions like `exports.default`
93817         // for ES3.
93818         if (languageVersion < 1 /* ES5 */) {
93819             transformers.push(ts.transformES5);
93820         }
93821         ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
93822         return transformers;
93823     }
93824     function getDeclarationTransformers(customTransformers) {
93825         var transformers = [];
93826         transformers.push(ts.transformDeclarations);
93827         ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
93828         return transformers;
93829     }
93830     /**
93831      * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
93832      */
93833     function wrapCustomTransformer(transformer) {
93834         return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
93835     }
93836     /**
93837      * Wrap a transformer factory that may return a custom script or declaration transformer object.
93838      */
93839     function wrapCustomTransformerFactory(transformer, handleDefault) {
93840         return function (context) {
93841             var customTransformer = transformer(context);
93842             return typeof customTransformer === "function"
93843                 ? handleDefault(customTransformer)
93844                 : wrapCustomTransformer(customTransformer);
93845         };
93846     }
93847     function wrapScriptTransformerFactory(transformer) {
93848         return wrapCustomTransformerFactory(transformer, ts.chainBundle);
93849     }
93850     function wrapDeclarationTransformerFactory(transformer) {
93851         return wrapCustomTransformerFactory(transformer, ts.identity);
93852     }
93853     function noEmitSubstitution(_hint, node) {
93854         return node;
93855     }
93856     ts.noEmitSubstitution = noEmitSubstitution;
93857     function noEmitNotification(hint, node, callback) {
93858         callback(hint, node);
93859     }
93860     ts.noEmitNotification = noEmitNotification;
93861     /**
93862      * Transforms an array of SourceFiles by passing them through each transformer.
93863      *
93864      * @param resolver The emit resolver provided by the checker.
93865      * @param host The emit host object used to interact with the file system.
93866      * @param options Compiler options to surface in the `TransformationContext`.
93867      * @param nodes An array of nodes to transform.
93868      * @param transforms An array of `TransformerFactory` callbacks.
93869      * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
93870      */
93871     function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
93872         var enabledSyntaxKindFeatures = new Array(331 /* Count */);
93873         var lexicalEnvironmentVariableDeclarations;
93874         var lexicalEnvironmentFunctionDeclarations;
93875         var lexicalEnvironmentStatements;
93876         var lexicalEnvironmentFlags = 0 /* None */;
93877         var lexicalEnvironmentVariableDeclarationsStack = [];
93878         var lexicalEnvironmentFunctionDeclarationsStack = [];
93879         var lexicalEnvironmentStatementsStack = [];
93880         var lexicalEnvironmentFlagsStack = [];
93881         var lexicalEnvironmentStackOffset = 0;
93882         var lexicalEnvironmentSuspended = false;
93883         var emitHelpers;
93884         var onSubstituteNode = noEmitSubstitution;
93885         var onEmitNode = noEmitNotification;
93886         var state = 0 /* Uninitialized */;
93887         var diagnostics = [];
93888         // The transformation context is provided to each transformer as part of transformer
93889         // initialization.
93890         var context = {
93891             getCompilerOptions: function () { return options; },
93892             getEmitResolver: function () { return resolver; },
93893             getEmitHost: function () { return host; },
93894             startLexicalEnvironment: startLexicalEnvironment,
93895             suspendLexicalEnvironment: suspendLexicalEnvironment,
93896             resumeLexicalEnvironment: resumeLexicalEnvironment,
93897             endLexicalEnvironment: endLexicalEnvironment,
93898             setLexicalEnvironmentFlags: setLexicalEnvironmentFlags,
93899             getLexicalEnvironmentFlags: getLexicalEnvironmentFlags,
93900             hoistVariableDeclaration: hoistVariableDeclaration,
93901             hoistFunctionDeclaration: hoistFunctionDeclaration,
93902             addInitializationStatement: addInitializationStatement,
93903             requestEmitHelper: requestEmitHelper,
93904             readEmitHelpers: readEmitHelpers,
93905             enableSubstitution: enableSubstitution,
93906             enableEmitNotification: enableEmitNotification,
93907             isSubstitutionEnabled: isSubstitutionEnabled,
93908             isEmitNotificationEnabled: isEmitNotificationEnabled,
93909             get onSubstituteNode() { return onSubstituteNode; },
93910             set onSubstituteNode(value) {
93911                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
93912                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
93913                 onSubstituteNode = value;
93914             },
93915             get onEmitNode() { return onEmitNode; },
93916             set onEmitNode(value) {
93917                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
93918                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
93919                 onEmitNode = value;
93920             },
93921             addDiagnostic: function (diag) {
93922                 diagnostics.push(diag);
93923             }
93924         };
93925         // Ensure the parse tree is clean before applying transformations
93926         for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
93927             var node = nodes_4[_i];
93928             ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
93929         }
93930         ts.performance.mark("beforeTransform");
93931         // Chain together and initialize each transformer.
93932         var transformersWithContext = transformers.map(function (t) { return t(context); });
93933         var transformation = function (node) {
93934             for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
93935                 var transform = transformersWithContext_1[_i];
93936                 node = transform(node);
93937             }
93938             return node;
93939         };
93940         // prevent modification of transformation hooks.
93941         state = 1 /* Initialized */;
93942         // Transform each node.
93943         var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot);
93944         // prevent modification of the lexical environment.
93945         state = 2 /* Completed */;
93946         ts.performance.mark("afterTransform");
93947         ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
93948         return {
93949             transformed: transformed,
93950             substituteNode: substituteNode,
93951             emitNodeWithNotification: emitNodeWithNotification,
93952             isEmitNotificationEnabled: isEmitNotificationEnabled,
93953             dispose: dispose,
93954             diagnostics: diagnostics
93955         };
93956         function transformRoot(node) {
93957             return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
93958         }
93959         /**
93960          * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
93961          */
93962         function enableSubstitution(kind) {
93963             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
93964             enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
93965         }
93966         /**
93967          * Determines whether expression substitutions are enabled for the provided node.
93968          */
93969         function isSubstitutionEnabled(node) {
93970             return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
93971                 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
93972         }
93973         /**
93974          * Emits a node with possible substitution.
93975          *
93976          * @param hint A hint as to the intended usage of the node.
93977          * @param node The node to emit.
93978          * @param emitCallback The callback used to emit the node or its substitute.
93979          */
93980         function substituteNode(hint, node) {
93981             ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
93982             return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
93983         }
93984         /**
93985          * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
93986          */
93987         function enableEmitNotification(kind) {
93988             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
93989             enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
93990         }
93991         /**
93992          * Determines whether before/after emit notifications should be raised in the pretty
93993          * printer when it emits a node.
93994          */
93995         function isEmitNotificationEnabled(node) {
93996             return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
93997                 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
93998         }
93999         /**
94000          * Emits a node with possible emit notification.
94001          *
94002          * @param hint A hint as to the intended usage of the node.
94003          * @param node The node to emit.
94004          * @param emitCallback The callback used to emit the node.
94005          */
94006         function emitNodeWithNotification(hint, node, emitCallback) {
94007             ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
94008             if (node) {
94009                 // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
94010                 // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
94011                 if (isEmitNotificationEnabled(node)) {
94012                     onEmitNode(hint, node, emitCallback);
94013                 }
94014                 else {
94015                     emitCallback(hint, node);
94016                 }
94017             }
94018         }
94019         /**
94020          * Records a hoisted variable declaration for the provided name within a lexical environment.
94021          */
94022         function hoistVariableDeclaration(name) {
94023             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94024             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94025             var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
94026             if (!lexicalEnvironmentVariableDeclarations) {
94027                 lexicalEnvironmentVariableDeclarations = [decl];
94028             }
94029             else {
94030                 lexicalEnvironmentVariableDeclarations.push(decl);
94031             }
94032             if (lexicalEnvironmentFlags & 1 /* InParameters */) {
94033                 lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
94034             }
94035         }
94036         /**
94037          * Records a hoisted function declaration within a lexical environment.
94038          */
94039         function hoistFunctionDeclaration(func) {
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.setEmitFlags(func, 1048576 /* CustomPrologue */);
94043             if (!lexicalEnvironmentFunctionDeclarations) {
94044                 lexicalEnvironmentFunctionDeclarations = [func];
94045             }
94046             else {
94047                 lexicalEnvironmentFunctionDeclarations.push(func);
94048             }
94049         }
94050         /**
94051          * Adds an initialization statement to the top of the lexical environment.
94052          */
94053         function addInitializationStatement(node) {
94054             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94055             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94056             ts.setEmitFlags(node, 1048576 /* CustomPrologue */);
94057             if (!lexicalEnvironmentStatements) {
94058                 lexicalEnvironmentStatements = [node];
94059             }
94060             else {
94061                 lexicalEnvironmentStatements.push(node);
94062             }
94063         }
94064         /**
94065          * Starts a new lexical environment. Any existing hoisted variable or function declarations
94066          * are pushed onto a stack, and the related storage variables are reset.
94067          */
94068         function startLexicalEnvironment() {
94069             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94070             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94071             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94072             // Save the current lexical environment. Rather than resizing the array we adjust the
94073             // stack size variable. This allows us to reuse existing array slots we've
94074             // already allocated between transformations to avoid allocation and GC overhead during
94075             // transformation.
94076             lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
94077             lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
94078             lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
94079             lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
94080             lexicalEnvironmentStackOffset++;
94081             lexicalEnvironmentVariableDeclarations = undefined;
94082             lexicalEnvironmentFunctionDeclarations = undefined;
94083             lexicalEnvironmentStatements = undefined;
94084             lexicalEnvironmentFlags = 0 /* None */;
94085         }
94086         /** Suspends the current lexical environment, usually after visiting a parameter list. */
94087         function suspendLexicalEnvironment() {
94088             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94089             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94090             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
94091             lexicalEnvironmentSuspended = true;
94092         }
94093         /** Resumes a suspended lexical environment, usually before visiting a function body. */
94094         function resumeLexicalEnvironment() {
94095             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94096             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94097             ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
94098             lexicalEnvironmentSuspended = false;
94099         }
94100         /**
94101          * Ends a lexical environment. The previous set of hoisted declarations are restored and
94102          * any hoisted declarations added in this environment are returned.
94103          */
94104         function endLexicalEnvironment() {
94105             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94106             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94107             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94108             var statements;
94109             if (lexicalEnvironmentVariableDeclarations ||
94110                 lexicalEnvironmentFunctionDeclarations ||
94111                 lexicalEnvironmentStatements) {
94112                 if (lexicalEnvironmentFunctionDeclarations) {
94113                     statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations);
94114                 }
94115                 if (lexicalEnvironmentVariableDeclarations) {
94116                     var statement = ts.createVariableStatement(
94117                     /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
94118                     ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
94119                     if (!statements) {
94120                         statements = [statement];
94121                     }
94122                     else {
94123                         statements.push(statement);
94124                     }
94125                 }
94126                 if (lexicalEnvironmentStatements) {
94127                     if (!statements) {
94128                         statements = __spreadArrays(lexicalEnvironmentStatements);
94129                     }
94130                     else {
94131                         statements = __spreadArrays(statements, lexicalEnvironmentStatements);
94132                     }
94133                 }
94134             }
94135             // Restore the previous lexical environment.
94136             lexicalEnvironmentStackOffset--;
94137             lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
94138             lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
94139             lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
94140             lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
94141             if (lexicalEnvironmentStackOffset === 0) {
94142                 lexicalEnvironmentVariableDeclarationsStack = [];
94143                 lexicalEnvironmentFunctionDeclarationsStack = [];
94144                 lexicalEnvironmentStatementsStack = [];
94145                 lexicalEnvironmentFlagsStack = [];
94146             }
94147             return statements;
94148         }
94149         function setLexicalEnvironmentFlags(flags, value) {
94150             lexicalEnvironmentFlags = value ?
94151                 lexicalEnvironmentFlags | flags :
94152                 lexicalEnvironmentFlags & ~flags;
94153         }
94154         function getLexicalEnvironmentFlags() {
94155             return lexicalEnvironmentFlags;
94156         }
94157         function requestEmitHelper(helper) {
94158             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94159             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94160             ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
94161             if (helper.dependencies) {
94162                 for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) {
94163                     var h = _a[_i];
94164                     requestEmitHelper(h);
94165                 }
94166             }
94167             emitHelpers = ts.append(emitHelpers, helper);
94168         }
94169         function readEmitHelpers() {
94170             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94171             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94172             var helpers = emitHelpers;
94173             emitHelpers = undefined;
94174             return helpers;
94175         }
94176         function dispose() {
94177             if (state < 3 /* Disposed */) {
94178                 // Clean up emit nodes on parse tree
94179                 for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
94180                     var node = nodes_5[_i];
94181                     ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
94182                 }
94183                 // Release references to external entries for GC purposes.
94184                 lexicalEnvironmentVariableDeclarations = undefined;
94185                 lexicalEnvironmentVariableDeclarationsStack = undefined;
94186                 lexicalEnvironmentFunctionDeclarations = undefined;
94187                 lexicalEnvironmentFunctionDeclarationsStack = undefined;
94188                 onSubstituteNode = undefined;
94189                 onEmitNode = undefined;
94190                 emitHelpers = undefined;
94191                 // Prevent further use of the transformation result.
94192                 state = 3 /* Disposed */;
94193             }
94194         }
94195     }
94196     ts.transformNodes = transformNodes;
94197 })(ts || (ts = {}));
94198 var ts;
94199 (function (ts) {
94200     var brackets = createBracketsMap();
94201     var syntheticParent = { pos: -1, end: -1 };
94202     /*@internal*/
94203     function isBuildInfoFile(file) {
94204         return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
94205     }
94206     ts.isBuildInfoFile = isBuildInfoFile;
94207     /*@internal*/
94208     /**
94209      * Iterates over the source files that are expected to have an emit output.
94210      *
94211      * @param host An EmitHost.
94212      * @param action The action to execute.
94213      * @param sourceFilesOrTargetSourceFile
94214      *   If an array, the full list of source files to emit.
94215      *   Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
94216      */
94217     function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
94218         if (forceDtsEmit === void 0) { forceDtsEmit = false; }
94219         var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
94220         var options = host.getCompilerOptions();
94221         if (options.outFile || options.out) {
94222             var prepends = host.getPrependNodes();
94223             if (sourceFiles.length || prepends.length) {
94224                 var bundle = ts.createBundle(sourceFiles, prepends);
94225                 var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
94226                 if (result) {
94227                     return result;
94228                 }
94229             }
94230         }
94231         else {
94232             if (!onlyBuildInfo) {
94233                 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
94234                     var sourceFile = sourceFiles_1[_a];
94235                     var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
94236                     if (result) {
94237                         return result;
94238                     }
94239                 }
94240             }
94241             if (includeBuildInfo) {
94242                 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(host.getCompilerOptions());
94243                 if (buildInfoPath)
94244                     return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
94245             }
94246         }
94247     }
94248     ts.forEachEmittedFile = forEachEmittedFile;
94249     function getTsBuildInfoEmitOutputFilePath(options) {
94250         var configFile = options.configFilePath;
94251         if (!ts.isIncrementalCompilation(options))
94252             return undefined;
94253         if (options.tsBuildInfoFile)
94254             return options.tsBuildInfoFile;
94255         var outPath = options.outFile || options.out;
94256         var buildInfoExtensionLess;
94257         if (outPath) {
94258             buildInfoExtensionLess = ts.removeFileExtension(outPath);
94259         }
94260         else {
94261             if (!configFile)
94262                 return undefined;
94263             var configFileExtensionLess = ts.removeFileExtension(configFile);
94264             buildInfoExtensionLess = options.outDir ?
94265                 options.rootDir ?
94266                     ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
94267                     ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
94268                 configFileExtensionLess;
94269         }
94270         return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
94271     }
94272     ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
94273     /*@internal*/
94274     function getOutputPathsForBundle(options, forceDtsPaths) {
94275         var outPath = options.outFile || options.out;
94276         var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
94277         var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
94278         var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
94279         var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94280         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
94281         return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
94282     }
94283     ts.getOutputPathsForBundle = getOutputPathsForBundle;
94284     /*@internal*/
94285     function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
94286         var options = host.getCompilerOptions();
94287         if (sourceFile.kind === 291 /* Bundle */) {
94288             return getOutputPathsForBundle(options, forceDtsPaths);
94289         }
94290         else {
94291             var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
94292             var isJsonFile = ts.isJsonSourceFile(sourceFile);
94293             // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
94294             var isJsonEmittedToSameLocation = isJsonFile &&
94295                 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
94296             var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
94297             var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
94298             var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
94299             var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94300             return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
94301         }
94302     }
94303     ts.getOutputPathsFor = getOutputPathsFor;
94304     function getSourceMapFilePath(jsFilePath, options) {
94305         return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
94306     }
94307     // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
94308     // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
94309     // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
94310     /* @internal */
94311     function getOutputExtension(sourceFile, options) {
94312         if (ts.isJsonSourceFile(sourceFile)) {
94313             return ".json" /* Json */;
94314         }
94315         if (options.jsx === 1 /* Preserve */) {
94316             if (ts.isSourceFileJS(sourceFile)) {
94317                 if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
94318                     return ".jsx" /* Jsx */;
94319                 }
94320             }
94321             else if (sourceFile.languageVariant === 1 /* JSX */) {
94322                 // TypeScript source file preserving JSX syntax
94323                 return ".jsx" /* Jsx */;
94324             }
94325         }
94326         return ".js" /* Js */;
94327     }
94328     ts.getOutputExtension = getOutputExtension;
94329     function rootDirOfOptions(configFile) {
94330         return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.checkDefined(configFile.options.configFilePath));
94331     }
94332     function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
94333         return outputDir ?
94334             ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
94335             inputFileName;
94336     }
94337     /* @internal */
94338     function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
94339         ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
94340         return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
94341     }
94342     ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
94343     function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
94344         if (configFile.options.emitDeclarationOnly)
94345             return undefined;
94346         var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
94347         var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
94348             ".json" /* Json */ :
94349             ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
94350                 ".jsx" /* Jsx */ :
94351                 ".js" /* Js */);
94352         return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
94353             outputFileName :
94354             undefined;
94355     }
94356     function createAddOutput() {
94357         var outputs;
94358         return { addOutput: addOutput, getOutputs: getOutputs };
94359         function addOutput(path) {
94360             if (path) {
94361                 (outputs || (outputs = [])).push(path);
94362             }
94363         }
94364         function getOutputs() {
94365             return outputs || ts.emptyArray;
94366         }
94367     }
94368     function getSingleOutputFileNames(configFile, addOutput) {
94369         var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94370         addOutput(jsFilePath);
94371         addOutput(sourceMapFilePath);
94372         addOutput(declarationFilePath);
94373         addOutput(declarationMapPath);
94374         addOutput(buildInfoPath);
94375     }
94376     function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput) {
94377         if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94378             return;
94379         var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94380         addOutput(js);
94381         if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94382             return;
94383         if (js && configFile.options.sourceMap) {
94384             addOutput(js + ".map");
94385         }
94386         if (ts.getEmitDeclarations(configFile.options)) {
94387             var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94388             addOutput(dts);
94389             if (configFile.options.declarationMap) {
94390                 addOutput(dts + ".map");
94391             }
94392         }
94393     }
94394     /*@internal*/
94395     function getAllProjectOutputs(configFile, ignoreCase) {
94396         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94397         if (configFile.options.outFile || configFile.options.out) {
94398             getSingleOutputFileNames(configFile, addOutput);
94399         }
94400         else {
94401             for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
94402                 var inputFileName = _c[_b];
94403                 getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
94404             }
94405             addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
94406         }
94407         return getOutputs();
94408     }
94409     ts.getAllProjectOutputs = getAllProjectOutputs;
94410     function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
94411         inputFileName = ts.normalizePath(inputFileName);
94412         ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
94413         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94414         if (commandLine.options.outFile || commandLine.options.out) {
94415             getSingleOutputFileNames(commandLine, addOutput);
94416         }
94417         else {
94418             getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
94419         }
94420         return getOutputs();
94421     }
94422     ts.getOutputFileNames = getOutputFileNames;
94423     /*@internal*/
94424     function getFirstProjectOutput(configFile, ignoreCase) {
94425         if (configFile.options.outFile || configFile.options.out) {
94426             var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
94427             return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
94428         }
94429         for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
94430             var inputFileName = _b[_a];
94431             if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94432                 continue;
94433             var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94434             if (jsFilePath)
94435                 return jsFilePath;
94436             if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94437                 continue;
94438             if (ts.getEmitDeclarations(configFile.options)) {
94439                 return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94440             }
94441         }
94442         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
94443         if (buildInfoPath)
94444             return buildInfoPath;
94445         return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
94446     }
94447     ts.getFirstProjectOutput = getFirstProjectOutput;
94448     /*@internal*/
94449     // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
94450     function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
94451         var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
94452         var compilerOptions = host.getCompilerOptions();
94453         var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
94454         var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
94455         var emitterDiagnostics = ts.createDiagnosticCollection();
94456         var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
94457         var writer = ts.createTextWriter(newLine);
94458         var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
94459         var bundleBuildInfo;
94460         var emitSkipped = false;
94461         var exportedModulesFromDeclarationEmit;
94462         // Emit each output file
94463         enter();
94464         forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
94465         exit();
94466         return {
94467             emitSkipped: emitSkipped,
94468             diagnostics: emitterDiagnostics.getDiagnostics(),
94469             emittedFiles: emittedFilesList,
94470             sourceMaps: sourceMapDataList,
94471             exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
94472         };
94473         function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
94474             var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94475             var buildInfoDirectory;
94476             if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
94477                 buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94478                 bundleBuildInfo = {
94479                     commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
94480                     sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
94481                 };
94482             }
94483             emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
94484             emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
94485             emitBuildInfo(bundleBuildInfo, buildInfoPath);
94486             if (!emitSkipped && emittedFilesList) {
94487                 if (!emitOnlyDtsFiles) {
94488                     if (jsFilePath) {
94489                         emittedFilesList.push(jsFilePath);
94490                     }
94491                     if (sourceMapFilePath) {
94492                         emittedFilesList.push(sourceMapFilePath);
94493                     }
94494                     if (buildInfoPath) {
94495                         emittedFilesList.push(buildInfoPath);
94496                     }
94497                 }
94498                 if (declarationFilePath) {
94499                     emittedFilesList.push(declarationFilePath);
94500                 }
94501                 if (declarationMapPath) {
94502                     emittedFilesList.push(declarationMapPath);
94503                 }
94504             }
94505             function relativeToBuildInfo(path) {
94506                 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
94507             }
94508         }
94509         function emitBuildInfo(bundle, buildInfoPath) {
94510             // Write build information if applicable
94511             if (!buildInfoPath || targetSourceFile || emitSkipped)
94512                 return;
94513             var program = host.getProgramBuildInfo();
94514             if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
94515                 emitSkipped = true;
94516                 return;
94517             }
94518             var version = ts.version; // Extracted into a const so the form is stable between namespace and module
94519             ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
94520         }
94521         function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
94522             if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
94523                 return;
94524             }
94525             // Make sure not to write js file and source map file if any of them cannot be written
94526             if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
94527                 emitSkipped = true;
94528                 return;
94529             }
94530             // Transform the source files
94531             var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
94532             var printerOptions = {
94533                 removeComments: compilerOptions.removeComments,
94534                 newLine: compilerOptions.newLine,
94535                 noEmitHelpers: compilerOptions.noEmitHelpers,
94536                 module: compilerOptions.module,
94537                 target: compilerOptions.target,
94538                 sourceMap: compilerOptions.sourceMap,
94539                 inlineSourceMap: compilerOptions.inlineSourceMap,
94540                 inlineSources: compilerOptions.inlineSources,
94541                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94542                 writeBundleFileInfo: !!bundleBuildInfo,
94543                 relativeToBuildInfo: relativeToBuildInfo
94544             };
94545             // Create a printer to print the nodes
94546             var printer = createPrinter(printerOptions, {
94547                 // resolver hooks
94548                 hasGlobalName: resolver.hasGlobalName,
94549                 // transform hooks
94550                 onEmitNode: transform.emitNodeWithNotification,
94551                 isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
94552                 substituteNode: transform.substituteNode,
94553             });
94554             ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
94555             printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
94556             // Clean up emit nodes on parse tree
94557             transform.dispose();
94558             if (bundleBuildInfo)
94559                 bundleBuildInfo.js = printer.bundleFileInfo;
94560         }
94561         function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
94562             if (!sourceFileOrBundle)
94563                 return;
94564             if (!declarationFilePath) {
94565                 if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
94566                     emitSkipped = true;
94567                 return;
94568             }
94569             var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
94570             var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
94571             // Setup and perform the transformation to retrieve declarations from the input files
94572             var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
94573             if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
94574                 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
94575                 // Do that here when emitting only dts files
94576                 filesForEmit.forEach(collectLinkedAliases);
94577             }
94578             var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
94579             if (ts.length(declarationTransform.diagnostics)) {
94580                 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
94581                     var diagnostic = _b[_a];
94582                     emitterDiagnostics.add(diagnostic);
94583                 }
94584             }
94585             var printerOptions = {
94586                 removeComments: compilerOptions.removeComments,
94587                 newLine: compilerOptions.newLine,
94588                 noEmitHelpers: true,
94589                 module: compilerOptions.module,
94590                 target: compilerOptions.target,
94591                 sourceMap: compilerOptions.sourceMap,
94592                 inlineSourceMap: compilerOptions.inlineSourceMap,
94593                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94594                 onlyPrintJsDocStyle: true,
94595                 writeBundleFileInfo: !!bundleBuildInfo,
94596                 recordInternalSection: !!bundleBuildInfo,
94597                 relativeToBuildInfo: relativeToBuildInfo
94598             };
94599             var declarationPrinter = createPrinter(printerOptions, {
94600                 // resolver hooks
94601                 hasGlobalName: resolver.hasGlobalName,
94602                 // transform hooks
94603                 onEmitNode: declarationTransform.emitNodeWithNotification,
94604                 isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
94605                 substituteNode: declarationTransform.substituteNode,
94606             });
94607             var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
94608             emitSkipped = emitSkipped || declBlocked;
94609             if (!declBlocked || forceDtsEmit) {
94610                 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
94611                 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
94612                     sourceMap: compilerOptions.declarationMap,
94613                     sourceRoot: compilerOptions.sourceRoot,
94614                     mapRoot: compilerOptions.mapRoot,
94615                     extendedDiagnostics: compilerOptions.extendedDiagnostics,
94616                 });
94617                 if (forceDtsEmit && declarationTransform.transformed[0].kind === 290 /* SourceFile */) {
94618                     var sourceFile = declarationTransform.transformed[0];
94619                     exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
94620                 }
94621             }
94622             declarationTransform.dispose();
94623             if (bundleBuildInfo)
94624                 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
94625         }
94626         function collectLinkedAliases(node) {
94627             if (ts.isExportAssignment(node)) {
94628                 if (node.expression.kind === 75 /* Identifier */) {
94629                     resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
94630                 }
94631                 return;
94632             }
94633             else if (ts.isExportSpecifier(node)) {
94634                 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
94635                 return;
94636             }
94637             ts.forEachChild(node, collectLinkedAliases);
94638         }
94639         function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
94640             var bundle = sourceFileOrBundle.kind === 291 /* Bundle */ ? sourceFileOrBundle : undefined;
94641             var sourceFile = sourceFileOrBundle.kind === 290 /* SourceFile */ ? sourceFileOrBundle : undefined;
94642             var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
94643             var sourceMapGenerator;
94644             if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
94645                 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
94646             }
94647             if (bundle) {
94648                 printer.writeBundle(bundle, writer, sourceMapGenerator);
94649             }
94650             else {
94651                 printer.writeFile(sourceFile, writer, sourceMapGenerator);
94652             }
94653             if (sourceMapGenerator) {
94654                 if (sourceMapDataList) {
94655                     sourceMapDataList.push({
94656                         inputSourceFileNames: sourceMapGenerator.getSources(),
94657                         sourceMap: sourceMapGenerator.toJSON()
94658                     });
94659                 }
94660                 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
94661                 if (sourceMappingURL) {
94662                     if (!writer.isAtStartOfLine())
94663                         writer.rawWrite(newLine);
94664                     writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
94665                 }
94666                 // Write the source map
94667                 if (sourceMapFilePath) {
94668                     var sourceMap = sourceMapGenerator.toString();
94669                     ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
94670                 }
94671             }
94672             else {
94673                 writer.writeLine();
94674             }
94675             // Write the output file
94676             ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
94677             // Reset state
94678             writer.clear();
94679         }
94680         function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
94681             return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
94682                 && (sourceFileOrBundle.kind !== 290 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
94683         }
94684         function getSourceRoot(mapOptions) {
94685             // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
94686             // relative paths of the sources list in the sourcemap
94687             var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
94688             return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
94689         }
94690         function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
94691             if (mapOptions.sourceRoot)
94692                 return host.getCommonSourceDirectory();
94693             if (mapOptions.mapRoot) {
94694                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94695                 if (sourceFile) {
94696                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94697                     // 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
94698                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94699                 }
94700                 if (ts.getRootLength(sourceMapDir) === 0) {
94701                     // The relative paths are relative to the common directory
94702                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94703                 }
94704                 return sourceMapDir;
94705             }
94706             return ts.getDirectoryPath(ts.normalizePath(filePath));
94707         }
94708         function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
94709             if (mapOptions.inlineSourceMap) {
94710                 // Encode the sourceMap into the sourceMap url
94711                 var sourceMapText = sourceMapGenerator.toString();
94712                 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
94713                 return "data:application/json;base64," + base64SourceMapText;
94714             }
94715             var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath)));
94716             if (mapOptions.mapRoot) {
94717                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94718                 if (sourceFile) {
94719                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94720                     // 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
94721                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94722                 }
94723                 if (ts.getRootLength(sourceMapDir) === 0) {
94724                     // The relative paths are relative to the common directory
94725                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94726                     return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
94727                     ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
94728                     host.getCurrentDirectory(), host.getCanonicalFileName, 
94729                     /*isAbsolutePathAnUrl*/ true);
94730                 }
94731                 else {
94732                     return ts.combinePaths(sourceMapDir, sourceMapFile);
94733                 }
94734             }
94735             return sourceMapFile;
94736         }
94737     }
94738     ts.emitFiles = emitFiles;
94739     /*@internal*/
94740     function getBuildInfoText(buildInfo) {
94741         return JSON.stringify(buildInfo, undefined, 2);
94742     }
94743     ts.getBuildInfoText = getBuildInfoText;
94744     /*@internal*/
94745     function getBuildInfo(buildInfoText) {
94746         return JSON.parse(buildInfoText);
94747     }
94748     ts.getBuildInfo = getBuildInfo;
94749     /*@internal*/
94750     ts.notImplementedResolver = {
94751         hasGlobalName: ts.notImplemented,
94752         getReferencedExportContainer: ts.notImplemented,
94753         getReferencedImportDeclaration: ts.notImplemented,
94754         getReferencedDeclarationWithCollidingName: ts.notImplemented,
94755         isDeclarationWithCollidingName: ts.notImplemented,
94756         isValueAliasDeclaration: ts.notImplemented,
94757         isReferencedAliasDeclaration: ts.notImplemented,
94758         isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
94759         getNodeCheckFlags: ts.notImplemented,
94760         isDeclarationVisible: ts.notImplemented,
94761         isLateBound: function (_node) { return false; },
94762         collectLinkedAliases: ts.notImplemented,
94763         isImplementationOfOverload: ts.notImplemented,
94764         isRequiredInitializedParameter: ts.notImplemented,
94765         isOptionalUninitializedParameterProperty: ts.notImplemented,
94766         isExpandoFunctionDeclaration: ts.notImplemented,
94767         getPropertiesOfContainerFunction: ts.notImplemented,
94768         createTypeOfDeclaration: ts.notImplemented,
94769         createReturnTypeOfSignatureDeclaration: ts.notImplemented,
94770         createTypeOfExpression: ts.notImplemented,
94771         createLiteralConstValue: ts.notImplemented,
94772         isSymbolAccessible: ts.notImplemented,
94773         isEntityNameVisible: ts.notImplemented,
94774         // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
94775         getConstantValue: ts.notImplemented,
94776         getReferencedValueDeclaration: ts.notImplemented,
94777         getTypeReferenceSerializationKind: ts.notImplemented,
94778         isOptionalParameter: ts.notImplemented,
94779         moduleExportsSomeValue: ts.notImplemented,
94780         isArgumentsLocalBinding: ts.notImplemented,
94781         getExternalModuleFileFromDeclaration: ts.notImplemented,
94782         getTypeReferenceDirectivesForEntityName: ts.notImplemented,
94783         getTypeReferenceDirectivesForSymbol: ts.notImplemented,
94784         isLiteralConstDeclaration: ts.notImplemented,
94785         getJsxFactoryEntity: ts.notImplemented,
94786         getAllAccessorDeclarations: ts.notImplemented,
94787         getSymbolOfExternalModuleSpecifier: ts.notImplemented,
94788         isBindingCapturedByNode: ts.notImplemented,
94789         getDeclarationStatementsForSourceFile: ts.notImplemented,
94790         isImportRequiredByAugmentation: ts.notImplemented,
94791     };
94792     function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
94793         var sourceFiles = bundle.sourceFiles.map(function (fileName) {
94794             var sourceFile = ts.createNode(290 /* SourceFile */, 0, 0);
94795             sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
94796             sourceFile.text = "";
94797             sourceFile.statements = ts.createNodeArray();
94798             return sourceFile;
94799         });
94800         var jsBundle = ts.Debug.checkDefined(bundle.js);
94801         ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
94802             var sourceFile = sourceFiles[prologueInfo.file];
94803             sourceFile.text = prologueInfo.text;
94804             sourceFile.end = prologueInfo.text.length;
94805             sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
94806                 var statement = ts.createNode(226 /* ExpressionStatement */, directive.pos, directive.end);
94807                 statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
94808                 statement.expression.text = directive.expression.text;
94809                 return statement;
94810             }));
94811         });
94812         return sourceFiles;
94813     }
94814     /*@internal*/
94815     function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
94816         var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
94817         var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath));
94818         if (!buildInfoText)
94819             return buildInfoPath;
94820         var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath));
94821         if (!jsFileText)
94822             return jsFilePath;
94823         var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
94824         // error if no source map or for now if inline sourcemap
94825         if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
94826             return sourceMapFilePath || "inline sourcemap decoding";
94827         // read declaration text
94828         var declarationText = declarationFilePath && host.readFile(declarationFilePath);
94829         if (declarationFilePath && !declarationText)
94830             return declarationFilePath;
94831         var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
94832         // error if no source map or for now if inline sourcemap
94833         if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
94834             return declarationMapPath || "inline sourcemap decoding";
94835         var buildInfo = getBuildInfo(buildInfoText);
94836         if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
94837             return buildInfoPath;
94838         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94839         var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, 
94840         /*onlyOwnText*/ true);
94841         var outputFiles = [];
94842         var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
94843         var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
94844         var emitHost = {
94845             getPrependNodes: ts.memoize(function () { return __spreadArrays(prependNodes, [ownPrependInput]); }),
94846             getCanonicalFileName: host.getCanonicalFileName,
94847             getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
94848             getCompilerOptions: function () { return config.options; },
94849             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
94850             getNewLine: function () { return host.getNewLine(); },
94851             getSourceFile: ts.returnUndefined,
94852             getSourceFileByPath: ts.returnUndefined,
94853             getSourceFiles: function () { return sourceFilesForJsEmit; },
94854             getLibFileFromReference: ts.notImplemented,
94855             isSourceFileFromExternalLibrary: ts.returnFalse,
94856             getResolvedProjectReferenceToRedirect: ts.returnUndefined,
94857             getProjectReferenceRedirect: ts.returnUndefined,
94858             isSourceOfProjectReferenceRedirect: ts.returnFalse,
94859             writeFile: function (name, text, writeByteOrderMark) {
94860                 switch (name) {
94861                     case jsFilePath:
94862                         if (jsFileText === text)
94863                             return;
94864                         break;
94865                     case sourceMapFilePath:
94866                         if (sourceMapText === text)
94867                             return;
94868                         break;
94869                     case buildInfoPath:
94870                         var newBuildInfo = getBuildInfo(text);
94871                         newBuildInfo.program = buildInfo.program;
94872                         // Update sourceFileInfo
94873                         var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
94874                         newBuildInfo.bundle.js.sources = js.sources;
94875                         if (dts) {
94876                             newBuildInfo.bundle.dts.sources = dts.sources;
94877                         }
94878                         newBuildInfo.bundle.sourceFiles = sourceFiles;
94879                         outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
94880                         return;
94881                     case declarationFilePath:
94882                         if (declarationText === text)
94883                             return;
94884                         break;
94885                     case declarationMapPath:
94886                         if (declarationMapText === text)
94887                             return;
94888                         break;
94889                     default:
94890                         ts.Debug.fail("Unexpected path: " + name);
94891                 }
94892                 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
94893             },
94894             isEmitBlocked: ts.returnFalse,
94895             readFile: function (f) { return host.readFile(f); },
94896             fileExists: function (f) { return host.fileExists(f); },
94897             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
94898             getProgramBuildInfo: ts.returnUndefined,
94899             getSourceFileFromReference: ts.returnUndefined,
94900             redirectTargetsMap: ts.createMultiMap()
94901         };
94902         emitFiles(ts.notImplementedResolver, emitHost, 
94903         /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
94904         return outputFiles;
94905     }
94906     ts.emitUsingBuildInfo = emitUsingBuildInfo;
94907     var PipelinePhase;
94908     (function (PipelinePhase) {
94909         PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
94910         PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
94911         PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
94912         PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
94913         PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
94914     })(PipelinePhase || (PipelinePhase = {}));
94915     function createPrinter(printerOptions, handlers) {
94916         if (printerOptions === void 0) { printerOptions = {}; }
94917         if (handlers === void 0) { handlers = {}; }
94918         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;
94919         var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
94920         var newLine = ts.getNewLineCharacter(printerOptions);
94921         var moduleKind = ts.getEmitModuleKind(printerOptions);
94922         var bundledHelpers = ts.createMap();
94923         var currentSourceFile;
94924         var nodeIdToGeneratedName; // Map of generated names for specific nodes.
94925         var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
94926         var generatedNames; // Set of names generated by the NameGenerator.
94927         var tempFlagsStack; // Stack of enclosing name generation scopes.
94928         var tempFlags; // TempFlags for the current name generation scope.
94929         var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
94930         var reservedNames; // TempFlags to reserve in nested name generation scopes.
94931         var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
94932         var writer;
94933         var ownWriter; // Reusable `EmitTextWriter` for basic printing.
94934         var write = writeBase;
94935         var isOwnFileEmit;
94936         var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
94937         var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
94938         var recordInternalSection = printerOptions.recordInternalSection;
94939         var sourceFileTextPos = 0;
94940         var sourceFileTextKind = "text" /* Text */;
94941         // Source Maps
94942         var sourceMapsDisabled = true;
94943         var sourceMapGenerator;
94944         var sourceMapSource;
94945         var sourceMapSourceIndex = -1;
94946         // Comments
94947         var containerPos = -1;
94948         var containerEnd = -1;
94949         var declarationListContainerEnd = -1;
94950         var currentLineMap;
94951         var detachedCommentsInfo;
94952         var hasWrittenComment = false;
94953         var commentsDisabled = !!printerOptions.removeComments;
94954         var lastNode;
94955         var lastSubstitution;
94956         var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
94957         reset();
94958         return {
94959             // public API
94960             printNode: printNode,
94961             printList: printList,
94962             printFile: printFile,
94963             printBundle: printBundle,
94964             // internal API
94965             writeNode: writeNode,
94966             writeList: writeList,
94967             writeFile: writeFile,
94968             writeBundle: writeBundle,
94969             bundleFileInfo: bundleFileInfo
94970         };
94971         function printNode(hint, node, sourceFile) {
94972             switch (hint) {
94973                 case 0 /* SourceFile */:
94974                     ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
94975                     break;
94976                 case 2 /* IdentifierName */:
94977                     ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
94978                     break;
94979                 case 1 /* Expression */:
94980                     ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
94981                     break;
94982             }
94983             switch (node.kind) {
94984                 case 290 /* SourceFile */: return printFile(node);
94985                 case 291 /* Bundle */: return printBundle(node);
94986                 case 292 /* UnparsedSource */: return printUnparsedSource(node);
94987             }
94988             writeNode(hint, node, sourceFile, beginPrint());
94989             return endPrint();
94990         }
94991         function printList(format, nodes, sourceFile) {
94992             writeList(format, nodes, sourceFile, beginPrint());
94993             return endPrint();
94994         }
94995         function printBundle(bundle) {
94996             writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
94997             return endPrint();
94998         }
94999         function printFile(sourceFile) {
95000             writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
95001             return endPrint();
95002         }
95003         function printUnparsedSource(unparsed) {
95004             writeUnparsedSource(unparsed, beginPrint());
95005             return endPrint();
95006         }
95007         function writeNode(hint, node, sourceFile, output) {
95008             var previousWriter = writer;
95009             setWriter(output, /*_sourceMapGenerator*/ undefined);
95010             print(hint, node, sourceFile);
95011             reset();
95012             writer = previousWriter;
95013         }
95014         function writeList(format, nodes, sourceFile, output) {
95015             var previousWriter = writer;
95016             setWriter(output, /*_sourceMapGenerator*/ undefined);
95017             if (sourceFile) {
95018                 setSourceFile(sourceFile);
95019             }
95020             emitList(syntheticParent, nodes, format);
95021             reset();
95022             writer = previousWriter;
95023         }
95024         function getTextPosWithWriteLine() {
95025             return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
95026         }
95027         function updateOrPushBundleFileTextLike(pos, end, kind) {
95028             var last = ts.lastOrUndefined(bundleFileInfo.sections);
95029             if (last && last.kind === kind) {
95030                 last.end = end;
95031             }
95032             else {
95033                 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
95034             }
95035         }
95036         function recordBundleFileInternalSectionStart(node) {
95037             if (recordInternalSection &&
95038                 bundleFileInfo &&
95039                 currentSourceFile &&
95040                 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
95041                 ts.isInternalDeclaration(node, currentSourceFile) &&
95042                 sourceFileTextKind !== "internal" /* Internal */) {
95043                 var prevSourceFileTextKind = sourceFileTextKind;
95044                 recordBundleFileTextLikeSection(writer.getTextPos());
95045                 sourceFileTextPos = getTextPosWithWriteLine();
95046                 sourceFileTextKind = "internal" /* Internal */;
95047                 return prevSourceFileTextKind;
95048             }
95049             return undefined;
95050         }
95051         function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
95052             if (prevSourceFileTextKind) {
95053                 recordBundleFileTextLikeSection(writer.getTextPos());
95054                 sourceFileTextPos = getTextPosWithWriteLine();
95055                 sourceFileTextKind = prevSourceFileTextKind;
95056             }
95057         }
95058         function recordBundleFileTextLikeSection(end) {
95059             if (sourceFileTextPos < end) {
95060                 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
95061                 return true;
95062             }
95063             return false;
95064         }
95065         function writeBundle(bundle, output, sourceMapGenerator) {
95066             var _a;
95067             isOwnFileEmit = false;
95068             var previousWriter = writer;
95069             setWriter(output, sourceMapGenerator);
95070             emitShebangIfNeeded(bundle);
95071             emitPrologueDirectivesIfNeeded(bundle);
95072             emitHelpers(bundle);
95073             emitSyntheticTripleSlashReferencesIfNeeded(bundle);
95074             for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
95075                 var prepend = _c[_b];
95076                 writeLine();
95077                 var pos = writer.getTextPos();
95078                 var savedSections = bundleFileInfo && bundleFileInfo.sections;
95079                 if (savedSections)
95080                     bundleFileInfo.sections = [];
95081                 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
95082                 if (bundleFileInfo) {
95083                     var newSections = bundleFileInfo.sections;
95084                     bundleFileInfo.sections = savedSections;
95085                     if (prepend.oldFileOfCurrentEmit)
95086                         (_a = bundleFileInfo.sections).push.apply(_a, newSections);
95087                     else {
95088                         newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
95089                         bundleFileInfo.sections.push({
95090                             pos: pos,
95091                             end: writer.getTextPos(),
95092                             kind: "prepend" /* Prepend */,
95093                             data: relativeToBuildInfo(prepend.fileName),
95094                             texts: newSections
95095                         });
95096                     }
95097                 }
95098             }
95099             sourceFileTextPos = getTextPosWithWriteLine();
95100             for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
95101                 var sourceFile = _e[_d];
95102                 print(0 /* SourceFile */, sourceFile, sourceFile);
95103             }
95104             if (bundleFileInfo && bundle.sourceFiles.length) {
95105                 var end = writer.getTextPos();
95106                 if (recordBundleFileTextLikeSection(end)) {
95107                     // Store prologues
95108                     var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
95109                     if (prologues) {
95110                         if (!bundleFileInfo.sources)
95111                             bundleFileInfo.sources = {};
95112                         bundleFileInfo.sources.prologues = prologues;
95113                     }
95114                     // Store helpes
95115                     var helpers = getHelpersFromBundledSourceFiles(bundle);
95116                     if (helpers) {
95117                         if (!bundleFileInfo.sources)
95118                             bundleFileInfo.sources = {};
95119                         bundleFileInfo.sources.helpers = helpers;
95120                     }
95121                 }
95122             }
95123             reset();
95124             writer = previousWriter;
95125         }
95126         function writeUnparsedSource(unparsed, output) {
95127             var previousWriter = writer;
95128             setWriter(output, /*_sourceMapGenerator*/ undefined);
95129             print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
95130             reset();
95131             writer = previousWriter;
95132         }
95133         function writeFile(sourceFile, output, sourceMapGenerator) {
95134             isOwnFileEmit = true;
95135             var previousWriter = writer;
95136             setWriter(output, sourceMapGenerator);
95137             emitShebangIfNeeded(sourceFile);
95138             emitPrologueDirectivesIfNeeded(sourceFile);
95139             print(0 /* SourceFile */, sourceFile, sourceFile);
95140             reset();
95141             writer = previousWriter;
95142         }
95143         function beginPrint() {
95144             return ownWriter || (ownWriter = ts.createTextWriter(newLine));
95145         }
95146         function endPrint() {
95147             var text = ownWriter.getText();
95148             ownWriter.clear();
95149             return text;
95150         }
95151         function print(hint, node, sourceFile) {
95152             if (sourceFile) {
95153                 setSourceFile(sourceFile);
95154             }
95155             pipelineEmit(hint, node);
95156         }
95157         function setSourceFile(sourceFile) {
95158             currentSourceFile = sourceFile;
95159             currentLineMap = undefined;
95160             detachedCommentsInfo = undefined;
95161             if (sourceFile) {
95162                 setSourceMapSource(sourceFile);
95163             }
95164         }
95165         function setWriter(_writer, _sourceMapGenerator) {
95166             if (_writer && printerOptions.omitTrailingSemicolon) {
95167                 _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
95168             }
95169             writer = _writer; // TODO: GH#18217
95170             sourceMapGenerator = _sourceMapGenerator;
95171             sourceMapsDisabled = !writer || !sourceMapGenerator;
95172         }
95173         function reset() {
95174             nodeIdToGeneratedName = [];
95175             autoGeneratedIdToGeneratedName = [];
95176             generatedNames = ts.createMap();
95177             tempFlagsStack = [];
95178             tempFlags = 0 /* Auto */;
95179             reservedNamesStack = [];
95180             currentSourceFile = undefined;
95181             currentLineMap = undefined;
95182             detachedCommentsInfo = undefined;
95183             lastNode = undefined;
95184             lastSubstitution = undefined;
95185             setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
95186         }
95187         function getCurrentLineMap() {
95188             return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
95189         }
95190         function emit(node) {
95191             if (node === undefined)
95192                 return;
95193             var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
95194             var substitute = pipelineEmit(4 /* Unspecified */, node);
95195             recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
95196             return substitute;
95197         }
95198         function emitIdentifierName(node) {
95199             if (node === undefined)
95200                 return;
95201             return pipelineEmit(2 /* IdentifierName */, node);
95202         }
95203         function emitExpression(node) {
95204             if (node === undefined)
95205                 return;
95206             return pipelineEmit(1 /* Expression */, node);
95207         }
95208         function emitJsxAttributeValue(node) {
95209             return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
95210         }
95211         function pipelineEmit(emitHint, node) {
95212             var savedLastNode = lastNode;
95213             var savedLastSubstitution = lastSubstitution;
95214             var savedPreserveSourceNewlines = preserveSourceNewlines;
95215             lastNode = node;
95216             lastSubstitution = undefined;
95217             if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) {
95218                 preserveSourceNewlines = false;
95219             }
95220             var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
95221             pipelinePhase(emitHint, node);
95222             ts.Debug.assert(lastNode === node);
95223             var substitute = lastSubstitution;
95224             lastNode = savedLastNode;
95225             lastSubstitution = savedLastSubstitution;
95226             preserveSourceNewlines = savedPreserveSourceNewlines;
95227             return substitute || node;
95228         }
95229         function getPipelinePhase(phase, emitHint, node) {
95230             switch (phase) {
95231                 case 0 /* Notification */:
95232                     if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
95233                         return pipelineEmitWithNotification;
95234                     }
95235                 // falls through
95236                 case 1 /* Substitution */:
95237                     if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
95238                         return pipelineEmitWithSubstitution;
95239                     }
95240                 // falls through
95241                 case 2 /* Comments */:
95242                     if (!commentsDisabled && node.kind !== 290 /* SourceFile */) {
95243                         return pipelineEmitWithComments;
95244                     }
95245                 // falls through
95246                 case 3 /* SourceMaps */:
95247                     if (!sourceMapsDisabled && node.kind !== 290 /* SourceFile */ && !ts.isInJsonFile(node)) {
95248                         return pipelineEmitWithSourceMap;
95249                     }
95250                 // falls through
95251                 case 4 /* Emit */:
95252                     return pipelineEmitWithHint;
95253                 default:
95254                     return ts.Debug.assertNever(phase);
95255             }
95256         }
95257         function getNextPipelinePhase(currentPhase, emitHint, node) {
95258             return getPipelinePhase(currentPhase + 1, emitHint, node);
95259         }
95260         function pipelineEmitWithNotification(hint, node) {
95261             ts.Debug.assert(lastNode === node);
95262             var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
95263             onEmitNode(hint, node, pipelinePhase);
95264             ts.Debug.assert(lastNode === node);
95265         }
95266         function pipelineEmitWithHint(hint, node) {
95267             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95268             if (hint === 0 /* SourceFile */)
95269                 return emitSourceFile(ts.cast(node, ts.isSourceFile));
95270             if (hint === 2 /* IdentifierName */)
95271                 return emitIdentifier(ts.cast(node, ts.isIdentifier));
95272             if (hint === 6 /* JsxAttributeValue */)
95273                 return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
95274             if (hint === 3 /* MappedTypeParameter */)
95275                 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
95276             if (hint === 5 /* EmbeddedStatement */) {
95277                 ts.Debug.assertNode(node, ts.isEmptyStatement);
95278                 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
95279             }
95280             if (hint === 4 /* Unspecified */) {
95281                 if (ts.isKeyword(node.kind))
95282                     return writeTokenNode(node, writeKeyword);
95283                 switch (node.kind) {
95284                     // Pseudo-literals
95285                     case 15 /* TemplateHead */:
95286                     case 16 /* TemplateMiddle */:
95287                     case 17 /* TemplateTail */:
95288                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95289                     case 292 /* UnparsedSource */:
95290                     case 286 /* UnparsedPrepend */:
95291                         return emitUnparsedSourceOrPrepend(node);
95292                     case 285 /* UnparsedPrologue */:
95293                         return writeUnparsedNode(node);
95294                     case 287 /* UnparsedText */:
95295                     case 288 /* UnparsedInternalText */:
95296                         return emitUnparsedTextLike(node);
95297                     case 289 /* UnparsedSyntheticReference */:
95298                         return emitUnparsedSyntheticReference(node);
95299                     // Identifiers
95300                     case 75 /* Identifier */:
95301                         return emitIdentifier(node);
95302                     // PrivateIdentifiers
95303                     case 76 /* PrivateIdentifier */:
95304                         return emitPrivateIdentifier(node);
95305                     // Parse tree nodes
95306                     // Names
95307                     case 153 /* QualifiedName */:
95308                         return emitQualifiedName(node);
95309                     case 154 /* ComputedPropertyName */:
95310                         return emitComputedPropertyName(node);
95311                     // Signature elements
95312                     case 155 /* TypeParameter */:
95313                         return emitTypeParameter(node);
95314                     case 156 /* Parameter */:
95315                         return emitParameter(node);
95316                     case 157 /* Decorator */:
95317                         return emitDecorator(node);
95318                     // Type members
95319                     case 158 /* PropertySignature */:
95320                         return emitPropertySignature(node);
95321                     case 159 /* PropertyDeclaration */:
95322                         return emitPropertyDeclaration(node);
95323                     case 160 /* MethodSignature */:
95324                         return emitMethodSignature(node);
95325                     case 161 /* MethodDeclaration */:
95326                         return emitMethodDeclaration(node);
95327                     case 162 /* Constructor */:
95328                         return emitConstructor(node);
95329                     case 163 /* GetAccessor */:
95330                     case 164 /* SetAccessor */:
95331                         return emitAccessorDeclaration(node);
95332                     case 165 /* CallSignature */:
95333                         return emitCallSignature(node);
95334                     case 166 /* ConstructSignature */:
95335                         return emitConstructSignature(node);
95336                     case 167 /* IndexSignature */:
95337                         return emitIndexSignature(node);
95338                     // Types
95339                     case 168 /* TypePredicate */:
95340                         return emitTypePredicate(node);
95341                     case 169 /* TypeReference */:
95342                         return emitTypeReference(node);
95343                     case 170 /* FunctionType */:
95344                         return emitFunctionType(node);
95345                     case 300 /* JSDocFunctionType */:
95346                         return emitJSDocFunctionType(node);
95347                     case 171 /* ConstructorType */:
95348                         return emitConstructorType(node);
95349                     case 172 /* TypeQuery */:
95350                         return emitTypeQuery(node);
95351                     case 173 /* TypeLiteral */:
95352                         return emitTypeLiteral(node);
95353                     case 174 /* ArrayType */:
95354                         return emitArrayType(node);
95355                     case 175 /* TupleType */:
95356                         return emitTupleType(node);
95357                     case 176 /* OptionalType */:
95358                         return emitOptionalType(node);
95359                     case 178 /* UnionType */:
95360                         return emitUnionType(node);
95361                     case 179 /* IntersectionType */:
95362                         return emitIntersectionType(node);
95363                     case 180 /* ConditionalType */:
95364                         return emitConditionalType(node);
95365                     case 181 /* InferType */:
95366                         return emitInferType(node);
95367                     case 182 /* ParenthesizedType */:
95368                         return emitParenthesizedType(node);
95369                     case 216 /* ExpressionWithTypeArguments */:
95370                         return emitExpressionWithTypeArguments(node);
95371                     case 183 /* ThisType */:
95372                         return emitThisType();
95373                     case 184 /* TypeOperator */:
95374                         return emitTypeOperator(node);
95375                     case 185 /* IndexedAccessType */:
95376                         return emitIndexedAccessType(node);
95377                     case 186 /* MappedType */:
95378                         return emitMappedType(node);
95379                     case 187 /* LiteralType */:
95380                         return emitLiteralType(node);
95381                     case 188 /* ImportType */:
95382                         return emitImportTypeNode(node);
95383                     case 295 /* JSDocAllType */:
95384                         writePunctuation("*");
95385                         return;
95386                     case 296 /* JSDocUnknownType */:
95387                         writePunctuation("?");
95388                         return;
95389                     case 297 /* JSDocNullableType */:
95390                         return emitJSDocNullableType(node);
95391                     case 298 /* JSDocNonNullableType */:
95392                         return emitJSDocNonNullableType(node);
95393                     case 299 /* JSDocOptionalType */:
95394                         return emitJSDocOptionalType(node);
95395                     case 177 /* RestType */:
95396                     case 301 /* JSDocVariadicType */:
95397                         return emitRestOrJSDocVariadicType(node);
95398                     // Binding patterns
95399                     case 189 /* ObjectBindingPattern */:
95400                         return emitObjectBindingPattern(node);
95401                     case 190 /* ArrayBindingPattern */:
95402                         return emitArrayBindingPattern(node);
95403                     case 191 /* BindingElement */:
95404                         return emitBindingElement(node);
95405                     // Misc
95406                     case 221 /* TemplateSpan */:
95407                         return emitTemplateSpan(node);
95408                     case 222 /* SemicolonClassElement */:
95409                         return emitSemicolonClassElement();
95410                     // Statements
95411                     case 223 /* Block */:
95412                         return emitBlock(node);
95413                     case 225 /* VariableStatement */:
95414                         return emitVariableStatement(node);
95415                     case 224 /* EmptyStatement */:
95416                         return emitEmptyStatement(/*isEmbeddedStatement*/ false);
95417                     case 226 /* ExpressionStatement */:
95418                         return emitExpressionStatement(node);
95419                     case 227 /* IfStatement */:
95420                         return emitIfStatement(node);
95421                     case 228 /* DoStatement */:
95422                         return emitDoStatement(node);
95423                     case 229 /* WhileStatement */:
95424                         return emitWhileStatement(node);
95425                     case 230 /* ForStatement */:
95426                         return emitForStatement(node);
95427                     case 231 /* ForInStatement */:
95428                         return emitForInStatement(node);
95429                     case 232 /* ForOfStatement */:
95430                         return emitForOfStatement(node);
95431                     case 233 /* ContinueStatement */:
95432                         return emitContinueStatement(node);
95433                     case 234 /* BreakStatement */:
95434                         return emitBreakStatement(node);
95435                     case 235 /* ReturnStatement */:
95436                         return emitReturnStatement(node);
95437                     case 236 /* WithStatement */:
95438                         return emitWithStatement(node);
95439                     case 237 /* SwitchStatement */:
95440                         return emitSwitchStatement(node);
95441                     case 238 /* LabeledStatement */:
95442                         return emitLabeledStatement(node);
95443                     case 239 /* ThrowStatement */:
95444                         return emitThrowStatement(node);
95445                     case 240 /* TryStatement */:
95446                         return emitTryStatement(node);
95447                     case 241 /* DebuggerStatement */:
95448                         return emitDebuggerStatement(node);
95449                     // Declarations
95450                     case 242 /* VariableDeclaration */:
95451                         return emitVariableDeclaration(node);
95452                     case 243 /* VariableDeclarationList */:
95453                         return emitVariableDeclarationList(node);
95454                     case 244 /* FunctionDeclaration */:
95455                         return emitFunctionDeclaration(node);
95456                     case 245 /* ClassDeclaration */:
95457                         return emitClassDeclaration(node);
95458                     case 246 /* InterfaceDeclaration */:
95459                         return emitInterfaceDeclaration(node);
95460                     case 247 /* TypeAliasDeclaration */:
95461                         return emitTypeAliasDeclaration(node);
95462                     case 248 /* EnumDeclaration */:
95463                         return emitEnumDeclaration(node);
95464                     case 249 /* ModuleDeclaration */:
95465                         return emitModuleDeclaration(node);
95466                     case 250 /* ModuleBlock */:
95467                         return emitModuleBlock(node);
95468                     case 251 /* CaseBlock */:
95469                         return emitCaseBlock(node);
95470                     case 252 /* NamespaceExportDeclaration */:
95471                         return emitNamespaceExportDeclaration(node);
95472                     case 253 /* ImportEqualsDeclaration */:
95473                         return emitImportEqualsDeclaration(node);
95474                     case 254 /* ImportDeclaration */:
95475                         return emitImportDeclaration(node);
95476                     case 255 /* ImportClause */:
95477                         return emitImportClause(node);
95478                     case 256 /* NamespaceImport */:
95479                         return emitNamespaceImport(node);
95480                     case 262 /* NamespaceExport */:
95481                         return emitNamespaceExport(node);
95482                     case 257 /* NamedImports */:
95483                         return emitNamedImports(node);
95484                     case 258 /* ImportSpecifier */:
95485                         return emitImportSpecifier(node);
95486                     case 259 /* ExportAssignment */:
95487                         return emitExportAssignment(node);
95488                     case 260 /* ExportDeclaration */:
95489                         return emitExportDeclaration(node);
95490                     case 261 /* NamedExports */:
95491                         return emitNamedExports(node);
95492                     case 263 /* ExportSpecifier */:
95493                         return emitExportSpecifier(node);
95494                     case 264 /* MissingDeclaration */:
95495                         return;
95496                     // Module references
95497                     case 265 /* ExternalModuleReference */:
95498                         return emitExternalModuleReference(node);
95499                     // JSX (non-expression)
95500                     case 11 /* JsxText */:
95501                         return emitJsxText(node);
95502                     case 268 /* JsxOpeningElement */:
95503                     case 271 /* JsxOpeningFragment */:
95504                         return emitJsxOpeningElementOrFragment(node);
95505                     case 269 /* JsxClosingElement */:
95506                     case 272 /* JsxClosingFragment */:
95507                         return emitJsxClosingElementOrFragment(node);
95508                     case 273 /* JsxAttribute */:
95509                         return emitJsxAttribute(node);
95510                     case 274 /* JsxAttributes */:
95511                         return emitJsxAttributes(node);
95512                     case 275 /* JsxSpreadAttribute */:
95513                         return emitJsxSpreadAttribute(node);
95514                     case 276 /* JsxExpression */:
95515                         return emitJsxExpression(node);
95516                     // Clauses
95517                     case 277 /* CaseClause */:
95518                         return emitCaseClause(node);
95519                     case 278 /* DefaultClause */:
95520                         return emitDefaultClause(node);
95521                     case 279 /* HeritageClause */:
95522                         return emitHeritageClause(node);
95523                     case 280 /* CatchClause */:
95524                         return emitCatchClause(node);
95525                     // Property assignments
95526                     case 281 /* PropertyAssignment */:
95527                         return emitPropertyAssignment(node);
95528                     case 282 /* ShorthandPropertyAssignment */:
95529                         return emitShorthandPropertyAssignment(node);
95530                     case 283 /* SpreadAssignment */:
95531                         return emitSpreadAssignment(node);
95532                     // Enum
95533                     case 284 /* EnumMember */:
95534                         return emitEnumMember(node);
95535                     // JSDoc nodes (only used in codefixes currently)
95536                     case 317 /* JSDocParameterTag */:
95537                     case 323 /* JSDocPropertyTag */:
95538                         return emitJSDocPropertyLikeTag(node);
95539                     case 318 /* JSDocReturnTag */:
95540                     case 320 /* JSDocTypeTag */:
95541                     case 319 /* JSDocThisTag */:
95542                     case 316 /* JSDocEnumTag */:
95543                         return emitJSDocSimpleTypedTag(node);
95544                     case 308 /* JSDocImplementsTag */:
95545                     case 307 /* JSDocAugmentsTag */:
95546                         return emitJSDocHeritageTag(node);
95547                     case 321 /* JSDocTemplateTag */:
95548                         return emitJSDocTemplateTag(node);
95549                     case 322 /* JSDocTypedefTag */:
95550                         return emitJSDocTypedefTag(node);
95551                     case 315 /* JSDocCallbackTag */:
95552                         return emitJSDocCallbackTag(node);
95553                     case 305 /* JSDocSignature */:
95554                         return emitJSDocSignature(node);
95555                     case 304 /* JSDocTypeLiteral */:
95556                         return emitJSDocTypeLiteral(node);
95557                     case 310 /* JSDocClassTag */:
95558                     case 306 /* JSDocTag */:
95559                         return emitJSDocSimpleTag(node);
95560                     case 303 /* JSDocComment */:
95561                         return emitJSDoc(node);
95562                     // Transformation nodes (ignored)
95563                 }
95564                 if (ts.isExpression(node)) {
95565                     hint = 1 /* Expression */;
95566                     if (substituteNode !== ts.noEmitSubstitution) {
95567                         lastSubstitution = node = substituteNode(hint, node);
95568                     }
95569                 }
95570                 else if (ts.isToken(node)) {
95571                     return writeTokenNode(node, writePunctuation);
95572                 }
95573             }
95574             if (hint === 1 /* Expression */) {
95575                 switch (node.kind) {
95576                     // Literals
95577                     case 8 /* NumericLiteral */:
95578                     case 9 /* BigIntLiteral */:
95579                         return emitNumericOrBigIntLiteral(node);
95580                     case 10 /* StringLiteral */:
95581                     case 13 /* RegularExpressionLiteral */:
95582                     case 14 /* NoSubstitutionTemplateLiteral */:
95583                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95584                     // Identifiers
95585                     case 75 /* Identifier */:
95586                         return emitIdentifier(node);
95587                     // Reserved words
95588                     case 91 /* FalseKeyword */:
95589                     case 100 /* NullKeyword */:
95590                     case 102 /* SuperKeyword */:
95591                     case 106 /* TrueKeyword */:
95592                     case 104 /* ThisKeyword */:
95593                     case 96 /* ImportKeyword */:
95594                         writeTokenNode(node, writeKeyword);
95595                         return;
95596                     // Expressions
95597                     case 192 /* ArrayLiteralExpression */:
95598                         return emitArrayLiteralExpression(node);
95599                     case 193 /* ObjectLiteralExpression */:
95600                         return emitObjectLiteralExpression(node);
95601                     case 194 /* PropertyAccessExpression */:
95602                         return emitPropertyAccessExpression(node);
95603                     case 195 /* ElementAccessExpression */:
95604                         return emitElementAccessExpression(node);
95605                     case 196 /* CallExpression */:
95606                         return emitCallExpression(node);
95607                     case 197 /* NewExpression */:
95608                         return emitNewExpression(node);
95609                     case 198 /* TaggedTemplateExpression */:
95610                         return emitTaggedTemplateExpression(node);
95611                     case 199 /* TypeAssertionExpression */:
95612                         return emitTypeAssertionExpression(node);
95613                     case 200 /* ParenthesizedExpression */:
95614                         return emitParenthesizedExpression(node);
95615                     case 201 /* FunctionExpression */:
95616                         return emitFunctionExpression(node);
95617                     case 202 /* ArrowFunction */:
95618                         return emitArrowFunction(node);
95619                     case 203 /* DeleteExpression */:
95620                         return emitDeleteExpression(node);
95621                     case 204 /* TypeOfExpression */:
95622                         return emitTypeOfExpression(node);
95623                     case 205 /* VoidExpression */:
95624                         return emitVoidExpression(node);
95625                     case 206 /* AwaitExpression */:
95626                         return emitAwaitExpression(node);
95627                     case 207 /* PrefixUnaryExpression */:
95628                         return emitPrefixUnaryExpression(node);
95629                     case 208 /* PostfixUnaryExpression */:
95630                         return emitPostfixUnaryExpression(node);
95631                     case 209 /* BinaryExpression */:
95632                         return emitBinaryExpression(node);
95633                     case 210 /* ConditionalExpression */:
95634                         return emitConditionalExpression(node);
95635                     case 211 /* TemplateExpression */:
95636                         return emitTemplateExpression(node);
95637                     case 212 /* YieldExpression */:
95638                         return emitYieldExpression(node);
95639                     case 213 /* SpreadElement */:
95640                         return emitSpreadExpression(node);
95641                     case 214 /* ClassExpression */:
95642                         return emitClassExpression(node);
95643                     case 215 /* OmittedExpression */:
95644                         return;
95645                     case 217 /* AsExpression */:
95646                         return emitAsExpression(node);
95647                     case 218 /* NonNullExpression */:
95648                         return emitNonNullExpression(node);
95649                     case 219 /* MetaProperty */:
95650                         return emitMetaProperty(node);
95651                     // JSX
95652                     case 266 /* JsxElement */:
95653                         return emitJsxElement(node);
95654                     case 267 /* JsxSelfClosingElement */:
95655                         return emitJsxSelfClosingElement(node);
95656                     case 270 /* JsxFragment */:
95657                         return emitJsxFragment(node);
95658                     // Transformation nodes
95659                     case 326 /* PartiallyEmittedExpression */:
95660                         return emitPartiallyEmittedExpression(node);
95661                     case 327 /* CommaListExpression */:
95662                         return emitCommaList(node);
95663                 }
95664             }
95665         }
95666         function emitMappedTypeParameter(node) {
95667             emit(node.name);
95668             writeSpace();
95669             writeKeyword("in");
95670             writeSpace();
95671             emit(node.constraint);
95672         }
95673         function pipelineEmitWithSubstitution(hint, node) {
95674             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95675             var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
95676             pipelinePhase(hint, lastSubstitution);
95677             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95678         }
95679         function getHelpersFromBundledSourceFiles(bundle) {
95680             var result;
95681             if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
95682                 return undefined;
95683             }
95684             var bundledHelpers = ts.createMap();
95685             for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
95686                 var sourceFile = _b[_a];
95687                 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
95688                 var helpers = getSortedEmitHelpers(sourceFile);
95689                 if (!helpers)
95690                     continue;
95691                 for (var _c = 0, helpers_4 = helpers; _c < helpers_4.length; _c++) {
95692                     var helper = helpers_4[_c];
95693                     if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
95694                         bundledHelpers.set(helper.name, true);
95695                         (result || (result = [])).push(helper.name);
95696                     }
95697                 }
95698             }
95699             return result;
95700         }
95701         function emitHelpers(node) {
95702             var helpersEmitted = false;
95703             var bundle = node.kind === 291 /* Bundle */ ? node : undefined;
95704             if (bundle && moduleKind === ts.ModuleKind.None) {
95705                 return;
95706             }
95707             var numPrepends = bundle ? bundle.prepends.length : 0;
95708             var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
95709             for (var i = 0; i < numNodes; i++) {
95710                 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
95711                 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
95712                 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
95713                 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
95714                 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
95715                 if (helpers) {
95716                     for (var _a = 0, helpers_5 = helpers; _a < helpers_5.length; _a++) {
95717                         var helper = helpers_5[_a];
95718                         if (!helper.scoped) {
95719                             // Skip the helper if it can be skipped and the noEmitHelpers compiler
95720                             // option is set, or if it can be imported and the importHelpers compiler
95721                             // option is set.
95722                             if (shouldSkip)
95723                                 continue;
95724                             // Skip the helper if it can be bundled but hasn't already been emitted and we
95725                             // are emitting a bundled module.
95726                             if (shouldBundle) {
95727                                 if (bundledHelpers.get(helper.name)) {
95728                                     continue;
95729                                 }
95730                                 bundledHelpers.set(helper.name, true);
95731                             }
95732                         }
95733                         else if (bundle) {
95734                             // Skip the helper if it is scoped and we are emitting bundled helpers
95735                             continue;
95736                         }
95737                         var pos = getTextPosWithWriteLine();
95738                         if (typeof helper.text === "string") {
95739                             writeLines(helper.text);
95740                         }
95741                         else {
95742                             writeLines(helper.text(makeFileLevelOptimisticUniqueName));
95743                         }
95744                         if (bundleFileInfo)
95745                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
95746                         helpersEmitted = true;
95747                     }
95748                 }
95749             }
95750             return helpersEmitted;
95751         }
95752         function getSortedEmitHelpers(node) {
95753             var helpers = ts.getEmitHelpers(node);
95754             return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
95755         }
95756         //
95757         // Literals/Pseudo-literals
95758         //
95759         // SyntaxKind.NumericLiteral
95760         // SyntaxKind.BigIntLiteral
95761         function emitNumericOrBigIntLiteral(node) {
95762             emitLiteral(node, /*jsxAttributeEscape*/ false);
95763         }
95764         // SyntaxKind.StringLiteral
95765         // SyntaxKind.RegularExpressionLiteral
95766         // SyntaxKind.NoSubstitutionTemplateLiteral
95767         // SyntaxKind.TemplateHead
95768         // SyntaxKind.TemplateMiddle
95769         // SyntaxKind.TemplateTail
95770         function emitLiteral(node, jsxAttributeEscape) {
95771             var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
95772             if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
95773                 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
95774                 writeLiteral(text);
95775             }
95776             else {
95777                 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
95778                 writeStringLiteral(text);
95779             }
95780         }
95781         // SyntaxKind.UnparsedSource
95782         // SyntaxKind.UnparsedPrepend
95783         function emitUnparsedSourceOrPrepend(unparsed) {
95784             for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
95785                 var text = _b[_a];
95786                 writeLine();
95787                 emit(text);
95788             }
95789         }
95790         // SyntaxKind.UnparsedPrologue
95791         // SyntaxKind.UnparsedText
95792         // SyntaxKind.UnparsedInternal
95793         // SyntaxKind.UnparsedSyntheticReference
95794         function writeUnparsedNode(unparsed) {
95795             writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
95796         }
95797         // SyntaxKind.UnparsedText
95798         // SyntaxKind.UnparsedInternal
95799         function emitUnparsedTextLike(unparsed) {
95800             var pos = getTextPosWithWriteLine();
95801             writeUnparsedNode(unparsed);
95802             if (bundleFileInfo) {
95803                 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 287 /* UnparsedText */ ?
95804                     "text" /* Text */ :
95805                     "internal" /* Internal */);
95806             }
95807         }
95808         // SyntaxKind.UnparsedSyntheticReference
95809         function emitUnparsedSyntheticReference(unparsed) {
95810             var pos = getTextPosWithWriteLine();
95811             writeUnparsedNode(unparsed);
95812             if (bundleFileInfo) {
95813                 var section = ts.clone(unparsed.section);
95814                 section.pos = pos;
95815                 section.end = writer.getTextPos();
95816                 bundleFileInfo.sections.push(section);
95817             }
95818         }
95819         //
95820         // Identifiers
95821         //
95822         function emitIdentifier(node) {
95823             var writeText = node.symbol ? writeSymbol : write;
95824             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95825             emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
95826         }
95827         //
95828         // Names
95829         //
95830         function emitPrivateIdentifier(node) {
95831             var writeText = node.symbol ? writeSymbol : write;
95832             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95833         }
95834         function emitQualifiedName(node) {
95835             emitEntityName(node.left);
95836             writePunctuation(".");
95837             emit(node.right);
95838         }
95839         function emitEntityName(node) {
95840             if (node.kind === 75 /* Identifier */) {
95841                 emitExpression(node);
95842             }
95843             else {
95844                 emit(node);
95845             }
95846         }
95847         function emitComputedPropertyName(node) {
95848             writePunctuation("[");
95849             emitExpression(node.expression);
95850             writePunctuation("]");
95851         }
95852         //
95853         // Signature elements
95854         //
95855         function emitTypeParameter(node) {
95856             emit(node.name);
95857             if (node.constraint) {
95858                 writeSpace();
95859                 writeKeyword("extends");
95860                 writeSpace();
95861                 emit(node.constraint);
95862             }
95863             if (node.default) {
95864                 writeSpace();
95865                 writeOperator("=");
95866                 writeSpace();
95867                 emit(node.default);
95868             }
95869         }
95870         function emitParameter(node) {
95871             emitDecorators(node, node.decorators);
95872             emitModifiers(node, node.modifiers);
95873             emit(node.dotDotDotToken);
95874             emitNodeWithWriter(node.name, writeParameter);
95875             emit(node.questionToken);
95876             if (node.parent && node.parent.kind === 300 /* JSDocFunctionType */ && !node.name) {
95877                 emit(node.type);
95878             }
95879             else {
95880                 emitTypeAnnotation(node.type);
95881             }
95882             // 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.
95883             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);
95884         }
95885         function emitDecorator(decorator) {
95886             writePunctuation("@");
95887             emitExpression(decorator.expression);
95888         }
95889         //
95890         // Type members
95891         //
95892         function emitPropertySignature(node) {
95893             emitDecorators(node, node.decorators);
95894             emitModifiers(node, node.modifiers);
95895             emitNodeWithWriter(node.name, writeProperty);
95896             emit(node.questionToken);
95897             emitTypeAnnotation(node.type);
95898             writeTrailingSemicolon();
95899         }
95900         function emitPropertyDeclaration(node) {
95901             emitDecorators(node, node.decorators);
95902             emitModifiers(node, node.modifiers);
95903             emit(node.name);
95904             emit(node.questionToken);
95905             emit(node.exclamationToken);
95906             emitTypeAnnotation(node.type);
95907             emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
95908             writeTrailingSemicolon();
95909         }
95910         function emitMethodSignature(node) {
95911             pushNameGenerationScope(node);
95912             emitDecorators(node, node.decorators);
95913             emitModifiers(node, node.modifiers);
95914             emit(node.name);
95915             emit(node.questionToken);
95916             emitTypeParameters(node, node.typeParameters);
95917             emitParameters(node, node.parameters);
95918             emitTypeAnnotation(node.type);
95919             writeTrailingSemicolon();
95920             popNameGenerationScope(node);
95921         }
95922         function emitMethodDeclaration(node) {
95923             emitDecorators(node, node.decorators);
95924             emitModifiers(node, node.modifiers);
95925             emit(node.asteriskToken);
95926             emit(node.name);
95927             emit(node.questionToken);
95928             emitSignatureAndBody(node, emitSignatureHead);
95929         }
95930         function emitConstructor(node) {
95931             emitModifiers(node, node.modifiers);
95932             writeKeyword("constructor");
95933             emitSignatureAndBody(node, emitSignatureHead);
95934         }
95935         function emitAccessorDeclaration(node) {
95936             emitDecorators(node, node.decorators);
95937             emitModifiers(node, node.modifiers);
95938             writeKeyword(node.kind === 163 /* GetAccessor */ ? "get" : "set");
95939             writeSpace();
95940             emit(node.name);
95941             emitSignatureAndBody(node, emitSignatureHead);
95942         }
95943         function emitCallSignature(node) {
95944             pushNameGenerationScope(node);
95945             emitDecorators(node, node.decorators);
95946             emitModifiers(node, node.modifiers);
95947             emitTypeParameters(node, node.typeParameters);
95948             emitParameters(node, node.parameters);
95949             emitTypeAnnotation(node.type);
95950             writeTrailingSemicolon();
95951             popNameGenerationScope(node);
95952         }
95953         function emitConstructSignature(node) {
95954             pushNameGenerationScope(node);
95955             emitDecorators(node, node.decorators);
95956             emitModifiers(node, node.modifiers);
95957             writeKeyword("new");
95958             writeSpace();
95959             emitTypeParameters(node, node.typeParameters);
95960             emitParameters(node, node.parameters);
95961             emitTypeAnnotation(node.type);
95962             writeTrailingSemicolon();
95963             popNameGenerationScope(node);
95964         }
95965         function emitIndexSignature(node) {
95966             emitDecorators(node, node.decorators);
95967             emitModifiers(node, node.modifiers);
95968             emitParametersForIndexSignature(node, node.parameters);
95969             emitTypeAnnotation(node.type);
95970             writeTrailingSemicolon();
95971         }
95972         function emitSemicolonClassElement() {
95973             writeTrailingSemicolon();
95974         }
95975         //
95976         // Types
95977         //
95978         function emitTypePredicate(node) {
95979             if (node.assertsModifier) {
95980                 emit(node.assertsModifier);
95981                 writeSpace();
95982             }
95983             emit(node.parameterName);
95984             if (node.type) {
95985                 writeSpace();
95986                 writeKeyword("is");
95987                 writeSpace();
95988                 emit(node.type);
95989             }
95990         }
95991         function emitTypeReference(node) {
95992             emit(node.typeName);
95993             emitTypeArguments(node, node.typeArguments);
95994         }
95995         function emitFunctionType(node) {
95996             pushNameGenerationScope(node);
95997             emitTypeParameters(node, node.typeParameters);
95998             emitParametersForArrow(node, node.parameters);
95999             writeSpace();
96000             writePunctuation("=>");
96001             writeSpace();
96002             emit(node.type);
96003             popNameGenerationScope(node);
96004         }
96005         function emitJSDocFunctionType(node) {
96006             writeKeyword("function");
96007             emitParameters(node, node.parameters);
96008             writePunctuation(":");
96009             emit(node.type);
96010         }
96011         function emitJSDocNullableType(node) {
96012             writePunctuation("?");
96013             emit(node.type);
96014         }
96015         function emitJSDocNonNullableType(node) {
96016             writePunctuation("!");
96017             emit(node.type);
96018         }
96019         function emitJSDocOptionalType(node) {
96020             emit(node.type);
96021             writePunctuation("=");
96022         }
96023         function emitConstructorType(node) {
96024             pushNameGenerationScope(node);
96025             writeKeyword("new");
96026             writeSpace();
96027             emitTypeParameters(node, node.typeParameters);
96028             emitParameters(node, node.parameters);
96029             writeSpace();
96030             writePunctuation("=>");
96031             writeSpace();
96032             emit(node.type);
96033             popNameGenerationScope(node);
96034         }
96035         function emitTypeQuery(node) {
96036             writeKeyword("typeof");
96037             writeSpace();
96038             emit(node.exprName);
96039         }
96040         function emitTypeLiteral(node) {
96041             writePunctuation("{");
96042             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
96043             emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
96044             writePunctuation("}");
96045         }
96046         function emitArrayType(node) {
96047             emit(node.elementType);
96048             writePunctuation("[");
96049             writePunctuation("]");
96050         }
96051         function emitRestOrJSDocVariadicType(node) {
96052             writePunctuation("...");
96053             emit(node.type);
96054         }
96055         function emitTupleType(node) {
96056             writePunctuation("[");
96057             emitList(node, node.elementTypes, 528 /* TupleTypeElements */);
96058             writePunctuation("]");
96059         }
96060         function emitOptionalType(node) {
96061             emit(node.type);
96062             writePunctuation("?");
96063         }
96064         function emitUnionType(node) {
96065             emitList(node, node.types, 516 /* UnionTypeConstituents */);
96066         }
96067         function emitIntersectionType(node) {
96068             emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
96069         }
96070         function emitConditionalType(node) {
96071             emit(node.checkType);
96072             writeSpace();
96073             writeKeyword("extends");
96074             writeSpace();
96075             emit(node.extendsType);
96076             writeSpace();
96077             writePunctuation("?");
96078             writeSpace();
96079             emit(node.trueType);
96080             writeSpace();
96081             writePunctuation(":");
96082             writeSpace();
96083             emit(node.falseType);
96084         }
96085         function emitInferType(node) {
96086             writeKeyword("infer");
96087             writeSpace();
96088             emit(node.typeParameter);
96089         }
96090         function emitParenthesizedType(node) {
96091             writePunctuation("(");
96092             emit(node.type);
96093             writePunctuation(")");
96094         }
96095         function emitThisType() {
96096             writeKeyword("this");
96097         }
96098         function emitTypeOperator(node) {
96099             writeTokenText(node.operator, writeKeyword);
96100             writeSpace();
96101             emit(node.type);
96102         }
96103         function emitIndexedAccessType(node) {
96104             emit(node.objectType);
96105             writePunctuation("[");
96106             emit(node.indexType);
96107             writePunctuation("]");
96108         }
96109         function emitMappedType(node) {
96110             var emitFlags = ts.getEmitFlags(node);
96111             writePunctuation("{");
96112             if (emitFlags & 1 /* SingleLine */) {
96113                 writeSpace();
96114             }
96115             else {
96116                 writeLine();
96117                 increaseIndent();
96118             }
96119             if (node.readonlyToken) {
96120                 emit(node.readonlyToken);
96121                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
96122                     writeKeyword("readonly");
96123                 }
96124                 writeSpace();
96125             }
96126             writePunctuation("[");
96127             pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
96128             writePunctuation("]");
96129             if (node.questionToken) {
96130                 emit(node.questionToken);
96131                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
96132                     writePunctuation("?");
96133                 }
96134             }
96135             writePunctuation(":");
96136             writeSpace();
96137             emit(node.type);
96138             writeTrailingSemicolon();
96139             if (emitFlags & 1 /* SingleLine */) {
96140                 writeSpace();
96141             }
96142             else {
96143                 writeLine();
96144                 decreaseIndent();
96145             }
96146             writePunctuation("}");
96147         }
96148         function emitLiteralType(node) {
96149             emitExpression(node.literal);
96150         }
96151         function emitImportTypeNode(node) {
96152             if (node.isTypeOf) {
96153                 writeKeyword("typeof");
96154                 writeSpace();
96155             }
96156             writeKeyword("import");
96157             writePunctuation("(");
96158             emit(node.argument);
96159             writePunctuation(")");
96160             if (node.qualifier) {
96161                 writePunctuation(".");
96162                 emit(node.qualifier);
96163             }
96164             emitTypeArguments(node, node.typeArguments);
96165         }
96166         //
96167         // Binding patterns
96168         //
96169         function emitObjectBindingPattern(node) {
96170             writePunctuation("{");
96171             emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
96172             writePunctuation("}");
96173         }
96174         function emitArrayBindingPattern(node) {
96175             writePunctuation("[");
96176             emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
96177             writePunctuation("]");
96178         }
96179         function emitBindingElement(node) {
96180             emit(node.dotDotDotToken);
96181             if (node.propertyName) {
96182                 emit(node.propertyName);
96183                 writePunctuation(":");
96184                 writeSpace();
96185             }
96186             emit(node.name);
96187             emitInitializer(node.initializer, node.name.end, node);
96188         }
96189         //
96190         // Expressions
96191         //
96192         function emitArrayLiteralExpression(node) {
96193             var elements = node.elements;
96194             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96195             emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
96196         }
96197         function emitObjectLiteralExpression(node) {
96198             ts.forEach(node.properties, generateMemberNames);
96199             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96200             if (indentedFlag) {
96201                 increaseIndent();
96202             }
96203             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96204             var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
96205             emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
96206             if (indentedFlag) {
96207                 decreaseIndent();
96208             }
96209         }
96210         function emitPropertyAccessExpression(node) {
96211             var expression = ts.cast(emitExpression(node.expression), ts.isExpression);
96212             var token = node.questionDotToken || ts.createNode(24 /* DotToken */, node.expression.end, node.name.pos);
96213             var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
96214             var linesAfterDot = getLinesBetweenNodes(node, token, node.name);
96215             writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false);
96216             var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
96217                 mayNeedDotDotForPropertyAccess(expression) &&
96218                 !writer.hasTrailingComment() &&
96219                 !writer.hasTrailingWhitespace();
96220             if (shouldEmitDotDot) {
96221                 writePunctuation(".");
96222             }
96223             if (node.questionDotToken) {
96224                 emit(token);
96225             }
96226             else {
96227                 emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
96228             }
96229             writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false);
96230             emit(node.name);
96231             decreaseIndentIf(linesBeforeDot, linesAfterDot);
96232         }
96233         // 1..toString is a valid property access, emit a dot after the literal
96234         // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
96235         function mayNeedDotDotForPropertyAccess(expression) {
96236             expression = ts.skipPartiallyEmittedExpressions(expression);
96237             if (ts.isNumericLiteral(expression)) {
96238                 // check if numeric literal is a decimal literal that was originally written with a dot
96239                 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
96240                 // If he number will be printed verbatim and it doesn't already contain a dot, add one
96241                 // if the expression doesn't have any comments that will be emitted.
96242                 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
96243             }
96244             else if (ts.isAccessExpression(expression)) {
96245                 // check if constant enum value is integer
96246                 var constantValue = ts.getConstantValue(expression);
96247                 // isFinite handles cases when constantValue is undefined
96248                 return typeof constantValue === "number" && isFinite(constantValue)
96249                     && Math.floor(constantValue) === constantValue;
96250             }
96251         }
96252         function emitElementAccessExpression(node) {
96253             emitExpression(node.expression);
96254             emit(node.questionDotToken);
96255             emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
96256             emitExpression(node.argumentExpression);
96257             emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
96258         }
96259         function emitCallExpression(node) {
96260             emitExpression(node.expression);
96261             emit(node.questionDotToken);
96262             emitTypeArguments(node, node.typeArguments);
96263             emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
96264         }
96265         function emitNewExpression(node) {
96266             emitTokenWithComment(99 /* NewKeyword */, node.pos, writeKeyword, node);
96267             writeSpace();
96268             emitExpression(node.expression);
96269             emitTypeArguments(node, node.typeArguments);
96270             emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
96271         }
96272         function emitTaggedTemplateExpression(node) {
96273             emitExpression(node.tag);
96274             emitTypeArguments(node, node.typeArguments);
96275             writeSpace();
96276             emitExpression(node.template);
96277         }
96278         function emitTypeAssertionExpression(node) {
96279             writePunctuation("<");
96280             emit(node.type);
96281             writePunctuation(">");
96282             emitExpression(node.expression);
96283         }
96284         function emitParenthesizedExpression(node) {
96285             var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
96286             var indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
96287             emitExpression(node.expression);
96288             writeLineSeparatorsAfter(node.expression, node);
96289             decreaseIndentIf(indented);
96290             emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
96291         }
96292         function emitFunctionExpression(node) {
96293             generateNameIfNeeded(node.name);
96294             emitFunctionDeclarationOrExpression(node);
96295         }
96296         function emitArrowFunction(node) {
96297             emitDecorators(node, node.decorators);
96298             emitModifiers(node, node.modifiers);
96299             emitSignatureAndBody(node, emitArrowFunctionHead);
96300         }
96301         function emitArrowFunctionHead(node) {
96302             emitTypeParameters(node, node.typeParameters);
96303             emitParametersForArrow(node, node.parameters);
96304             emitTypeAnnotation(node.type);
96305             writeSpace();
96306             emit(node.equalsGreaterThanToken);
96307         }
96308         function emitDeleteExpression(node) {
96309             emitTokenWithComment(85 /* DeleteKeyword */, node.pos, writeKeyword, node);
96310             writeSpace();
96311             emitExpression(node.expression);
96312         }
96313         function emitTypeOfExpression(node) {
96314             emitTokenWithComment(108 /* TypeOfKeyword */, node.pos, writeKeyword, node);
96315             writeSpace();
96316             emitExpression(node.expression);
96317         }
96318         function emitVoidExpression(node) {
96319             emitTokenWithComment(110 /* VoidKeyword */, node.pos, writeKeyword, node);
96320             writeSpace();
96321             emitExpression(node.expression);
96322         }
96323         function emitAwaitExpression(node) {
96324             emitTokenWithComment(127 /* AwaitKeyword */, node.pos, writeKeyword, node);
96325             writeSpace();
96326             emitExpression(node.expression);
96327         }
96328         function emitPrefixUnaryExpression(node) {
96329             writeTokenText(node.operator, writeOperator);
96330             if (shouldEmitWhitespaceBeforeOperand(node)) {
96331                 writeSpace();
96332             }
96333             emitExpression(node.operand);
96334         }
96335         function shouldEmitWhitespaceBeforeOperand(node) {
96336             // In some cases, we need to emit a space between the operator and the operand. One obvious case
96337             // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
96338             // and minus expressions in certain cases. Specifically, consider the following two cases (parens
96339             // are just for clarity of exposition, and not part of the source code):
96340             //
96341             //  (+(+1))
96342             //  (+(++1))
96343             //
96344             // We need to emit a space in both cases. In the first case, the absence of a space will make
96345             // the resulting expression a prefix increment operation. And in the second, it will make the resulting
96346             // expression a prefix increment whose operand is a plus expression - (++(+x))
96347             // The same is true of minus of course.
96348             var operand = node.operand;
96349             return operand.kind === 207 /* PrefixUnaryExpression */
96350                 && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
96351                     || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
96352         }
96353         function emitPostfixUnaryExpression(node) {
96354             emitExpression(node.operand);
96355             writeTokenText(node.operator, writeOperator);
96356         }
96357         var EmitBinaryExpressionState;
96358         (function (EmitBinaryExpressionState) {
96359             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft";
96360             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight";
96361             EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit";
96362         })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {}));
96363         /**
96364          * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
96365          * as possible without creating any additional stack frames. This can only be done when the emit pipeline does
96366          * not require notification/substitution/comment/sourcemap decorations.
96367          */
96368         function emitBinaryExpression(node) {
96369             var nodeStack = [node];
96370             var stateStack = [0 /* EmitLeft */];
96371             var stackIndex = 0;
96372             while (stackIndex >= 0) {
96373                 node = nodeStack[stackIndex];
96374                 switch (stateStack[stackIndex]) {
96375                     case 0 /* EmitLeft */: {
96376                         maybePipelineEmitExpression(node.left);
96377                         break;
96378                     }
96379                     case 1 /* EmitRight */: {
96380                         var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
96381                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96382                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96383                         writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
96384                         emitLeadingCommentsOfPosition(node.operatorToken.pos);
96385                         writeTokenNode(node.operatorToken, node.operatorToken.kind === 97 /* InKeyword */ ? writeKeyword : writeOperator);
96386                         emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
96387                         writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true);
96388                         maybePipelineEmitExpression(node.right);
96389                         break;
96390                     }
96391                     case 2 /* FinishEmit */: {
96392                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96393                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96394                         decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
96395                         stackIndex--;
96396                         break;
96397                     }
96398                     default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker");
96399                 }
96400             }
96401             function maybePipelineEmitExpression(next) {
96402                 // Advance the state of this unit of work,
96403                 stateStack[stackIndex]++;
96404                 // Then actually do the work of emitting the node `next` returned by the prior state
96405                 // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
96406                 // binary expression handling, where possible, to the contained work queue
96407                 // #region trampolinePipelineEmit
96408                 var savedLastNode = lastNode;
96409                 var savedLastSubstitution = lastSubstitution;
96410                 lastNode = next;
96411                 lastSubstitution = undefined;
96412                 var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
96413                 if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) {
96414                     // If the target pipeline phase is emit directly, and the next node's also a binary expression,
96415                     // skip all the intermediate indirection and push the expression directly onto the work stack
96416                     stackIndex++;
96417                     stateStack[stackIndex] = 0 /* EmitLeft */;
96418                     nodeStack[stackIndex] = next;
96419                 }
96420                 else {
96421                     pipelinePhase(1 /* Expression */, next);
96422                 }
96423                 ts.Debug.assert(lastNode === next);
96424                 lastNode = savedLastNode;
96425                 lastSubstitution = savedLastSubstitution;
96426                 // #endregion trampolinePipelineEmit
96427             }
96428         }
96429         function emitConditionalExpression(node) {
96430             var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
96431             var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
96432             var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
96433             var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
96434             emitExpression(node.condition);
96435             writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
96436             emit(node.questionToken);
96437             writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
96438             emitExpression(node.whenTrue);
96439             decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
96440             writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true);
96441             emit(node.colonToken);
96442             writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true);
96443             emitExpression(node.whenFalse);
96444             decreaseIndentIf(linesBeforeColon, linesAfterColon);
96445         }
96446         function emitTemplateExpression(node) {
96447             emit(node.head);
96448             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
96449         }
96450         function emitYieldExpression(node) {
96451             emitTokenWithComment(121 /* YieldKeyword */, node.pos, writeKeyword, node);
96452             emit(node.asteriskToken);
96453             emitExpressionWithLeadingSpace(node.expression);
96454         }
96455         function emitSpreadExpression(node) {
96456             emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
96457             emitExpression(node.expression);
96458         }
96459         function emitClassExpression(node) {
96460             generateNameIfNeeded(node.name);
96461             emitClassDeclarationOrExpression(node);
96462         }
96463         function emitExpressionWithTypeArguments(node) {
96464             emitExpression(node.expression);
96465             emitTypeArguments(node, node.typeArguments);
96466         }
96467         function emitAsExpression(node) {
96468             emitExpression(node.expression);
96469             if (node.type) {
96470                 writeSpace();
96471                 writeKeyword("as");
96472                 writeSpace();
96473                 emit(node.type);
96474             }
96475         }
96476         function emitNonNullExpression(node) {
96477             emitExpression(node.expression);
96478             writeOperator("!");
96479         }
96480         function emitMetaProperty(node) {
96481             writeToken(node.keywordToken, node.pos, writePunctuation);
96482             writePunctuation(".");
96483             emit(node.name);
96484         }
96485         //
96486         // Misc
96487         //
96488         function emitTemplateSpan(node) {
96489             emitExpression(node.expression);
96490             emit(node.literal);
96491         }
96492         //
96493         // Statements
96494         //
96495         function emitBlock(node) {
96496             emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
96497         }
96498         function emitBlockStatements(node, forceSingleLine) {
96499             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
96500             var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
96501             emitList(node, node.statements, format);
96502             emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
96503         }
96504         function emitVariableStatement(node) {
96505             emitModifiers(node, node.modifiers);
96506             emit(node.declarationList);
96507             writeTrailingSemicolon();
96508         }
96509         function emitEmptyStatement(isEmbeddedStatement) {
96510             // While most trailing semicolons are possibly insignificant, an embedded "empty"
96511             // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
96512             if (isEmbeddedStatement) {
96513                 writePunctuation(";");
96514             }
96515             else {
96516                 writeTrailingSemicolon();
96517             }
96518         }
96519         function emitExpressionStatement(node) {
96520             emitExpression(node.expression);
96521             // Emit semicolon in non json files
96522             // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
96523             if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
96524                 writeTrailingSemicolon();
96525             }
96526         }
96527         function emitIfStatement(node) {
96528             var openParenPos = emitTokenWithComment(95 /* IfKeyword */, node.pos, writeKeyword, node);
96529             writeSpace();
96530             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96531             emitExpression(node.expression);
96532             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96533             emitEmbeddedStatement(node, node.thenStatement);
96534             if (node.elseStatement) {
96535                 writeLineOrSpace(node);
96536                 emitTokenWithComment(87 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
96537                 if (node.elseStatement.kind === 227 /* IfStatement */) {
96538                     writeSpace();
96539                     emit(node.elseStatement);
96540                 }
96541                 else {
96542                     emitEmbeddedStatement(node, node.elseStatement);
96543                 }
96544             }
96545         }
96546         function emitWhileClause(node, startPos) {
96547             var openParenPos = emitTokenWithComment(111 /* WhileKeyword */, startPos, writeKeyword, node);
96548             writeSpace();
96549             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96550             emitExpression(node.expression);
96551             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96552         }
96553         function emitDoStatement(node) {
96554             emitTokenWithComment(86 /* DoKeyword */, node.pos, writeKeyword, node);
96555             emitEmbeddedStatement(node, node.statement);
96556             if (ts.isBlock(node.statement)) {
96557                 writeSpace();
96558             }
96559             else {
96560                 writeLineOrSpace(node);
96561             }
96562             emitWhileClause(node, node.statement.end);
96563             writeTrailingSemicolon();
96564         }
96565         function emitWhileStatement(node) {
96566             emitWhileClause(node, node.pos);
96567             emitEmbeddedStatement(node, node.statement);
96568         }
96569         function emitForStatement(node) {
96570             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96571             writeSpace();
96572             var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
96573             emitForBinding(node.initializer);
96574             pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
96575             emitExpressionWithLeadingSpace(node.condition);
96576             pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
96577             emitExpressionWithLeadingSpace(node.incrementor);
96578             emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
96579             emitEmbeddedStatement(node, node.statement);
96580         }
96581         function emitForInStatement(node) {
96582             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96583             writeSpace();
96584             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96585             emitForBinding(node.initializer);
96586             writeSpace();
96587             emitTokenWithComment(97 /* InKeyword */, node.initializer.end, writeKeyword, node);
96588             writeSpace();
96589             emitExpression(node.expression);
96590             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96591             emitEmbeddedStatement(node, node.statement);
96592         }
96593         function emitForOfStatement(node) {
96594             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96595             writeSpace();
96596             emitWithTrailingSpace(node.awaitModifier);
96597             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96598             emitForBinding(node.initializer);
96599             writeSpace();
96600             emitTokenWithComment(152 /* OfKeyword */, node.initializer.end, writeKeyword, node);
96601             writeSpace();
96602             emitExpression(node.expression);
96603             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96604             emitEmbeddedStatement(node, node.statement);
96605         }
96606         function emitForBinding(node) {
96607             if (node !== undefined) {
96608                 if (node.kind === 243 /* VariableDeclarationList */) {
96609                     emit(node);
96610                 }
96611                 else {
96612                     emitExpression(node);
96613                 }
96614             }
96615         }
96616         function emitContinueStatement(node) {
96617             emitTokenWithComment(82 /* ContinueKeyword */, node.pos, writeKeyword, node);
96618             emitWithLeadingSpace(node.label);
96619             writeTrailingSemicolon();
96620         }
96621         function emitBreakStatement(node) {
96622             emitTokenWithComment(77 /* BreakKeyword */, node.pos, writeKeyword, node);
96623             emitWithLeadingSpace(node.label);
96624             writeTrailingSemicolon();
96625         }
96626         function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
96627             var node = ts.getParseTreeNode(contextNode);
96628             var isSimilarNode = node && node.kind === contextNode.kind;
96629             var startPos = pos;
96630             if (isSimilarNode && currentSourceFile) {
96631                 pos = ts.skipTrivia(currentSourceFile.text, pos);
96632             }
96633             if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
96634                 var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
96635                 if (needsIndent) {
96636                     increaseIndent();
96637                 }
96638                 emitLeadingCommentsOfPosition(startPos);
96639                 if (needsIndent) {
96640                     decreaseIndent();
96641                 }
96642             }
96643             pos = writeTokenText(token, writer, pos);
96644             if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
96645                 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
96646             }
96647             return pos;
96648         }
96649         function emitReturnStatement(node) {
96650             emitTokenWithComment(101 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
96651             emitExpressionWithLeadingSpace(node.expression);
96652             writeTrailingSemicolon();
96653         }
96654         function emitWithStatement(node) {
96655             var openParenPos = emitTokenWithComment(112 /* WithKeyword */, node.pos, writeKeyword, node);
96656             writeSpace();
96657             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96658             emitExpression(node.expression);
96659             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96660             emitEmbeddedStatement(node, node.statement);
96661         }
96662         function emitSwitchStatement(node) {
96663             var openParenPos = emitTokenWithComment(103 /* SwitchKeyword */, node.pos, writeKeyword, node);
96664             writeSpace();
96665             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96666             emitExpression(node.expression);
96667             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96668             writeSpace();
96669             emit(node.caseBlock);
96670         }
96671         function emitLabeledStatement(node) {
96672             emit(node.label);
96673             emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
96674             writeSpace();
96675             emit(node.statement);
96676         }
96677         function emitThrowStatement(node) {
96678             emitTokenWithComment(105 /* ThrowKeyword */, node.pos, writeKeyword, node);
96679             emitExpressionWithLeadingSpace(node.expression);
96680             writeTrailingSemicolon();
96681         }
96682         function emitTryStatement(node) {
96683             emitTokenWithComment(107 /* TryKeyword */, node.pos, writeKeyword, node);
96684             writeSpace();
96685             emit(node.tryBlock);
96686             if (node.catchClause) {
96687                 writeLineOrSpace(node);
96688                 emit(node.catchClause);
96689             }
96690             if (node.finallyBlock) {
96691                 writeLineOrSpace(node);
96692                 emitTokenWithComment(92 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
96693                 writeSpace();
96694                 emit(node.finallyBlock);
96695             }
96696         }
96697         function emitDebuggerStatement(node) {
96698             writeToken(83 /* DebuggerKeyword */, node.pos, writeKeyword);
96699             writeTrailingSemicolon();
96700         }
96701         //
96702         // Declarations
96703         //
96704         function emitVariableDeclaration(node) {
96705             emit(node.name);
96706             emit(node.exclamationToken);
96707             emitTypeAnnotation(node.type);
96708             emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
96709         }
96710         function emitVariableDeclarationList(node) {
96711             writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
96712             writeSpace();
96713             emitList(node, node.declarations, 528 /* VariableDeclarationList */);
96714         }
96715         function emitFunctionDeclaration(node) {
96716             emitFunctionDeclarationOrExpression(node);
96717         }
96718         function emitFunctionDeclarationOrExpression(node) {
96719             emitDecorators(node, node.decorators);
96720             emitModifiers(node, node.modifiers);
96721             writeKeyword("function");
96722             emit(node.asteriskToken);
96723             writeSpace();
96724             emitIdentifierName(node.name);
96725             emitSignatureAndBody(node, emitSignatureHead);
96726         }
96727         function emitBlockCallback(_hint, body) {
96728             emitBlockFunctionBody(body);
96729         }
96730         function emitSignatureAndBody(node, emitSignatureHead) {
96731             var body = node.body;
96732             if (body) {
96733                 if (ts.isBlock(body)) {
96734                     var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96735                     if (indentedFlag) {
96736                         increaseIndent();
96737                     }
96738                     pushNameGenerationScope(node);
96739                     ts.forEach(node.parameters, generateNames);
96740                     generateNames(node.body);
96741                     emitSignatureHead(node);
96742                     if (onEmitNode) {
96743                         onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
96744                     }
96745                     else {
96746                         emitBlockFunctionBody(body);
96747                     }
96748                     popNameGenerationScope(node);
96749                     if (indentedFlag) {
96750                         decreaseIndent();
96751                     }
96752                 }
96753                 else {
96754                     emitSignatureHead(node);
96755                     writeSpace();
96756                     emitExpression(body);
96757                 }
96758             }
96759             else {
96760                 emitSignatureHead(node);
96761                 writeTrailingSemicolon();
96762             }
96763         }
96764         function emitSignatureHead(node) {
96765             emitTypeParameters(node, node.typeParameters);
96766             emitParameters(node, node.parameters);
96767             emitTypeAnnotation(node.type);
96768         }
96769         function shouldEmitBlockFunctionBodyOnSingleLine(body) {
96770             // We must emit a function body as a single-line body in the following case:
96771             // * The body has NodeEmitFlags.SingleLine specified.
96772             // We must emit a function body as a multi-line body in the following cases:
96773             // * The body is explicitly marked as multi-line.
96774             // * A non-synthesized body's start and end position are on different lines.
96775             // * Any statement in the body starts on a new line.
96776             if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
96777                 return true;
96778             }
96779             if (body.multiLine) {
96780                 return false;
96781             }
96782             if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
96783                 return false;
96784             }
96785             if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)
96786                 || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) {
96787                 return false;
96788             }
96789             var previousStatement;
96790             for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
96791                 var statement = _b[_a];
96792                 if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
96793                     return false;
96794                 }
96795                 previousStatement = statement;
96796             }
96797             return true;
96798         }
96799         function emitBlockFunctionBody(body) {
96800             writeSpace();
96801             writePunctuation("{");
96802             increaseIndent();
96803             var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
96804                 ? emitBlockFunctionBodyOnSingleLine
96805                 : emitBlockFunctionBodyWorker;
96806             if (emitBodyWithDetachedComments) {
96807                 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
96808             }
96809             else {
96810                 emitBlockFunctionBody(body);
96811             }
96812             decreaseIndent();
96813             writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
96814         }
96815         function emitBlockFunctionBodyOnSingleLine(body) {
96816             emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
96817         }
96818         function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
96819             // Emit all the prologue directives (like "use strict").
96820             var statementOffset = emitPrologueDirectives(body.statements);
96821             var pos = writer.getTextPos();
96822             emitHelpers(body);
96823             if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
96824                 decreaseIndent();
96825                 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
96826                 increaseIndent();
96827             }
96828             else {
96829                 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
96830             }
96831         }
96832         function emitClassDeclaration(node) {
96833             emitClassDeclarationOrExpression(node);
96834         }
96835         function emitClassDeclarationOrExpression(node) {
96836             ts.forEach(node.members, generateMemberNames);
96837             emitDecorators(node, node.decorators);
96838             emitModifiers(node, node.modifiers);
96839             writeKeyword("class");
96840             if (node.name) {
96841                 writeSpace();
96842                 emitIdentifierName(node.name);
96843             }
96844             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96845             if (indentedFlag) {
96846                 increaseIndent();
96847             }
96848             emitTypeParameters(node, node.typeParameters);
96849             emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
96850             writeSpace();
96851             writePunctuation("{");
96852             emitList(node, node.members, 129 /* ClassMembers */);
96853             writePunctuation("}");
96854             if (indentedFlag) {
96855                 decreaseIndent();
96856             }
96857         }
96858         function emitInterfaceDeclaration(node) {
96859             emitDecorators(node, node.decorators);
96860             emitModifiers(node, node.modifiers);
96861             writeKeyword("interface");
96862             writeSpace();
96863             emit(node.name);
96864             emitTypeParameters(node, node.typeParameters);
96865             emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
96866             writeSpace();
96867             writePunctuation("{");
96868             emitList(node, node.members, 129 /* InterfaceMembers */);
96869             writePunctuation("}");
96870         }
96871         function emitTypeAliasDeclaration(node) {
96872             emitDecorators(node, node.decorators);
96873             emitModifiers(node, node.modifiers);
96874             writeKeyword("type");
96875             writeSpace();
96876             emit(node.name);
96877             emitTypeParameters(node, node.typeParameters);
96878             writeSpace();
96879             writePunctuation("=");
96880             writeSpace();
96881             emit(node.type);
96882             writeTrailingSemicolon();
96883         }
96884         function emitEnumDeclaration(node) {
96885             emitModifiers(node, node.modifiers);
96886             writeKeyword("enum");
96887             writeSpace();
96888             emit(node.name);
96889             writeSpace();
96890             writePunctuation("{");
96891             emitList(node, node.members, 145 /* EnumMembers */);
96892             writePunctuation("}");
96893         }
96894         function emitModuleDeclaration(node) {
96895             emitModifiers(node, node.modifiers);
96896             if (~node.flags & 1024 /* GlobalAugmentation */) {
96897                 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
96898                 writeSpace();
96899             }
96900             emit(node.name);
96901             var body = node.body;
96902             if (!body)
96903                 return writeTrailingSemicolon();
96904             while (body.kind === 249 /* ModuleDeclaration */) {
96905                 writePunctuation(".");
96906                 emit(body.name);
96907                 body = body.body;
96908             }
96909             writeSpace();
96910             emit(body);
96911         }
96912         function emitModuleBlock(node) {
96913             pushNameGenerationScope(node);
96914             ts.forEach(node.statements, generateNames);
96915             emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
96916             popNameGenerationScope(node);
96917         }
96918         function emitCaseBlock(node) {
96919             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
96920             emitList(node, node.clauses, 129 /* CaseBlockClauses */);
96921             emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
96922         }
96923         function emitImportEqualsDeclaration(node) {
96924             emitModifiers(node, node.modifiers);
96925             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
96926             writeSpace();
96927             emit(node.name);
96928             writeSpace();
96929             emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
96930             writeSpace();
96931             emitModuleReference(node.moduleReference);
96932             writeTrailingSemicolon();
96933         }
96934         function emitModuleReference(node) {
96935             if (node.kind === 75 /* Identifier */) {
96936                 emitExpression(node);
96937             }
96938             else {
96939                 emit(node);
96940             }
96941         }
96942         function emitImportDeclaration(node) {
96943             emitModifiers(node, node.modifiers);
96944             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
96945             writeSpace();
96946             if (node.importClause) {
96947                 emit(node.importClause);
96948                 writeSpace();
96949                 emitTokenWithComment(149 /* FromKeyword */, node.importClause.end, writeKeyword, node);
96950                 writeSpace();
96951             }
96952             emitExpression(node.moduleSpecifier);
96953             writeTrailingSemicolon();
96954         }
96955         function emitImportClause(node) {
96956             if (node.isTypeOnly) {
96957                 emitTokenWithComment(145 /* TypeKeyword */, node.pos, writeKeyword, node);
96958                 writeSpace();
96959             }
96960             emit(node.name);
96961             if (node.name && node.namedBindings) {
96962                 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
96963                 writeSpace();
96964             }
96965             emit(node.namedBindings);
96966         }
96967         function emitNamespaceImport(node) {
96968             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
96969             writeSpace();
96970             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
96971             writeSpace();
96972             emit(node.name);
96973         }
96974         function emitNamedImports(node) {
96975             emitNamedImportsOrExports(node);
96976         }
96977         function emitImportSpecifier(node) {
96978             emitImportOrExportSpecifier(node);
96979         }
96980         function emitExportAssignment(node) {
96981             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
96982             writeSpace();
96983             if (node.isExportEquals) {
96984                 emitTokenWithComment(62 /* EqualsToken */, nextPos, writeOperator, node);
96985             }
96986             else {
96987                 emitTokenWithComment(84 /* DefaultKeyword */, nextPos, writeKeyword, node);
96988             }
96989             writeSpace();
96990             emitExpression(node.expression);
96991             writeTrailingSemicolon();
96992         }
96993         function emitExportDeclaration(node) {
96994             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
96995             writeSpace();
96996             if (node.isTypeOnly) {
96997                 nextPos = emitTokenWithComment(145 /* TypeKeyword */, nextPos, writeKeyword, node);
96998                 writeSpace();
96999             }
97000             if (node.exportClause) {
97001                 emit(node.exportClause);
97002             }
97003             else {
97004                 nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
97005             }
97006             if (node.moduleSpecifier) {
97007                 writeSpace();
97008                 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
97009                 emitTokenWithComment(149 /* FromKeyword */, fromPos, writeKeyword, node);
97010                 writeSpace();
97011                 emitExpression(node.moduleSpecifier);
97012             }
97013             writeTrailingSemicolon();
97014         }
97015         function emitNamespaceExportDeclaration(node) {
97016             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
97017             writeSpace();
97018             nextPos = emitTokenWithComment(123 /* AsKeyword */, nextPos, writeKeyword, node);
97019             writeSpace();
97020             nextPos = emitTokenWithComment(136 /* NamespaceKeyword */, nextPos, writeKeyword, node);
97021             writeSpace();
97022             emit(node.name);
97023             writeTrailingSemicolon();
97024         }
97025         function emitNamespaceExport(node) {
97026             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
97027             writeSpace();
97028             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
97029             writeSpace();
97030             emit(node.name);
97031         }
97032         function emitNamedExports(node) {
97033             emitNamedImportsOrExports(node);
97034         }
97035         function emitExportSpecifier(node) {
97036             emitImportOrExportSpecifier(node);
97037         }
97038         function emitNamedImportsOrExports(node) {
97039             writePunctuation("{");
97040             emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
97041             writePunctuation("}");
97042         }
97043         function emitImportOrExportSpecifier(node) {
97044             if (node.propertyName) {
97045                 emit(node.propertyName);
97046                 writeSpace();
97047                 emitTokenWithComment(123 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
97048                 writeSpace();
97049             }
97050             emit(node.name);
97051         }
97052         //
97053         // Module references
97054         //
97055         function emitExternalModuleReference(node) {
97056             writeKeyword("require");
97057             writePunctuation("(");
97058             emitExpression(node.expression);
97059             writePunctuation(")");
97060         }
97061         //
97062         // JSX
97063         //
97064         function emitJsxElement(node) {
97065             emit(node.openingElement);
97066             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97067             emit(node.closingElement);
97068         }
97069         function emitJsxSelfClosingElement(node) {
97070             writePunctuation("<");
97071             emitJsxTagName(node.tagName);
97072             emitTypeArguments(node, node.typeArguments);
97073             writeSpace();
97074             emit(node.attributes);
97075             writePunctuation("/>");
97076         }
97077         function emitJsxFragment(node) {
97078             emit(node.openingFragment);
97079             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97080             emit(node.closingFragment);
97081         }
97082         function emitJsxOpeningElementOrFragment(node) {
97083             writePunctuation("<");
97084             if (ts.isJsxOpeningElement(node)) {
97085                 var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
97086                 emitJsxTagName(node.tagName);
97087                 emitTypeArguments(node, node.typeArguments);
97088                 if (node.attributes.properties && node.attributes.properties.length > 0) {
97089                     writeSpace();
97090                 }
97091                 emit(node.attributes);
97092                 writeLineSeparatorsAfter(node.attributes, node);
97093                 decreaseIndentIf(indented);
97094             }
97095             writePunctuation(">");
97096         }
97097         function emitJsxText(node) {
97098             writer.writeLiteral(node.text);
97099         }
97100         function emitJsxClosingElementOrFragment(node) {
97101             writePunctuation("</");
97102             if (ts.isJsxClosingElement(node)) {
97103                 emitJsxTagName(node.tagName);
97104             }
97105             writePunctuation(">");
97106         }
97107         function emitJsxAttributes(node) {
97108             emitList(node, node.properties, 262656 /* JsxElementAttributes */);
97109         }
97110         function emitJsxAttribute(node) {
97111             emit(node.name);
97112             emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
97113         }
97114         function emitJsxSpreadAttribute(node) {
97115             writePunctuation("{...");
97116             emitExpression(node.expression);
97117             writePunctuation("}");
97118         }
97119         function emitJsxExpression(node) {
97120             if (node.expression) {
97121                 writePunctuation("{");
97122                 emit(node.dotDotDotToken);
97123                 emitExpression(node.expression);
97124                 writePunctuation("}");
97125             }
97126         }
97127         function emitJsxTagName(node) {
97128             if (node.kind === 75 /* Identifier */) {
97129                 emitExpression(node);
97130             }
97131             else {
97132                 emit(node);
97133             }
97134         }
97135         //
97136         // Clauses
97137         //
97138         function emitCaseClause(node) {
97139             emitTokenWithComment(78 /* CaseKeyword */, node.pos, writeKeyword, node);
97140             writeSpace();
97141             emitExpression(node.expression);
97142             emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
97143         }
97144         function emitDefaultClause(node) {
97145             var pos = emitTokenWithComment(84 /* DefaultKeyword */, node.pos, writeKeyword, node);
97146             emitCaseOrDefaultClauseRest(node, node.statements, pos);
97147         }
97148         function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
97149             var emitAsSingleStatement = statements.length === 1 &&
97150                 (
97151                 // treat synthesized nodes as located on the same line for emit purposes
97152                 ts.nodeIsSynthesized(parentNode) ||
97153                     ts.nodeIsSynthesized(statements[0]) ||
97154                     ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
97155             var format = 163969 /* CaseOrDefaultClauseStatements */;
97156             if (emitAsSingleStatement) {
97157                 writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97158                 writeSpace();
97159                 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
97160             }
97161             else {
97162                 emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97163             }
97164             emitList(parentNode, statements, format);
97165         }
97166         function emitHeritageClause(node) {
97167             writeSpace();
97168             writeTokenText(node.token, writeKeyword);
97169             writeSpace();
97170             emitList(node, node.types, 528 /* HeritageClauseTypes */);
97171         }
97172         function emitCatchClause(node) {
97173             var openParenPos = emitTokenWithComment(79 /* CatchKeyword */, node.pos, writeKeyword, node);
97174             writeSpace();
97175             if (node.variableDeclaration) {
97176                 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
97177                 emit(node.variableDeclaration);
97178                 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
97179                 writeSpace();
97180             }
97181             emit(node.block);
97182         }
97183         //
97184         // Property assignments
97185         //
97186         function emitPropertyAssignment(node) {
97187             emit(node.name);
97188             writePunctuation(":");
97189             writeSpace();
97190             // This is to ensure that we emit comment in the following case:
97191             //      For example:
97192             //          obj = {
97193             //              id: /*comment1*/ ()=>void
97194             //          }
97195             // "comment1" is not considered to be leading comment for node.initializer
97196             // but rather a trailing comment on the previous node.
97197             var initializer = node.initializer;
97198             if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
97199                 var commentRange = ts.getCommentRange(initializer);
97200                 emitTrailingCommentsOfPosition(commentRange.pos);
97201             }
97202             emitExpression(initializer);
97203         }
97204         function emitShorthandPropertyAssignment(node) {
97205             emit(node.name);
97206             if (node.objectAssignmentInitializer) {
97207                 writeSpace();
97208                 writePunctuation("=");
97209                 writeSpace();
97210                 emitExpression(node.objectAssignmentInitializer);
97211             }
97212         }
97213         function emitSpreadAssignment(node) {
97214             if (node.expression) {
97215                 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
97216                 emitExpression(node.expression);
97217             }
97218         }
97219         //
97220         // Enum
97221         //
97222         function emitEnumMember(node) {
97223             emit(node.name);
97224             emitInitializer(node.initializer, node.name.end, node);
97225         }
97226         //
97227         // JSDoc
97228         //
97229         function emitJSDoc(node) {
97230             write("/**");
97231             if (node.comment) {
97232                 var lines = node.comment.split(/\r\n?|\n/g);
97233                 for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
97234                     var line = lines_2[_a];
97235                     writeLine();
97236                     writeSpace();
97237                     writePunctuation("*");
97238                     writeSpace();
97239                     write(line);
97240                 }
97241             }
97242             if (node.tags) {
97243                 if (node.tags.length === 1 && node.tags[0].kind === 320 /* JSDocTypeTag */ && !node.comment) {
97244                     writeSpace();
97245                     emit(node.tags[0]);
97246                 }
97247                 else {
97248                     emitList(node, node.tags, 33 /* JSDocComment */);
97249                 }
97250             }
97251             writeSpace();
97252             write("*/");
97253         }
97254         function emitJSDocSimpleTypedTag(tag) {
97255             emitJSDocTagName(tag.tagName);
97256             emitJSDocTypeExpression(tag.typeExpression);
97257             emitJSDocComment(tag.comment);
97258         }
97259         function emitJSDocHeritageTag(tag) {
97260             emitJSDocTagName(tag.tagName);
97261             writeSpace();
97262             writePunctuation("{");
97263             emit(tag.class);
97264             writePunctuation("}");
97265             emitJSDocComment(tag.comment);
97266         }
97267         function emitJSDocTemplateTag(tag) {
97268             emitJSDocTagName(tag.tagName);
97269             emitJSDocTypeExpression(tag.constraint);
97270             writeSpace();
97271             emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
97272             emitJSDocComment(tag.comment);
97273         }
97274         function emitJSDocTypedefTag(tag) {
97275             emitJSDocTagName(tag.tagName);
97276             if (tag.typeExpression) {
97277                 if (tag.typeExpression.kind === 294 /* JSDocTypeExpression */) {
97278                     emitJSDocTypeExpression(tag.typeExpression);
97279                 }
97280                 else {
97281                     writeSpace();
97282                     writePunctuation("{");
97283                     write("Object");
97284                     if (tag.typeExpression.isArrayType) {
97285                         writePunctuation("[");
97286                         writePunctuation("]");
97287                     }
97288                     writePunctuation("}");
97289                 }
97290             }
97291             if (tag.fullName) {
97292                 writeSpace();
97293                 emit(tag.fullName);
97294             }
97295             emitJSDocComment(tag.comment);
97296             if (tag.typeExpression && tag.typeExpression.kind === 304 /* JSDocTypeLiteral */) {
97297                 emitJSDocTypeLiteral(tag.typeExpression);
97298             }
97299         }
97300         function emitJSDocCallbackTag(tag) {
97301             emitJSDocTagName(tag.tagName);
97302             if (tag.name) {
97303                 writeSpace();
97304                 emit(tag.name);
97305             }
97306             emitJSDocComment(tag.comment);
97307             emitJSDocSignature(tag.typeExpression);
97308         }
97309         function emitJSDocSimpleTag(tag) {
97310             emitJSDocTagName(tag.tagName);
97311             emitJSDocComment(tag.comment);
97312         }
97313         function emitJSDocTypeLiteral(lit) {
97314             emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
97315         }
97316         function emitJSDocSignature(sig) {
97317             if (sig.typeParameters) {
97318                 emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
97319             }
97320             if (sig.parameters) {
97321                 emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */);
97322             }
97323             if (sig.type) {
97324                 writeLine();
97325                 writeSpace();
97326                 writePunctuation("*");
97327                 writeSpace();
97328                 emit(sig.type);
97329             }
97330         }
97331         function emitJSDocPropertyLikeTag(param) {
97332             emitJSDocTagName(param.tagName);
97333             emitJSDocTypeExpression(param.typeExpression);
97334             writeSpace();
97335             if (param.isBracketed) {
97336                 writePunctuation("[");
97337             }
97338             emit(param.name);
97339             if (param.isBracketed) {
97340                 writePunctuation("]");
97341             }
97342             emitJSDocComment(param.comment);
97343         }
97344         function emitJSDocTagName(tagName) {
97345             writePunctuation("@");
97346             emit(tagName);
97347         }
97348         function emitJSDocComment(comment) {
97349             if (comment) {
97350                 writeSpace();
97351                 write(comment);
97352             }
97353         }
97354         function emitJSDocTypeExpression(typeExpression) {
97355             if (typeExpression) {
97356                 writeSpace();
97357                 writePunctuation("{");
97358                 emit(typeExpression.type);
97359                 writePunctuation("}");
97360             }
97361         }
97362         //
97363         // Top-level nodes
97364         //
97365         function emitSourceFile(node) {
97366             writeLine();
97367             var statements = node.statements;
97368             if (emitBodyWithDetachedComments) {
97369                 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
97370                 // The synthesized node will have no leading comment so some comments may be missed.
97371                 var shouldEmitDetachedComment = statements.length === 0 ||
97372                     !ts.isPrologueDirective(statements[0]) ||
97373                     ts.nodeIsSynthesized(statements[0]);
97374                 if (shouldEmitDetachedComment) {
97375                     emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
97376                     return;
97377                 }
97378             }
97379             emitSourceFileWorker(node);
97380         }
97381         function emitSyntheticTripleSlashReferencesIfNeeded(node) {
97382             emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
97383             for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
97384                 var prepend = _b[_a];
97385                 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
97386                     for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
97387                         var ref = _d[_c];
97388                         emit(ref);
97389                         writeLine();
97390                     }
97391                 }
97392             }
97393         }
97394         function emitTripleSlashDirectivesIfNeeded(node) {
97395             if (node.isDeclarationFile)
97396                 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
97397         }
97398         function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
97399             if (hasNoDefaultLib) {
97400                 var pos = writer.getTextPos();
97401                 writeComment("/// <reference no-default-lib=\"true\"/>");
97402                 if (bundleFileInfo)
97403                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
97404                 writeLine();
97405             }
97406             if (currentSourceFile && currentSourceFile.moduleName) {
97407                 writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
97408                 writeLine();
97409             }
97410             if (currentSourceFile && currentSourceFile.amdDependencies) {
97411                 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
97412                     var dep = _b[_a];
97413                     if (dep.name) {
97414                         writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
97415                     }
97416                     else {
97417                         writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
97418                     }
97419                     writeLine();
97420                 }
97421             }
97422             for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
97423                 var directive = files_1[_c];
97424                 var pos = writer.getTextPos();
97425                 writeComment("/// <reference path=\"" + directive.fileName + "\" />");
97426                 if (bundleFileInfo)
97427                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
97428                 writeLine();
97429             }
97430             for (var _d = 0, types_22 = types; _d < types_22.length; _d++) {
97431                 var directive = types_22[_d];
97432                 var pos = writer.getTextPos();
97433                 writeComment("/// <reference types=\"" + directive.fileName + "\" />");
97434                 if (bundleFileInfo)
97435                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
97436                 writeLine();
97437             }
97438             for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
97439                 var directive = libs_1[_e];
97440                 var pos = writer.getTextPos();
97441                 writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
97442                 if (bundleFileInfo)
97443                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
97444                 writeLine();
97445             }
97446         }
97447         function emitSourceFileWorker(node) {
97448             var statements = node.statements;
97449             pushNameGenerationScope(node);
97450             ts.forEach(node.statements, generateNames);
97451             emitHelpers(node);
97452             var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
97453             emitTripleSlashDirectivesIfNeeded(node);
97454             emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
97455             popNameGenerationScope(node);
97456         }
97457         // Transformation nodes
97458         function emitPartiallyEmittedExpression(node) {
97459             emitExpression(node.expression);
97460         }
97461         function emitCommaList(node) {
97462             emitExpressionList(node, node.elements, 528 /* CommaListElements */);
97463         }
97464         /**
97465          * Emits any prologue directives at the start of a Statement list, returning the
97466          * number of prologue directives written to the output.
97467          */
97468         function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
97469             var needsToSetSourceFile = !!sourceFile;
97470             for (var i = 0; i < statements.length; i++) {
97471                 var statement = statements[i];
97472                 if (ts.isPrologueDirective(statement)) {
97473                     var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
97474                     if (shouldEmitPrologueDirective) {
97475                         if (needsToSetSourceFile) {
97476                             needsToSetSourceFile = false;
97477                             setSourceFile(sourceFile);
97478                         }
97479                         writeLine();
97480                         var pos = writer.getTextPos();
97481                         emit(statement);
97482                         if (recordBundleFileSection && bundleFileInfo)
97483                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
97484                         if (seenPrologueDirectives) {
97485                             seenPrologueDirectives.set(statement.expression.text, true);
97486                         }
97487                     }
97488                 }
97489                 else {
97490                     // return index of the first non prologue directive
97491                     return i;
97492                 }
97493             }
97494             return statements.length;
97495         }
97496         function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
97497             for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
97498                 var prologue = prologues_1[_a];
97499                 if (!seenPrologueDirectives.has(prologue.data)) {
97500                     writeLine();
97501                     var pos = writer.getTextPos();
97502                     emit(prologue);
97503                     if (bundleFileInfo)
97504                         bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
97505                     if (seenPrologueDirectives) {
97506                         seenPrologueDirectives.set(prologue.data, true);
97507                     }
97508                 }
97509             }
97510         }
97511         function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
97512             if (ts.isSourceFile(sourceFileOrBundle)) {
97513                 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
97514             }
97515             else {
97516                 var seenPrologueDirectives = ts.createMap();
97517                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97518                     var prepend = _b[_a];
97519                     emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
97520                 }
97521                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97522                     var sourceFile = _d[_c];
97523                     emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
97524                 }
97525                 setSourceFile(undefined);
97526             }
97527         }
97528         function getPrologueDirectivesFromBundledSourceFiles(bundle) {
97529             var seenPrologueDirectives = ts.createMap();
97530             var prologues;
97531             for (var index = 0; index < bundle.sourceFiles.length; index++) {
97532                 var sourceFile = bundle.sourceFiles[index];
97533                 var directives = void 0;
97534                 var end = 0;
97535                 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
97536                     var statement = _b[_a];
97537                     if (!ts.isPrologueDirective(statement))
97538                         break;
97539                     if (seenPrologueDirectives.has(statement.expression.text))
97540                         continue;
97541                     seenPrologueDirectives.set(statement.expression.text, true);
97542                     (directives || (directives = [])).push({
97543                         pos: statement.pos,
97544                         end: statement.end,
97545                         expression: {
97546                             pos: statement.expression.pos,
97547                             end: statement.expression.end,
97548                             text: statement.expression.text
97549                         }
97550                     });
97551                     end = end < statement.end ? statement.end : end;
97552                 }
97553                 if (directives)
97554                     (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
97555             }
97556             return prologues;
97557         }
97558         function emitShebangIfNeeded(sourceFileOrBundle) {
97559             if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
97560                 var shebang = ts.getShebang(sourceFileOrBundle.text);
97561                 if (shebang) {
97562                     writeComment(shebang);
97563                     writeLine();
97564                     return true;
97565                 }
97566             }
97567             else {
97568                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97569                     var prepend = _b[_a];
97570                     ts.Debug.assertNode(prepend, ts.isUnparsedSource);
97571                     if (emitShebangIfNeeded(prepend)) {
97572                         return true;
97573                     }
97574                 }
97575                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97576                     var sourceFile = _d[_c];
97577                     // Emit only the first encountered shebang
97578                     if (emitShebangIfNeeded(sourceFile)) {
97579                         return true;
97580                     }
97581                 }
97582             }
97583         }
97584         //
97585         // Helpers
97586         //
97587         function emitNodeWithWriter(node, writer) {
97588             if (!node)
97589                 return;
97590             var savedWrite = write;
97591             write = writer;
97592             emit(node);
97593             write = savedWrite;
97594         }
97595         function emitModifiers(node, modifiers) {
97596             if (modifiers && modifiers.length) {
97597                 emitList(node, modifiers, 262656 /* Modifiers */);
97598                 writeSpace();
97599             }
97600         }
97601         function emitTypeAnnotation(node) {
97602             if (node) {
97603                 writePunctuation(":");
97604                 writeSpace();
97605                 emit(node);
97606             }
97607         }
97608         function emitInitializer(node, equalCommentStartPos, container) {
97609             if (node) {
97610                 writeSpace();
97611                 emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
97612                 writeSpace();
97613                 emitExpression(node);
97614             }
97615         }
97616         function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
97617             if (node) {
97618                 prefixWriter(prefix);
97619                 emit(node);
97620             }
97621         }
97622         function emitWithLeadingSpace(node) {
97623             if (node) {
97624                 writeSpace();
97625                 emit(node);
97626             }
97627         }
97628         function emitExpressionWithLeadingSpace(node) {
97629             if (node) {
97630                 writeSpace();
97631                 emitExpression(node);
97632             }
97633         }
97634         function emitWithTrailingSpace(node) {
97635             if (node) {
97636                 emit(node);
97637                 writeSpace();
97638             }
97639         }
97640         function emitEmbeddedStatement(parent, node) {
97641             if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
97642                 writeSpace();
97643                 emit(node);
97644             }
97645             else {
97646                 writeLine();
97647                 increaseIndent();
97648                 if (ts.isEmptyStatement(node)) {
97649                     pipelineEmit(5 /* EmbeddedStatement */, node);
97650                 }
97651                 else {
97652                     emit(node);
97653                 }
97654                 decreaseIndent();
97655             }
97656         }
97657         function emitDecorators(parentNode, decorators) {
97658             emitList(parentNode, decorators, 2146305 /* Decorators */);
97659         }
97660         function emitTypeArguments(parentNode, typeArguments) {
97661             emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
97662         }
97663         function emitTypeParameters(parentNode, typeParameters) {
97664             if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
97665                 return emitTypeArguments(parentNode, parentNode.typeArguments);
97666             }
97667             emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
97668         }
97669         function emitParameters(parentNode, parameters) {
97670             emitList(parentNode, parameters, 2576 /* Parameters */);
97671         }
97672         function canEmitSimpleArrowHead(parentNode, parameters) {
97673             var parameter = ts.singleOrUndefined(parameters);
97674             return parameter
97675                 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
97676                 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
97677                 && !parentNode.type // arrow function may not have return type annotation
97678                 && !ts.some(parentNode.decorators) // parent may not have decorators
97679                 && !ts.some(parentNode.modifiers) // parent may not have modifiers
97680                 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
97681                 && !ts.some(parameter.decorators) // parameter may not have decorators
97682                 && !ts.some(parameter.modifiers) // parameter may not have modifiers
97683                 && !parameter.dotDotDotToken // parameter may not be rest
97684                 && !parameter.questionToken // parameter may not be optional
97685                 && !parameter.type // parameter may not have a type annotation
97686                 && !parameter.initializer // parameter may not have an initializer
97687                 && ts.isIdentifier(parameter.name); // parameter name must be identifier
97688         }
97689         function emitParametersForArrow(parentNode, parameters) {
97690             if (canEmitSimpleArrowHead(parentNode, parameters)) {
97691                 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
97692             }
97693             else {
97694                 emitParameters(parentNode, parameters);
97695             }
97696         }
97697         function emitParametersForIndexSignature(parentNode, parameters) {
97698             emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
97699         }
97700         function emitList(parentNode, children, format, start, count) {
97701             emitNodeList(emit, parentNode, children, format, start, count);
97702         }
97703         function emitExpressionList(parentNode, children, format, start, count) {
97704             emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
97705         }
97706         function writeDelimiter(format) {
97707             switch (format & 60 /* DelimitersMask */) {
97708                 case 0 /* None */:
97709                     break;
97710                 case 16 /* CommaDelimited */:
97711                     writePunctuation(",");
97712                     break;
97713                 case 4 /* BarDelimited */:
97714                     writeSpace();
97715                     writePunctuation("|");
97716                     break;
97717                 case 32 /* AsteriskDelimited */:
97718                     writeSpace();
97719                     writePunctuation("*");
97720                     writeSpace();
97721                     break;
97722                 case 8 /* AmpersandDelimited */:
97723                     writeSpace();
97724                     writePunctuation("&");
97725                     break;
97726             }
97727         }
97728         function emitNodeList(emit, parentNode, children, format, start, count) {
97729             if (start === void 0) { start = 0; }
97730             if (count === void 0) { count = children ? children.length - start : 0; }
97731             var isUndefined = children === undefined;
97732             if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
97733                 return;
97734             }
97735             var isEmpty = children === undefined || start >= children.length || count === 0;
97736             if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
97737                 if (onBeforeEmitNodeArray) {
97738                     onBeforeEmitNodeArray(children);
97739                 }
97740                 if (onAfterEmitNodeArray) {
97741                     onAfterEmitNodeArray(children);
97742                 }
97743                 return;
97744             }
97745             if (format & 15360 /* BracketsMask */) {
97746                 writePunctuation(getOpeningBracket(format));
97747                 if (isEmpty && !isUndefined) {
97748                     // TODO: GH#18217
97749                     emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
97750                 }
97751             }
97752             if (onBeforeEmitNodeArray) {
97753                 onBeforeEmitNodeArray(children);
97754             }
97755             if (isEmpty) {
97756                 // Write a line terminator if the parent node was multi-line
97757                 if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) {
97758                     writeLine();
97759                 }
97760                 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
97761                     writeSpace();
97762                 }
97763             }
97764             else {
97765                 // Write the opening line terminator or leading whitespace.
97766                 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
97767                 var shouldEmitInterveningComments = mayEmitInterveningComments;
97768                 var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217
97769                 if (leadingLineTerminatorCount) {
97770                     writeLine(leadingLineTerminatorCount);
97771                     shouldEmitInterveningComments = false;
97772                 }
97773                 else if (format & 256 /* SpaceBetweenBraces */) {
97774                     writeSpace();
97775                 }
97776                 // Increase the indent, if requested.
97777                 if (format & 128 /* Indented */) {
97778                     increaseIndent();
97779                 }
97780                 // Emit each child.
97781                 var previousSibling = void 0;
97782                 var previousSourceFileTextKind = void 0;
97783                 var shouldDecreaseIndentAfterEmit = false;
97784                 for (var i = 0; i < count; i++) {
97785                     var child = children[start + i];
97786                     // Write the delimiter if this is not the first node.
97787                     if (format & 32 /* AsteriskDelimited */) {
97788                         // always write JSDoc in the format "\n *"
97789                         writeLine();
97790                         writeDelimiter(format);
97791                     }
97792                     else if (previousSibling) {
97793                         // i.e
97794                         //      function commentedParameters(
97795                         //          /* Parameter a */
97796                         //          a
97797                         //          /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
97798                         //          ,
97799                         if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
97800                             emitLeadingCommentsOfPosition(previousSibling.end);
97801                         }
97802                         writeDelimiter(format);
97803                         recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
97804                         // Write either a line terminator or whitespace to separate the elements.
97805                         var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
97806                         if (separatingLineTerminatorCount > 0) {
97807                             // If a synthesized node in a single-line list starts on a new
97808                             // line, we should increase the indent.
97809                             if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
97810                                 increaseIndent();
97811                                 shouldDecreaseIndentAfterEmit = true;
97812                             }
97813                             writeLine(separatingLineTerminatorCount);
97814                             shouldEmitInterveningComments = false;
97815                         }
97816                         else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
97817                             writeSpace();
97818                         }
97819                     }
97820                     // Emit this child.
97821                     previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
97822                     if (shouldEmitInterveningComments) {
97823                         if (emitTrailingCommentsOfPosition) {
97824                             var commentRange = ts.getCommentRange(child);
97825                             emitTrailingCommentsOfPosition(commentRange.pos);
97826                         }
97827                     }
97828                     else {
97829                         shouldEmitInterveningComments = mayEmitInterveningComments;
97830                     }
97831                     emit(child);
97832                     if (shouldDecreaseIndentAfterEmit) {
97833                         decreaseIndent();
97834                         shouldDecreaseIndentAfterEmit = false;
97835                     }
97836                     previousSibling = child;
97837                 }
97838                 // Write a trailing comma, if requested.
97839                 var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
97840                 if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
97841                     writePunctuation(",");
97842                 }
97843                 // Emit any trailing comment of the last element in the list
97844                 // i.e
97845                 //       var array = [...
97846                 //          2
97847                 //          /* end of element 2 */
97848                 //       ];
97849                 if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
97850                     emitLeadingCommentsOfPosition(previousSibling.end);
97851                 }
97852                 // Decrease the indent, if requested.
97853                 if (format & 128 /* Indented */) {
97854                     decreaseIndent();
97855                 }
97856                 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
97857                 // Write the closing line terminator or closing whitespace.
97858                 var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format);
97859                 if (closingLineTerminatorCount) {
97860                     writeLine(closingLineTerminatorCount);
97861                 }
97862                 else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
97863                     writeSpace();
97864                 }
97865             }
97866             if (onAfterEmitNodeArray) {
97867                 onAfterEmitNodeArray(children);
97868             }
97869             if (format & 15360 /* BracketsMask */) {
97870                 if (isEmpty && !isUndefined) {
97871                     // TODO: GH#18217
97872                     emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
97873                 }
97874                 writePunctuation(getClosingBracket(format));
97875             }
97876         }
97877         // Writers
97878         function writeLiteral(s) {
97879             writer.writeLiteral(s);
97880         }
97881         function writeStringLiteral(s) {
97882             writer.writeStringLiteral(s);
97883         }
97884         function writeBase(s) {
97885             writer.write(s);
97886         }
97887         function writeSymbol(s, sym) {
97888             writer.writeSymbol(s, sym);
97889         }
97890         function writePunctuation(s) {
97891             writer.writePunctuation(s);
97892         }
97893         function writeTrailingSemicolon() {
97894             writer.writeTrailingSemicolon(";");
97895         }
97896         function writeKeyword(s) {
97897             writer.writeKeyword(s);
97898         }
97899         function writeOperator(s) {
97900             writer.writeOperator(s);
97901         }
97902         function writeParameter(s) {
97903             writer.writeParameter(s);
97904         }
97905         function writeComment(s) {
97906             writer.writeComment(s);
97907         }
97908         function writeSpace() {
97909             writer.writeSpace(" ");
97910         }
97911         function writeProperty(s) {
97912             writer.writeProperty(s);
97913         }
97914         function writeLine(count) {
97915             if (count === void 0) { count = 1; }
97916             for (var i = 0; i < count; i++) {
97917                 writer.writeLine(i > 0);
97918             }
97919         }
97920         function increaseIndent() {
97921             writer.increaseIndent();
97922         }
97923         function decreaseIndent() {
97924             writer.decreaseIndent();
97925         }
97926         function writeToken(token, pos, writer, contextNode) {
97927             return !sourceMapsDisabled
97928                 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
97929                 : writeTokenText(token, writer, pos);
97930         }
97931         function writeTokenNode(node, writer) {
97932             if (onBeforeEmitToken) {
97933                 onBeforeEmitToken(node);
97934             }
97935             writer(ts.tokenToString(node.kind));
97936             if (onAfterEmitToken) {
97937                 onAfterEmitToken(node);
97938             }
97939         }
97940         function writeTokenText(token, writer, pos) {
97941             var tokenString = ts.tokenToString(token);
97942             writer(tokenString);
97943             return pos < 0 ? pos : pos + tokenString.length;
97944         }
97945         function writeLineOrSpace(node) {
97946             if (ts.getEmitFlags(node) & 1 /* SingleLine */) {
97947                 writeSpace();
97948             }
97949             else {
97950                 writeLine();
97951             }
97952         }
97953         function writeLines(text) {
97954             var lines = text.split(/\r\n?|\n/g);
97955             var indentation = ts.guessIndentation(lines);
97956             for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
97957                 var lineText = lines_3[_a];
97958                 var line = indentation ? lineText.slice(indentation) : lineText;
97959                 if (line.length) {
97960                     writeLine();
97961                     write(line);
97962                 }
97963             }
97964         }
97965         function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
97966             if (lineCount) {
97967                 increaseIndent();
97968                 writeLine(lineCount);
97969             }
97970             else if (writeSpaceIfNotIndenting) {
97971                 writeSpace();
97972             }
97973         }
97974         // Helper function to decrease the indent if we previously indented.  Allows multiple
97975         // previous indent values to be considered at a time.  This also allows caller to just
97976         // call this once, passing in all their appropriate indent values, instead of needing
97977         // to call this helper function multiple times.
97978         function decreaseIndentIf(value1, value2) {
97979             if (value1) {
97980                 decreaseIndent();
97981             }
97982             if (value2) {
97983                 decreaseIndent();
97984             }
97985         }
97986         function getLeadingLineTerminatorCount(parentNode, children, format) {
97987             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
97988                 if (format & 65536 /* PreferNewLine */) {
97989                     return 1;
97990                 }
97991                 var firstChild_1 = children[0];
97992                 if (firstChild_1 === undefined) {
97993                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
97994                 }
97995                 if (firstChild_1.kind === 11 /* JsxText */) {
97996                     // JsxText will be written with its leading whitespace, so don't add more manually.
97997                     return 0;
97998                 }
97999                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) {
98000                     if (preserveSourceNewlines) {
98001                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); });
98002                     }
98003                     return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1;
98004                 }
98005                 if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) {
98006                     return 1;
98007                 }
98008             }
98009             return format & 1 /* MultiLine */ ? 1 : 0;
98010         }
98011         function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
98012             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98013                 if (previousNode === undefined || nextNode === undefined) {
98014                     return 0;
98015                 }
98016                 if (nextNode.kind === 11 /* JsxText */) {
98017                     // JsxText will be written with its leading whitespace, so don't add more manually.
98018                     return 0;
98019                 }
98020                 else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) {
98021                     if (preserveSourceNewlines) {
98022                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); });
98023                     }
98024                     return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
98025                 }
98026                 else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
98027                     return 1;
98028                 }
98029             }
98030             else if (ts.getStartsOnNewLine(nextNode)) {
98031                 return 1;
98032             }
98033             return format & 1 /* MultiLine */ ? 1 : 0;
98034         }
98035         function getClosingLineTerminatorCount(parentNode, children, format) {
98036             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98037                 if (format & 65536 /* PreferNewLine */) {
98038                     return 1;
98039                 }
98040                 var lastChild_1 = ts.lastOrUndefined(children);
98041                 if (lastChild_1 === undefined) {
98042                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
98043                 }
98044                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) {
98045                     if (preserveSourceNewlines) {
98046                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); });
98047                     }
98048                     return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1;
98049                 }
98050                 if (synthesizedNodeStartsOnNewLine(lastChild_1, format)) {
98051                     return 1;
98052                 }
98053             }
98054             if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
98055                 return 1;
98056             }
98057             return 0;
98058         }
98059         function getEffectiveLines(getLineDifference) {
98060             // If 'preserveSourceNewlines' is disabled, we should never call this function
98061             // because it could be more expensive than alternative approximations.
98062             ts.Debug.assert(!!preserveSourceNewlines);
98063             // We start by measuring the line difference from a position to its adjacent comments,
98064             // so that this is counted as a one-line difference, not two:
98065             //
98066             //   node1;
98067             //   // NODE2 COMMENT
98068             //   node2;
98069             var lines = getLineDifference(/*includeComments*/ true);
98070             if (lines === 0) {
98071                 // However, if the line difference considering comments was 0, we might have this:
98072                 //
98073                 //   node1; // NODE2 COMMENT
98074                 //   node2;
98075                 //
98076                 // in which case we should be ignoring node2's comment, so this too is counted as
98077                 // a one-line difference, not zero.
98078                 return getLineDifference(/*includeComments*/ false);
98079             }
98080             return lines;
98081         }
98082         function writeLineSeparatorsAndIndentBefore(node, parent) {
98083             var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */);
98084             if (leadingNewlines) {
98085                 writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
98086             }
98087             return !!leadingNewlines;
98088         }
98089         function writeLineSeparatorsAfter(node, parent) {
98090             var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */);
98091             if (trailingNewlines) {
98092                 writeLine(trailingNewlines);
98093             }
98094         }
98095         function synthesizedNodeStartsOnNewLine(node, format) {
98096             if (ts.nodeIsSynthesized(node)) {
98097                 var startsOnNewLine = ts.getStartsOnNewLine(node);
98098                 if (startsOnNewLine === undefined) {
98099                     return (format & 65536 /* PreferNewLine */) !== 0;
98100                 }
98101                 return startsOnNewLine;
98102             }
98103             return (format & 65536 /* PreferNewLine */) !== 0;
98104         }
98105         function getLinesBetweenNodes(parent, node1, node2) {
98106             if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
98107                 return 0;
98108             }
98109             parent = skipSynthesizedParentheses(parent);
98110             node1 = skipSynthesizedParentheses(node1);
98111             node2 = skipSynthesizedParentheses(node2);
98112             // Always use a newline for synthesized code if the synthesizer desires it.
98113             if (ts.getStartsOnNewLine(node2)) {
98114                 return 1;
98115             }
98116             if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) {
98117                 if (preserveSourceNewlines) {
98118                     return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); });
98119                 }
98120                 return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
98121             }
98122             return 0;
98123         }
98124         function isEmptyBlock(block) {
98125             return block.statements.length === 0
98126                 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
98127         }
98128         function skipSynthesizedParentheses(node) {
98129             while (node.kind === 200 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
98130                 node = node.expression;
98131             }
98132             return node;
98133         }
98134         function getTextOfNode(node, includeTrivia) {
98135             if (ts.isGeneratedIdentifier(node)) {
98136                 return generateName(node);
98137             }
98138             else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
98139                 return ts.idText(node);
98140             }
98141             else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98142                 return getTextOfNode(node.textSourceNode, includeTrivia);
98143             }
98144             else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
98145                 return node.text;
98146             }
98147             return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
98148         }
98149         function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
98150             if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98151                 var textSourceNode = node.textSourceNode;
98152                 if (ts.isIdentifier(textSourceNode)) {
98153                     return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(getTextOfNode(textSourceNode)) + "\"" :
98154                         neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" :
98155                             "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\"";
98156                 }
98157                 else {
98158                     return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
98159                 }
98160             }
98161             return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape, jsxAttributeEscape);
98162         }
98163         /**
98164          * Push a new name generation scope.
98165          */
98166         function pushNameGenerationScope(node) {
98167             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98168                 return;
98169             }
98170             tempFlagsStack.push(tempFlags);
98171             tempFlags = 0;
98172             reservedNamesStack.push(reservedNames);
98173         }
98174         /**
98175          * Pop the current name generation scope.
98176          */
98177         function popNameGenerationScope(node) {
98178             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98179                 return;
98180             }
98181             tempFlags = tempFlagsStack.pop();
98182             reservedNames = reservedNamesStack.pop();
98183         }
98184         function reserveNameInNestedScopes(name) {
98185             if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
98186                 reservedNames = ts.createMap();
98187             }
98188             reservedNames.set(name, true);
98189         }
98190         function generateNames(node) {
98191             if (!node)
98192                 return;
98193             switch (node.kind) {
98194                 case 223 /* Block */:
98195                     ts.forEach(node.statements, generateNames);
98196                     break;
98197                 case 238 /* LabeledStatement */:
98198                 case 236 /* WithStatement */:
98199                 case 228 /* DoStatement */:
98200                 case 229 /* WhileStatement */:
98201                     generateNames(node.statement);
98202                     break;
98203                 case 227 /* IfStatement */:
98204                     generateNames(node.thenStatement);
98205                     generateNames(node.elseStatement);
98206                     break;
98207                 case 230 /* ForStatement */:
98208                 case 232 /* ForOfStatement */:
98209                 case 231 /* ForInStatement */:
98210                     generateNames(node.initializer);
98211                     generateNames(node.statement);
98212                     break;
98213                 case 237 /* SwitchStatement */:
98214                     generateNames(node.caseBlock);
98215                     break;
98216                 case 251 /* CaseBlock */:
98217                     ts.forEach(node.clauses, generateNames);
98218                     break;
98219                 case 277 /* CaseClause */:
98220                 case 278 /* DefaultClause */:
98221                     ts.forEach(node.statements, generateNames);
98222                     break;
98223                 case 240 /* TryStatement */:
98224                     generateNames(node.tryBlock);
98225                     generateNames(node.catchClause);
98226                     generateNames(node.finallyBlock);
98227                     break;
98228                 case 280 /* CatchClause */:
98229                     generateNames(node.variableDeclaration);
98230                     generateNames(node.block);
98231                     break;
98232                 case 225 /* VariableStatement */:
98233                     generateNames(node.declarationList);
98234                     break;
98235                 case 243 /* VariableDeclarationList */:
98236                     ts.forEach(node.declarations, generateNames);
98237                     break;
98238                 case 242 /* VariableDeclaration */:
98239                 case 156 /* Parameter */:
98240                 case 191 /* BindingElement */:
98241                 case 245 /* ClassDeclaration */:
98242                     generateNameIfNeeded(node.name);
98243                     break;
98244                 case 244 /* FunctionDeclaration */:
98245                     generateNameIfNeeded(node.name);
98246                     if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98247                         ts.forEach(node.parameters, generateNames);
98248                         generateNames(node.body);
98249                     }
98250                     break;
98251                 case 189 /* ObjectBindingPattern */:
98252                 case 190 /* ArrayBindingPattern */:
98253                     ts.forEach(node.elements, generateNames);
98254                     break;
98255                 case 254 /* ImportDeclaration */:
98256                     generateNames(node.importClause);
98257                     break;
98258                 case 255 /* ImportClause */:
98259                     generateNameIfNeeded(node.name);
98260                     generateNames(node.namedBindings);
98261                     break;
98262                 case 256 /* NamespaceImport */:
98263                     generateNameIfNeeded(node.name);
98264                     break;
98265                 case 262 /* NamespaceExport */:
98266                     generateNameIfNeeded(node.name);
98267                     break;
98268                 case 257 /* NamedImports */:
98269                     ts.forEach(node.elements, generateNames);
98270                     break;
98271                 case 258 /* ImportSpecifier */:
98272                     generateNameIfNeeded(node.propertyName || node.name);
98273                     break;
98274             }
98275         }
98276         function generateMemberNames(node) {
98277             if (!node)
98278                 return;
98279             switch (node.kind) {
98280                 case 281 /* PropertyAssignment */:
98281                 case 282 /* ShorthandPropertyAssignment */:
98282                 case 159 /* PropertyDeclaration */:
98283                 case 161 /* MethodDeclaration */:
98284                 case 163 /* GetAccessor */:
98285                 case 164 /* SetAccessor */:
98286                     generateNameIfNeeded(node.name);
98287                     break;
98288             }
98289         }
98290         function generateNameIfNeeded(name) {
98291             if (name) {
98292                 if (ts.isGeneratedIdentifier(name)) {
98293                     generateName(name);
98294                 }
98295                 else if (ts.isBindingPattern(name)) {
98296                     generateNames(name);
98297                 }
98298             }
98299         }
98300         /**
98301          * Generate the text for a generated identifier.
98302          */
98303         function generateName(name) {
98304             if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
98305                 // Node names generate unique names based on their original node
98306                 // and are cached based on that node's id.
98307                 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
98308             }
98309             else {
98310                 // Auto, Loop, and Unique names are cached based on their unique
98311                 // autoGenerateId.
98312                 var autoGenerateId = name.autoGenerateId;
98313                 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
98314             }
98315         }
98316         function generateNameCached(node, flags) {
98317             var nodeId = ts.getNodeId(node);
98318             return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
98319         }
98320         /**
98321          * Returns a value indicating whether a name is unique globally, within the current file,
98322          * or within the NameGenerator.
98323          */
98324         function isUniqueName(name) {
98325             return isFileLevelUniqueName(name)
98326                 && !generatedNames.has(name)
98327                 && !(reservedNames && reservedNames.has(name));
98328         }
98329         /**
98330          * Returns a value indicating whether a name is unique globally or within the current file.
98331          */
98332         function isFileLevelUniqueName(name) {
98333             return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
98334         }
98335         /**
98336          * Returns a value indicating whether a name is unique within a container.
98337          */
98338         function isUniqueLocalName(name, container) {
98339             for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
98340                 if (node.locals) {
98341                     var local = node.locals.get(ts.escapeLeadingUnderscores(name));
98342                     // We conservatively include alias symbols to cover cases where they're emitted as locals
98343                     if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
98344                         return false;
98345                     }
98346                 }
98347             }
98348             return true;
98349         }
98350         /**
98351          * Return the next available name in the pattern _a ... _z, _0, _1, ...
98352          * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
98353          * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
98354          */
98355         function makeTempVariableName(flags, reservedInNestedScopes) {
98356             if (flags && !(tempFlags & flags)) {
98357                 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
98358                 if (isUniqueName(name)) {
98359                     tempFlags |= flags;
98360                     if (reservedInNestedScopes) {
98361                         reserveNameInNestedScopes(name);
98362                     }
98363                     return name;
98364                 }
98365             }
98366             while (true) {
98367                 var count = tempFlags & 268435455 /* CountMask */;
98368                 tempFlags++;
98369                 // Skip over 'i' and 'n'
98370                 if (count !== 8 && count !== 13) {
98371                     var name = count < 26
98372                         ? "_" + String.fromCharCode(97 /* a */ + count)
98373                         : "_" + (count - 26);
98374                     if (isUniqueName(name)) {
98375                         if (reservedInNestedScopes) {
98376                             reserveNameInNestedScopes(name);
98377                         }
98378                         return name;
98379                     }
98380                 }
98381             }
98382         }
98383         /**
98384          * Generate a name that is unique within the current file and doesn't conflict with any names
98385          * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
98386          * where n is a positive integer. Note that names generated by makeTempVariableName and
98387          * makeUniqueName are guaranteed to never conflict.
98388          * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
98389          */
98390         function makeUniqueName(baseName, checkFn, optimistic, scoped) {
98391             if (checkFn === void 0) { checkFn = isUniqueName; }
98392             if (optimistic) {
98393                 if (checkFn(baseName)) {
98394                     if (scoped) {
98395                         reserveNameInNestedScopes(baseName);
98396                     }
98397                     else {
98398                         generatedNames.set(baseName, true);
98399                     }
98400                     return baseName;
98401                 }
98402             }
98403             // Find the first unique 'name_n', where n is a positive number
98404             if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
98405                 baseName += "_";
98406             }
98407             var i = 1;
98408             while (true) {
98409                 var generatedName = baseName + i;
98410                 if (checkFn(generatedName)) {
98411                     if (scoped) {
98412                         reserveNameInNestedScopes(generatedName);
98413                     }
98414                     else {
98415                         generatedNames.set(generatedName, true);
98416                     }
98417                     return generatedName;
98418                 }
98419                 i++;
98420             }
98421         }
98422         function makeFileLevelOptimisticUniqueName(name) {
98423             return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
98424         }
98425         /**
98426          * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
98427          */
98428         function generateNameForModuleOrEnum(node) {
98429             var name = getTextOfNode(node.name);
98430             // Use module/enum name itself if it is unique, otherwise make a unique variation
98431             return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
98432         }
98433         /**
98434          * Generates a unique name for an ImportDeclaration or ExportDeclaration.
98435          */
98436         function generateNameForImportOrExportDeclaration(node) {
98437             var expr = ts.getExternalModuleName(node); // TODO: GH#18217
98438             var baseName = ts.isStringLiteral(expr) ?
98439                 ts.makeIdentifierFromModuleName(expr.text) : "module";
98440             return makeUniqueName(baseName);
98441         }
98442         /**
98443          * Generates a unique name for a default export.
98444          */
98445         function generateNameForExportDefault() {
98446             return makeUniqueName("default");
98447         }
98448         /**
98449          * Generates a unique name for a class expression.
98450          */
98451         function generateNameForClassExpression() {
98452             return makeUniqueName("class");
98453         }
98454         function generateNameForMethodOrAccessor(node) {
98455             if (ts.isIdentifier(node.name)) {
98456                 return generateNameCached(node.name);
98457             }
98458             return makeTempVariableName(0 /* Auto */);
98459         }
98460         /**
98461          * Generates a unique name from a node.
98462          */
98463         function generateNameForNode(node, flags) {
98464             switch (node.kind) {
98465                 case 75 /* Identifier */:
98466                     return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
98467                 case 249 /* ModuleDeclaration */:
98468                 case 248 /* EnumDeclaration */:
98469                     return generateNameForModuleOrEnum(node);
98470                 case 254 /* ImportDeclaration */:
98471                 case 260 /* ExportDeclaration */:
98472                     return generateNameForImportOrExportDeclaration(node);
98473                 case 244 /* FunctionDeclaration */:
98474                 case 245 /* ClassDeclaration */:
98475                 case 259 /* ExportAssignment */:
98476                     return generateNameForExportDefault();
98477                 case 214 /* ClassExpression */:
98478                     return generateNameForClassExpression();
98479                 case 161 /* MethodDeclaration */:
98480                 case 163 /* GetAccessor */:
98481                 case 164 /* SetAccessor */:
98482                     return generateNameForMethodOrAccessor(node);
98483                 case 154 /* ComputedPropertyName */:
98484                     return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
98485                 default:
98486                     return makeTempVariableName(0 /* Auto */);
98487             }
98488         }
98489         /**
98490          * Generates a unique identifier for a node.
98491          */
98492         function makeName(name) {
98493             switch (name.autoGenerateFlags & 7 /* KindMask */) {
98494                 case 1 /* Auto */:
98495                     return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98496                 case 2 /* Loop */:
98497                     return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98498                 case 3 /* Unique */:
98499                     return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98500             }
98501             return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
98502         }
98503         /**
98504          * Gets the node from which a name should be generated.
98505          */
98506         function getNodeForGeneratedName(name) {
98507             var autoGenerateId = name.autoGenerateId;
98508             var node = name;
98509             var original = node.original;
98510             while (original) {
98511                 node = original;
98512                 // if "node" is a different generated name (having a different
98513                 // "autoGenerateId"), use it and stop traversing.
98514                 if (ts.isIdentifier(node)
98515                     && !!(node.autoGenerateFlags & 4 /* Node */)
98516                     && node.autoGenerateId !== autoGenerateId) {
98517                     break;
98518                 }
98519                 original = node.original;
98520             }
98521             // otherwise, return the original node for the source;
98522             return node;
98523         }
98524         // Comments
98525         function pipelineEmitWithComments(hint, node) {
98526             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98527             enterComment();
98528             hasWrittenComment = false;
98529             var emitFlags = ts.getEmitFlags(node);
98530             var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
98531             var isEmittedNode = node.kind !== 325 /* NotEmittedStatement */;
98532             // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
98533             // It is expensive to walk entire tree just to set one kind of node to have no comments.
98534             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
98535             var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
98536             // Save current container state on the stack.
98537             var savedContainerPos = containerPos;
98538             var savedContainerEnd = containerEnd;
98539             var savedDeclarationListContainerEnd = declarationListContainerEnd;
98540             if ((pos > 0 || end > 0) && pos !== end) {
98541                 // Emit leading comments if the position is not synthesized and the node
98542                 // has not opted out from emitting leading comments.
98543                 if (!skipLeadingComments) {
98544                     emitLeadingComments(pos, isEmittedNode);
98545                 }
98546                 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
98547                     // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
98548                     containerPos = pos;
98549                 }
98550                 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
98551                     // As above.
98552                     containerEnd = end;
98553                     // To avoid invalid comment emit in a down-level binding pattern, we
98554                     // keep track of the last declaration list container's end
98555                     if (node.kind === 243 /* VariableDeclarationList */) {
98556                         declarationListContainerEnd = end;
98557                     }
98558                 }
98559             }
98560             ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
98561             exitComment();
98562             var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
98563             if (emitFlags & 2048 /* NoNestedComments */) {
98564                 commentsDisabled = true;
98565                 pipelinePhase(hint, node);
98566                 commentsDisabled = false;
98567             }
98568             else {
98569                 pipelinePhase(hint, node);
98570             }
98571             enterComment();
98572             ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
98573             if ((pos > 0 || end > 0) && pos !== end) {
98574                 // Restore previous container state.
98575                 containerPos = savedContainerPos;
98576                 containerEnd = savedContainerEnd;
98577                 declarationListContainerEnd = savedDeclarationListContainerEnd;
98578                 // Emit trailing comments if the position is not synthesized and the node
98579                 // has not opted out from emitting leading comments and is an emitted node.
98580                 if (!skipTrailingComments && isEmittedNode) {
98581                     emitTrailingComments(end);
98582                 }
98583             }
98584             exitComment();
98585             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98586         }
98587         function emitLeadingSynthesizedComment(comment) {
98588             if (comment.kind === 2 /* SingleLineCommentTrivia */) {
98589                 writer.writeLine();
98590             }
98591             writeSynthesizedComment(comment);
98592             if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
98593                 writer.writeLine();
98594             }
98595             else {
98596                 writer.writeSpace(" ");
98597             }
98598         }
98599         function emitTrailingSynthesizedComment(comment) {
98600             if (!writer.isAtStartOfLine()) {
98601                 writer.writeSpace(" ");
98602             }
98603             writeSynthesizedComment(comment);
98604             if (comment.hasTrailingNewLine) {
98605                 writer.writeLine();
98606             }
98607         }
98608         function writeSynthesizedComment(comment) {
98609             var text = formatSynthesizedComment(comment);
98610             var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
98611             ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
98612         }
98613         function formatSynthesizedComment(comment) {
98614             return comment.kind === 3 /* MultiLineCommentTrivia */
98615                 ? "/*" + comment.text + "*/"
98616                 : "//" + comment.text;
98617         }
98618         function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
98619             enterComment();
98620             var pos = detachedRange.pos, end = detachedRange.end;
98621             var emitFlags = ts.getEmitFlags(node);
98622             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
98623             var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
98624             if (!skipLeadingComments) {
98625                 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
98626             }
98627             exitComment();
98628             if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
98629                 commentsDisabled = true;
98630                 emitCallback(node);
98631                 commentsDisabled = false;
98632             }
98633             else {
98634                 emitCallback(node);
98635             }
98636             enterComment();
98637             if (!skipTrailingComments) {
98638                 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
98639                 if (hasWrittenComment && !writer.isAtStartOfLine()) {
98640                     writer.writeLine();
98641                 }
98642             }
98643             exitComment();
98644         }
98645         function emitLeadingComments(pos, isEmittedNode) {
98646             hasWrittenComment = false;
98647             if (isEmittedNode) {
98648                 forEachLeadingCommentToEmit(pos, emitLeadingComment);
98649             }
98650             else if (pos === 0) {
98651                 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
98652                 // unless it is a triple slash comment at the top of the file.
98653                 // For Example:
98654                 //      /// <reference-path ...>
98655                 //      declare var x;
98656                 //      /// <reference-path ...>
98657                 //      interface F {}
98658                 //  The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
98659                 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
98660             }
98661         }
98662         function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98663             if (isTripleSlashComment(commentPos, commentEnd)) {
98664                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
98665             }
98666         }
98667         function shouldWriteComment(text, pos) {
98668             if (printerOptions.onlyPrintJsDocStyle) {
98669                 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
98670             }
98671             return true;
98672         }
98673         function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98674             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98675                 return;
98676             if (!hasWrittenComment) {
98677                 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
98678                 hasWrittenComment = true;
98679             }
98680             // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
98681             emitPos(commentPos);
98682             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98683             emitPos(commentEnd);
98684             if (hasTrailingNewLine) {
98685                 writer.writeLine();
98686             }
98687             else if (kind === 3 /* MultiLineCommentTrivia */) {
98688                 writer.writeSpace(" ");
98689             }
98690         }
98691         function emitLeadingCommentsOfPosition(pos) {
98692             if (commentsDisabled || pos === -1) {
98693                 return;
98694             }
98695             emitLeadingComments(pos, /*isEmittedNode*/ true);
98696         }
98697         function emitTrailingComments(pos) {
98698             forEachTrailingCommentToEmit(pos, emitTrailingComment);
98699         }
98700         function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98701             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98702                 return;
98703             // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
98704             if (!writer.isAtStartOfLine()) {
98705                 writer.writeSpace(" ");
98706             }
98707             emitPos(commentPos);
98708             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98709             emitPos(commentEnd);
98710             if (hasTrailingNewLine) {
98711                 writer.writeLine();
98712             }
98713         }
98714         function emitTrailingCommentsOfPosition(pos, prefixSpace) {
98715             if (commentsDisabled) {
98716                 return;
98717             }
98718             enterComment();
98719             forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
98720             exitComment();
98721         }
98722         function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98723             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
98724             emitPos(commentPos);
98725             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98726             emitPos(commentEnd);
98727             if (hasTrailingNewLine) {
98728                 writer.writeLine();
98729             }
98730             else {
98731                 writer.writeSpace(" ");
98732             }
98733         }
98734         function forEachLeadingCommentToEmit(pos, cb) {
98735             // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
98736             if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
98737                 if (hasDetachedComments(pos)) {
98738                     forEachLeadingCommentWithoutDetachedComments(cb);
98739                 }
98740                 else {
98741                     ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98742                 }
98743             }
98744         }
98745         function forEachTrailingCommentToEmit(end, cb) {
98746             // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
98747             if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
98748                 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
98749             }
98750         }
98751         function hasDetachedComments(pos) {
98752             return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
98753         }
98754         function forEachLeadingCommentWithoutDetachedComments(cb) {
98755             // get the leading comments from detachedPos
98756             var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
98757             if (detachedCommentsInfo.length - 1) {
98758                 detachedCommentsInfo.pop();
98759             }
98760             else {
98761                 detachedCommentsInfo = undefined;
98762             }
98763             ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98764         }
98765         function emitDetachedCommentsAndUpdateCommentsInfo(range) {
98766             var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
98767             if (currentDetachedCommentInfo) {
98768                 if (detachedCommentsInfo) {
98769                     detachedCommentsInfo.push(currentDetachedCommentInfo);
98770                 }
98771                 else {
98772                     detachedCommentsInfo = [currentDetachedCommentInfo];
98773                 }
98774             }
98775         }
98776         function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
98777             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98778                 return;
98779             emitPos(commentPos);
98780             ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
98781             emitPos(commentEnd);
98782         }
98783         /**
98784          * Determine if the given comment is a triple-slash
98785          *
98786          * @return true if the comment is a triple-slash comment else false
98787          */
98788         function isTripleSlashComment(commentPos, commentEnd) {
98789             return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
98790         }
98791         // Source Maps
98792         function getParsedSourceMap(node) {
98793             if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
98794                 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
98795             }
98796             return node.parsedSourceMap || undefined;
98797         }
98798         function pipelineEmitWithSourceMap(hint, node) {
98799             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98800             var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
98801             if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
98802                 pipelinePhase(hint, node);
98803             }
98804             else if (ts.isUnparsedNode(node)) {
98805                 var parsed = getParsedSourceMap(node.parent);
98806                 if (parsed && sourceMapGenerator) {
98807                     sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
98808                 }
98809                 pipelinePhase(hint, node);
98810             }
98811             else {
98812                 var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
98813                 var emitFlags = ts.getEmitFlags(node);
98814                 if (node.kind !== 325 /* NotEmittedStatement */
98815                     && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
98816                     && pos >= 0) {
98817                     emitSourcePos(source, skipSourceTrivia(source, pos));
98818                 }
98819                 if (emitFlags & 64 /* NoNestedSourceMaps */) {
98820                     sourceMapsDisabled = true;
98821                     pipelinePhase(hint, node);
98822                     sourceMapsDisabled = false;
98823                 }
98824                 else {
98825                     pipelinePhase(hint, node);
98826                 }
98827                 if (node.kind !== 325 /* NotEmittedStatement */
98828                     && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
98829                     && end >= 0) {
98830                     emitSourcePos(source, end);
98831                 }
98832             }
98833             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98834         }
98835         /**
98836          * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
98837          */
98838         function skipSourceTrivia(source, pos) {
98839             return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
98840         }
98841         /**
98842          * Emits a mapping.
98843          *
98844          * If the position is synthetic (undefined or a negative value), no mapping will be
98845          * created.
98846          *
98847          * @param pos The position.
98848          */
98849         function emitPos(pos) {
98850             if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
98851                 return;
98852             }
98853             var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
98854             sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, 
98855             /*nameIndex*/ undefined);
98856         }
98857         function emitSourcePos(source, pos) {
98858             if (source !== sourceMapSource) {
98859                 var savedSourceMapSource = sourceMapSource;
98860                 setSourceMapSource(source);
98861                 emitPos(pos);
98862                 setSourceMapSource(savedSourceMapSource);
98863             }
98864             else {
98865                 emitPos(pos);
98866             }
98867         }
98868         /**
98869          * Emits a token of a node with possible leading and trailing source maps.
98870          *
98871          * @param node The node containing the token.
98872          * @param token The token to emit.
98873          * @param tokenStartPos The start pos of the token.
98874          * @param emitCallback The callback used to emit the token.
98875          */
98876         function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
98877             if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
98878                 return emitCallback(token, writer, tokenPos);
98879             }
98880             var emitNode = node && node.emitNode;
98881             var emitFlags = emitNode && emitNode.flags || 0 /* None */;
98882             var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
98883             var source = range && range.source || sourceMapSource;
98884             tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
98885             if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
98886                 emitSourcePos(source, tokenPos);
98887             }
98888             tokenPos = emitCallback(token, writer, tokenPos);
98889             if (range)
98890                 tokenPos = range.end;
98891             if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
98892                 emitSourcePos(source, tokenPos);
98893             }
98894             return tokenPos;
98895         }
98896         function setSourceMapSource(source) {
98897             if (sourceMapsDisabled) {
98898                 return;
98899             }
98900             sourceMapSource = source;
98901             if (isJsonSourceMapSource(source)) {
98902                 return;
98903             }
98904             sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
98905             if (printerOptions.inlineSources) {
98906                 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
98907             }
98908         }
98909         function isJsonSourceMapSource(sourceFile) {
98910             return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
98911         }
98912     }
98913     ts.createPrinter = createPrinter;
98914     function createBracketsMap() {
98915         var brackets = [];
98916         brackets[1024 /* Braces */] = ["{", "}"];
98917         brackets[2048 /* Parenthesis */] = ["(", ")"];
98918         brackets[4096 /* AngleBrackets */] = ["<", ">"];
98919         brackets[8192 /* SquareBrackets */] = ["[", "]"];
98920         return brackets;
98921     }
98922     function getOpeningBracket(format) {
98923         return brackets[format & 15360 /* BracketsMask */][0];
98924     }
98925     function getClosingBracket(format) {
98926         return brackets[format & 15360 /* BracketsMask */][1];
98927     }
98928     // Flags enum to track count of temp variables and a few dedicated names
98929     var TempFlags;
98930     (function (TempFlags) {
98931         TempFlags[TempFlags["Auto"] = 0] = "Auto";
98932         TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
98933         TempFlags[TempFlags["_i"] = 268435456] = "_i";
98934     })(TempFlags || (TempFlags = {}));
98935 })(ts || (ts = {}));
98936 /* @internal */
98937 var ts;
98938 (function (ts) {
98939     function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
98940         if (!host.getDirectories || !host.readDirectory) {
98941             return undefined;
98942         }
98943         var cachedReadDirectoryResult = ts.createMap();
98944         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
98945         return {
98946             useCaseSensitiveFileNames: useCaseSensitiveFileNames,
98947             fileExists: fileExists,
98948             readFile: function (path, encoding) { return host.readFile(path, encoding); },
98949             directoryExists: host.directoryExists && directoryExists,
98950             getDirectories: getDirectories,
98951             readDirectory: readDirectory,
98952             createDirectory: host.createDirectory && createDirectory,
98953             writeFile: host.writeFile && writeFile,
98954             addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
98955             addOrDeleteFile: addOrDeleteFile,
98956             clearCache: clearCache,
98957             realpath: host.realpath && realpath
98958         };
98959         function toPath(fileName) {
98960             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
98961         }
98962         function getCachedFileSystemEntries(rootDirPath) {
98963             return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
98964         }
98965         function getCachedFileSystemEntriesForBaseDir(path) {
98966             return getCachedFileSystemEntries(ts.getDirectoryPath(path));
98967         }
98968         function getBaseNameOfFileName(fileName) {
98969             return ts.getBaseFileName(ts.normalizePath(fileName));
98970         }
98971         function createCachedFileSystemEntries(rootDir, rootDirPath) {
98972             var resultFromHost = {
98973                 files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
98974                 directories: host.getDirectories(rootDir) || []
98975             };
98976             cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
98977             return resultFromHost;
98978         }
98979         /**
98980          * If the readDirectory result was already cached, it returns that
98981          * Otherwise gets result from host and caches it.
98982          * The host request is done under try catch block to avoid caching incorrect result
98983          */
98984         function tryReadDirectory(rootDir, rootDirPath) {
98985             rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
98986             var cachedResult = getCachedFileSystemEntries(rootDirPath);
98987             if (cachedResult) {
98988                 return cachedResult;
98989             }
98990             try {
98991                 return createCachedFileSystemEntries(rootDir, rootDirPath);
98992             }
98993             catch (_e) {
98994                 // If there is exception to read directories, dont cache the result and direct the calls to host
98995                 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
98996                 return undefined;
98997             }
98998         }
98999         function fileNameEqual(name1, name2) {
99000             return getCanonicalFileName(name1) === getCanonicalFileName(name2);
99001         }
99002         function hasEntry(entries, name) {
99003             return ts.some(entries, function (file) { return fileNameEqual(file, name); });
99004         }
99005         function updateFileSystemEntry(entries, baseName, isValid) {
99006             if (hasEntry(entries, baseName)) {
99007                 if (!isValid) {
99008                     return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
99009                 }
99010             }
99011             else if (isValid) {
99012                 return entries.push(baseName);
99013             }
99014         }
99015         function writeFile(fileName, data, writeByteOrderMark) {
99016             var path = toPath(fileName);
99017             var result = getCachedFileSystemEntriesForBaseDir(path);
99018             if (result) {
99019                 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
99020             }
99021             return host.writeFile(fileName, data, writeByteOrderMark);
99022         }
99023         function fileExists(fileName) {
99024             var path = toPath(fileName);
99025             var result = getCachedFileSystemEntriesForBaseDir(path);
99026             return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
99027                 host.fileExists(fileName);
99028         }
99029         function directoryExists(dirPath) {
99030             var path = toPath(dirPath);
99031             return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
99032         }
99033         function createDirectory(dirPath) {
99034             var path = toPath(dirPath);
99035             var result = getCachedFileSystemEntriesForBaseDir(path);
99036             var baseFileName = getBaseNameOfFileName(dirPath);
99037             if (result) {
99038                 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
99039             }
99040             host.createDirectory(dirPath);
99041         }
99042         function getDirectories(rootDir) {
99043             var rootDirPath = toPath(rootDir);
99044             var result = tryReadDirectory(rootDir, rootDirPath);
99045             if (result) {
99046                 return result.directories.slice();
99047             }
99048             return host.getDirectories(rootDir);
99049         }
99050         function readDirectory(rootDir, extensions, excludes, includes, depth) {
99051             var rootDirPath = toPath(rootDir);
99052             var result = tryReadDirectory(rootDir, rootDirPath);
99053             if (result) {
99054                 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
99055             }
99056             return host.readDirectory(rootDir, extensions, excludes, includes, depth);
99057             function getFileSystemEntries(dir) {
99058                 var path = toPath(dir);
99059                 if (path === rootDirPath) {
99060                     return result;
99061                 }
99062                 return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
99063             }
99064         }
99065         function realpath(s) {
99066             return host.realpath ? host.realpath(s) : s;
99067         }
99068         function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
99069             var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
99070             if (existingResult) {
99071                 // Just clear the cache for now
99072                 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
99073                 clearCache();
99074                 return undefined;
99075             }
99076             var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
99077             if (!parentResult) {
99078                 return undefined;
99079             }
99080             // This was earlier a file (hence not in cached directory contents)
99081             // or we never cached the directory containing it
99082             if (!host.directoryExists) {
99083                 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
99084                 clearCache();
99085                 return undefined;
99086             }
99087             var baseName = getBaseNameOfFileName(fileOrDirectory);
99088             var fsQueryResult = {
99089                 fileExists: host.fileExists(fileOrDirectoryPath),
99090                 directoryExists: host.directoryExists(fileOrDirectoryPath)
99091             };
99092             if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
99093                 // Folder added or removed, clear the cache instead of updating the folder and its structure
99094                 clearCache();
99095             }
99096             else {
99097                 // No need to update the directory structure, just files
99098                 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
99099             }
99100             return fsQueryResult;
99101         }
99102         function addOrDeleteFile(fileName, filePath, eventKind) {
99103             if (eventKind === ts.FileWatcherEventKind.Changed) {
99104                 return;
99105             }
99106             var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
99107             if (parentResult) {
99108                 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
99109             }
99110         }
99111         function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
99112             updateFileSystemEntry(parentResult.files, baseName, fileExists);
99113         }
99114         function clearCache() {
99115             cachedReadDirectoryResult.clear();
99116         }
99117     }
99118     ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
99119     var ConfigFileProgramReloadLevel;
99120     (function (ConfigFileProgramReloadLevel) {
99121         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
99122         /** Update the file name list from the disk */
99123         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
99124         /** Reload completely by re-reading contents of config file from disk and updating program */
99125         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
99126     })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
99127     /**
99128      * Updates the existing missing file watches with the new set of missing files after new program is created
99129      */
99130     function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
99131         var missingFilePaths = program.getMissingFilePaths();
99132         var newMissingFilePathMap = ts.arrayToSet(missingFilePaths);
99133         // Update the missing file paths watcher
99134         ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
99135             // Watch the missing files
99136             createNewValue: createMissingFileWatch,
99137             // Files that are no longer missing (e.g. because they are no longer required)
99138             // should no longer be watched.
99139             onDeleteValue: ts.closeFileWatcher
99140         });
99141     }
99142     ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
99143     /**
99144      * Updates the existing wild card directory watches with the new set of wild card directories from the config file
99145      * after new program is created because the config file was reloaded or program was created first time from the config file
99146      * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
99147      * as wildcard directories wont change unless reloading config file
99148      */
99149     function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
99150         ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
99151             // Create new watch and recursive info
99152             createNewValue: createWildcardDirectoryWatcher,
99153             // Close existing watch thats not needed any more
99154             onDeleteValue: closeFileWatcherOf,
99155             // Close existing watch that doesnt match in the flags
99156             onExistingValue: updateWildcardDirectoryWatcher
99157         });
99158         function createWildcardDirectoryWatcher(directory, flags) {
99159             // Create new watch and recursive info
99160             return {
99161                 watcher: watchDirectory(directory, flags),
99162                 flags: flags
99163             };
99164         }
99165         function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
99166             // Watcher needs to be updated if the recursive flags dont match
99167             if (existingWatcher.flags === flags) {
99168                 return;
99169             }
99170             existingWatcher.watcher.close();
99171             existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
99172         }
99173     }
99174     ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
99175     function isEmittedFileOfProgram(program, file) {
99176         if (!program) {
99177             return false;
99178         }
99179         return program.isEmittedFile(file);
99180     }
99181     ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
99182     var WatchLogLevel;
99183     (function (WatchLogLevel) {
99184         WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
99185         WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
99186         WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
99187     })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
99188     function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
99189         return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
99190     }
99191     ts.getWatchFactory = getWatchFactory;
99192     function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
99193         var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
99194         var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
99195         var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
99196         if (watchLogLevel === WatchLogLevel.Verbose && ts.sysLog === ts.noop) {
99197             ts.setSysLog(function (s) { return log(s); });
99198         }
99199         return {
99200             watchFile: function (host, file, callback, pollingInterval, options, detailInfo1, detailInfo2) {
99201                 return createFileWatcher(host, file, callback, pollingInterval, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99202             },
99203             watchFilePath: function (host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2) {
99204                 return createFilePathWatcher(host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99205             },
99206             watchDirectory: function (host, directory, callback, flags, options, detailInfo1, detailInfo2) {
99207                 return createDirectoryWatcher(host, directory, callback, flags, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
99208             }
99209         };
99210     }
99211     function watchFile(host, file, callback, pollingInterval, options) {
99212         return host.watchFile(file, callback, pollingInterval, options);
99213     }
99214     function watchFilePath(host, file, callback, pollingInterval, options, path) {
99215         return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options);
99216     }
99217     function watchDirectory(host, directory, callback, flags, options) {
99218         return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options);
99219     }
99220     function getCreateFileWatcher(watchLogLevel, addWatch) {
99221         switch (watchLogLevel) {
99222             case WatchLogLevel.None:
99223                 return addWatch;
99224             case WatchLogLevel.TriggerOnly:
99225                 return createFileWatcherWithTriggerLogging;
99226             case WatchLogLevel.Verbose:
99227                 return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
99228         }
99229     }
99230     function createFileWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99231         log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99232         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99233         return {
99234             close: function () {
99235                 log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99236                 watcher.close();
99237             }
99238         };
99239     }
99240     function createDirectoryWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99241         var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99242         log(watchInfo);
99243         var start = ts.timestamp();
99244         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99245         var elapsed = ts.timestamp() - start;
99246         log("Elapsed:: " + elapsed + "ms " + watchInfo);
99247         return {
99248             close: function () {
99249                 var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99250                 log(watchInfo);
99251                 var start = ts.timestamp();
99252                 watcher.close();
99253                 var elapsed = ts.timestamp() - start;
99254                 log("Elapsed:: " + elapsed + "ms " + watchInfo);
99255             }
99256         };
99257     }
99258     function createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99259         return addWatch(host, file, function (fileName, cbOptional) {
99260             var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99261             log(triggerredInfo);
99262             var start = ts.timestamp();
99263             cb(fileName, cbOptional, passThrough);
99264             var elapsed = ts.timestamp() - start;
99265             log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
99266         }, flags, options);
99267     }
99268     function getFallbackOptions(options) {
99269         var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
99270         return {
99271             watchFile: fallbackPolling !== undefined ?
99272                 fallbackPolling :
99273                 ts.WatchFileKind.PriorityPollingInterval
99274         };
99275     }
99276     ts.getFallbackOptions = getFallbackOptions;
99277     function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
99278         return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
99279     }
99280     function closeFileWatcherOf(objWithWatcher) {
99281         objWithWatcher.watcher.close();
99282     }
99283     ts.closeFileWatcherOf = closeFileWatcherOf;
99284 })(ts || (ts = {}));
99285 var ts;
99286 (function (ts) {
99287     function findConfigFile(searchPath, fileExists, configName) {
99288         if (configName === void 0) { configName = "tsconfig.json"; }
99289         return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
99290             var fileName = ts.combinePaths(ancestor, configName);
99291             return fileExists(fileName) ? fileName : undefined;
99292         });
99293     }
99294     ts.findConfigFile = findConfigFile;
99295     function resolveTripleslashReference(moduleName, containingFile) {
99296         var basePath = ts.getDirectoryPath(containingFile);
99297         var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
99298         return ts.normalizePath(referencedFileName);
99299     }
99300     ts.resolveTripleslashReference = resolveTripleslashReference;
99301     /* @internal */
99302     function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
99303         var commonPathComponents;
99304         var failed = ts.forEach(fileNames, function (sourceFile) {
99305             // Each file contributes into common source file path
99306             var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
99307             sourcePathComponents.pop(); // The base file name is not part of the common directory path
99308             if (!commonPathComponents) {
99309                 // first file
99310                 commonPathComponents = sourcePathComponents;
99311                 return;
99312             }
99313             var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
99314             for (var i = 0; i < n; i++) {
99315                 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
99316                     if (i === 0) {
99317                         // Failed to find any common path component
99318                         return true;
99319                     }
99320                     // New common path found that is 0 -> i-1
99321                     commonPathComponents.length = i;
99322                     break;
99323                 }
99324             }
99325             // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
99326             if (sourcePathComponents.length < commonPathComponents.length) {
99327                 commonPathComponents.length = sourcePathComponents.length;
99328             }
99329         });
99330         // A common path can not be found when paths span multiple drives on windows, for example
99331         if (failed) {
99332             return "";
99333         }
99334         if (!commonPathComponents) { // Can happen when all input files are .d.ts files
99335             return currentDirectory;
99336         }
99337         return ts.getPathFromPathComponents(commonPathComponents);
99338     }
99339     ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
99340     function createCompilerHost(options, setParentNodes) {
99341         return createCompilerHostWorker(options, setParentNodes);
99342     }
99343     ts.createCompilerHost = createCompilerHost;
99344     /*@internal*/
99345     // TODO(shkamat): update this after reworking ts build API
99346     function createCompilerHostWorker(options, setParentNodes, system) {
99347         if (system === void 0) { system = ts.sys; }
99348         var existingDirectories = ts.createMap();
99349         var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
99350         function getSourceFile(fileName, languageVersion, onError) {
99351             var text;
99352             try {
99353                 ts.performance.mark("beforeIORead");
99354                 text = compilerHost.readFile(fileName);
99355                 ts.performance.mark("afterIORead");
99356                 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
99357             }
99358             catch (e) {
99359                 if (onError) {
99360                     onError(e.message);
99361                 }
99362                 text = "";
99363             }
99364             return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
99365         }
99366         function directoryExists(directoryPath) {
99367             if (existingDirectories.has(directoryPath)) {
99368                 return true;
99369             }
99370             if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
99371                 existingDirectories.set(directoryPath, true);
99372                 return true;
99373             }
99374             return false;
99375         }
99376         function writeFile(fileName, data, writeByteOrderMark, onError) {
99377             try {
99378                 ts.performance.mark("beforeIOWrite");
99379                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
99380                 // the system.writeFile will do its own directory creation and
99381                 // the ensureDirectoriesExist call will always be redundant.
99382                 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); });
99383                 ts.performance.mark("afterIOWrite");
99384                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
99385             }
99386             catch (e) {
99387                 if (onError) {
99388                     onError(e.message);
99389                 }
99390             }
99391         }
99392         var outputFingerprints;
99393         function writeFileWorker(fileName, data, writeByteOrderMark) {
99394             if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) {
99395                 system.writeFile(fileName, data, writeByteOrderMark);
99396                 return;
99397             }
99398             if (!outputFingerprints) {
99399                 outputFingerprints = ts.createMap();
99400             }
99401             var hash = system.createHash(data);
99402             var mtimeBefore = system.getModifiedTime(fileName);
99403             if (mtimeBefore) {
99404                 var fingerprint = outputFingerprints.get(fileName);
99405                 // If output has not been changed, and the file has no external modification
99406                 if (fingerprint &&
99407                     fingerprint.byteOrderMark === writeByteOrderMark &&
99408                     fingerprint.hash === hash &&
99409                     fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
99410                     return;
99411                 }
99412             }
99413             system.writeFile(fileName, data, writeByteOrderMark);
99414             var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
99415             outputFingerprints.set(fileName, {
99416                 hash: hash,
99417                 byteOrderMark: writeByteOrderMark,
99418                 mtime: mtimeAfter
99419             });
99420         }
99421         function getDefaultLibLocation() {
99422             return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
99423         }
99424         var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
99425         var realpath = system.realpath && (function (path) { return system.realpath(path); });
99426         var compilerHost = {
99427             getSourceFile: getSourceFile,
99428             getDefaultLibLocation: getDefaultLibLocation,
99429             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
99430             writeFile: writeFile,
99431             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
99432             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
99433             getCanonicalFileName: getCanonicalFileName,
99434             getNewLine: function () { return newLine; },
99435             fileExists: function (fileName) { return system.fileExists(fileName); },
99436             readFile: function (fileName) { return system.readFile(fileName); },
99437             trace: function (s) { return system.write(s + newLine); },
99438             directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
99439             getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
99440             getDirectories: function (path) { return system.getDirectories(path); },
99441             realpath: realpath,
99442             readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
99443             createDirectory: function (d) { return system.createDirectory(d); },
99444             createHash: ts.maybeBind(system, system.createHash)
99445         };
99446         return compilerHost;
99447     }
99448     ts.createCompilerHostWorker = createCompilerHostWorker;
99449     /*@internal*/
99450     function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
99451         var originalReadFile = host.readFile;
99452         var originalFileExists = host.fileExists;
99453         var originalDirectoryExists = host.directoryExists;
99454         var originalCreateDirectory = host.createDirectory;
99455         var originalWriteFile = host.writeFile;
99456         var readFileCache = ts.createMap();
99457         var fileExistsCache = ts.createMap();
99458         var directoryExistsCache = ts.createMap();
99459         var sourceFileCache = ts.createMap();
99460         var readFileWithCache = function (fileName) {
99461             var key = toPath(fileName);
99462             var value = readFileCache.get(key);
99463             if (value !== undefined)
99464                 return value !== false ? value : undefined;
99465             return setReadFileCache(key, fileName);
99466         };
99467         var setReadFileCache = function (key, fileName) {
99468             var newValue = originalReadFile.call(host, fileName);
99469             readFileCache.set(key, newValue !== undefined ? newValue : false);
99470             return newValue;
99471         };
99472         host.readFile = function (fileName) {
99473             var key = toPath(fileName);
99474             var value = readFileCache.get(key);
99475             if (value !== undefined)
99476                 return value !== false ? value : undefined; // could be .d.ts from output
99477             // Cache json or buildInfo
99478             if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
99479                 return originalReadFile.call(host, fileName);
99480             }
99481             return setReadFileCache(key, fileName);
99482         };
99483         var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
99484             var key = toPath(fileName);
99485             var value = sourceFileCache.get(key);
99486             if (value)
99487                 return value;
99488             var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
99489             if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
99490                 sourceFileCache.set(key, sourceFile);
99491             }
99492             return sourceFile;
99493         } : undefined;
99494         // fileExists for any kind of extension
99495         host.fileExists = function (fileName) {
99496             var key = toPath(fileName);
99497             var value = fileExistsCache.get(key);
99498             if (value !== undefined)
99499                 return value;
99500             var newValue = originalFileExists.call(host, fileName);
99501             fileExistsCache.set(key, !!newValue);
99502             return newValue;
99503         };
99504         if (originalWriteFile) {
99505             host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
99506                 var key = toPath(fileName);
99507                 fileExistsCache.delete(key);
99508                 var value = readFileCache.get(key);
99509                 if (value !== undefined && value !== data) {
99510                     readFileCache.delete(key);
99511                     sourceFileCache.delete(key);
99512                 }
99513                 else if (getSourceFileWithCache) {
99514                     var sourceFile = sourceFileCache.get(key);
99515                     if (sourceFile && sourceFile.text !== data) {
99516                         sourceFileCache.delete(key);
99517                     }
99518                 }
99519                 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
99520             };
99521         }
99522         // directoryExists
99523         if (originalDirectoryExists && originalCreateDirectory) {
99524             host.directoryExists = function (directory) {
99525                 var key = toPath(directory);
99526                 var value = directoryExistsCache.get(key);
99527                 if (value !== undefined)
99528                     return value;
99529                 var newValue = originalDirectoryExists.call(host, directory);
99530                 directoryExistsCache.set(key, !!newValue);
99531                 return newValue;
99532             };
99533             host.createDirectory = function (directory) {
99534                 var key = toPath(directory);
99535                 directoryExistsCache.delete(key);
99536                 originalCreateDirectory.call(host, directory);
99537             };
99538         }
99539         return {
99540             originalReadFile: originalReadFile,
99541             originalFileExists: originalFileExists,
99542             originalDirectoryExists: originalDirectoryExists,
99543             originalCreateDirectory: originalCreateDirectory,
99544             originalWriteFile: originalWriteFile,
99545             getSourceFileWithCache: getSourceFileWithCache,
99546             readFileWithCache: readFileWithCache
99547         };
99548     }
99549     ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
99550     function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
99551         var diagnostics;
99552         diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
99553         diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
99554         diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
99555         diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
99556         diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
99557         if (ts.getEmitDeclarations(program.getCompilerOptions())) {
99558             diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
99559         }
99560         return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
99561     }
99562     ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
99563     function formatDiagnostics(diagnostics, host) {
99564         var output = "";
99565         for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
99566             var diagnostic = diagnostics_2[_i];
99567             output += formatDiagnostic(diagnostic, host);
99568         }
99569         return output;
99570     }
99571     ts.formatDiagnostics = formatDiagnostics;
99572     function formatDiagnostic(diagnostic, host) {
99573         var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
99574         if (diagnostic.file) {
99575             var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
99576             var fileName = diagnostic.file.fileName;
99577             var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
99578             return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
99579         }
99580         return errorMessage;
99581     }
99582     ts.formatDiagnostic = formatDiagnostic;
99583     /** @internal */
99584     var ForegroundColorEscapeSequences;
99585     (function (ForegroundColorEscapeSequences) {
99586         ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
99587         ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
99588         ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
99589         ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
99590         ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
99591     })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
99592     var gutterStyleSequence = "\u001b[7m";
99593     var gutterSeparator = " ";
99594     var resetEscapeSequence = "\u001b[0m";
99595     var ellipsis = "...";
99596     var halfIndent = "  ";
99597     var indent = "    ";
99598     function getCategoryFormat(category) {
99599         switch (category) {
99600             case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
99601             case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
99602             case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
99603             case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
99604         }
99605     }
99606     /** @internal */
99607     function formatColorAndReset(text, formatStyle) {
99608         return formatStyle + text + resetEscapeSequence;
99609     }
99610     ts.formatColorAndReset = formatColorAndReset;
99611     function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
99612         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
99613         var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
99614         var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
99615         var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
99616         var gutterWidth = (lastLine + 1 + "").length;
99617         if (hasMoreThanFiveLines) {
99618             gutterWidth = Math.max(ellipsis.length, gutterWidth);
99619         }
99620         var context = "";
99621         for (var i = firstLine; i <= lastLine; i++) {
99622             context += host.getNewLine();
99623             // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
99624             // so we'll skip ahead to the second-to-last line.
99625             if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
99626                 context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
99627                 i = lastLine - 1;
99628             }
99629             var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
99630             var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
99631             var lineContent = file.text.slice(lineStart, lineEnd);
99632             lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
99633             lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
99634             // Output the gutter and the actual contents of the line.
99635             context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
99636             context += lineContent + host.getNewLine();
99637             // Output the gutter and the error span for the line using tildes.
99638             context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
99639             context += squiggleColor;
99640             if (i === firstLine) {
99641                 // If we're on the last line, then limit it to the last character of the last line.
99642                 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
99643                 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
99644                 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
99645                 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
99646             }
99647             else if (i === lastLine) {
99648                 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
99649             }
99650             else {
99651                 // Squiggle the entire line.
99652                 context += lineContent.replace(/./g, "~");
99653             }
99654             context += resetEscapeSequence;
99655         }
99656         return context;
99657     }
99658     /* @internal */
99659     function formatLocation(file, start, host, color) {
99660         if (color === void 0) { color = formatColorAndReset; }
99661         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
99662         var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
99663         var output = "";
99664         output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
99665         output += ":";
99666         output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
99667         output += ":";
99668         output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
99669         return output;
99670     }
99671     ts.formatLocation = formatLocation;
99672     function formatDiagnosticsWithColorAndContext(diagnostics, host) {
99673         var output = "";
99674         for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
99675             var diagnostic = diagnostics_3[_i];
99676             if (diagnostic.file) {
99677                 var file = diagnostic.file, start = diagnostic.start;
99678                 output += formatLocation(file, start, host); // TODO: GH#18217
99679                 output += " - ";
99680             }
99681             output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
99682             output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
99683             output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
99684             if (diagnostic.file) {
99685                 output += host.getNewLine();
99686                 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
99687                 if (diagnostic.relatedInformation) {
99688                     output += host.getNewLine();
99689                     for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
99690                         var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText;
99691                         if (file) {
99692                             output += host.getNewLine();
99693                             output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
99694                             output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
99695                         }
99696                         output += host.getNewLine();
99697                         output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
99698                     }
99699                 }
99700             }
99701             output += host.getNewLine();
99702         }
99703         return output;
99704     }
99705     ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
99706     function flattenDiagnosticMessageText(diag, newLine, indent) {
99707         if (indent === void 0) { indent = 0; }
99708         if (ts.isString(diag)) {
99709             return diag;
99710         }
99711         else if (diag === undefined) {
99712             return "";
99713         }
99714         var result = "";
99715         if (indent) {
99716             result += newLine;
99717             for (var i = 0; i < indent; i++) {
99718                 result += "  ";
99719             }
99720         }
99721         result += diag.messageText;
99722         indent++;
99723         if (diag.next) {
99724             for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
99725                 var kid = _a[_i];
99726                 result += flattenDiagnosticMessageText(kid, newLine, indent);
99727             }
99728         }
99729         return result;
99730     }
99731     ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
99732     /* @internal */
99733     function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
99734         if (names.length === 0) {
99735             return [];
99736         }
99737         var resolutions = [];
99738         var cache = ts.createMap();
99739         for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
99740             var name = names_2[_i];
99741             var result = void 0;
99742             if (cache.has(name)) {
99743                 result = cache.get(name);
99744             }
99745             else {
99746                 cache.set(name, result = loader(name, containingFile, redirectedReference));
99747             }
99748             resolutions.push(result);
99749         }
99750         return resolutions;
99751     }
99752     ts.loadWithLocalCache = loadWithLocalCache;
99753     /* @internal */
99754     ts.inferredTypesContainingFile = "__inferred type names__.ts";
99755     /**
99756      * Determines if program structure is upto date or needs to be recreated
99757      */
99758     /* @internal */
99759     function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
99760         // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
99761         if (!program || hasChangedAutomaticTypeDirectiveNames) {
99762             return false;
99763         }
99764         // If root file names don't match
99765         if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
99766             return false;
99767         }
99768         var seenResolvedRefs;
99769         // If project references don't match
99770         if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
99771             return false;
99772         }
99773         // If any file is not up-to-date, then the whole program is not up-to-date
99774         if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
99775             return false;
99776         }
99777         // If any of the missing file paths are now created
99778         if (program.getMissingFilePaths().some(fileExists)) {
99779             return false;
99780         }
99781         var currentOptions = program.getCompilerOptions();
99782         // If the compilation settings do no match, then the program is not up-to-date
99783         if (!ts.compareDataObjects(currentOptions, newOptions)) {
99784             return false;
99785         }
99786         // If everything matches but the text of config file is changed,
99787         // error locations can change for program options, so update the program
99788         if (currentOptions.configFile && newOptions.configFile) {
99789             return currentOptions.configFile.text === newOptions.configFile.text;
99790         }
99791         return true;
99792         function sourceFileNotUptoDate(sourceFile) {
99793             return !sourceFileVersionUptoDate(sourceFile) ||
99794                 hasInvalidatedResolution(sourceFile.path);
99795         }
99796         function sourceFileVersionUptoDate(sourceFile) {
99797             return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
99798         }
99799         function projectReferenceUptoDate(oldRef, newRef, index) {
99800             if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
99801                 return false;
99802             }
99803             return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
99804         }
99805         function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
99806             if (oldResolvedRef) {
99807                 if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
99808                     // Assume true
99809                     return true;
99810                 }
99811                 // If sourceFile for the oldResolvedRef existed, check the version for uptodate
99812                 if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
99813                     return false;
99814                 }
99815                 // Add to seen before checking the referenced paths of this config file
99816                 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
99817                 // If child project references are upto date, this project reference is uptodate
99818                 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
99819                     return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
99820                 });
99821             }
99822             // In old program, not able to resolve project reference path,
99823             // so if config file doesnt exist, it is uptodate.
99824             return !fileExists(resolveProjectReferencePath(oldRef));
99825         }
99826     }
99827     ts.isProgramUptoDate = isProgramUptoDate;
99828     function getConfigFileParsingDiagnostics(configFileParseResult) {
99829         return configFileParseResult.options.configFile ? __spreadArrays(configFileParseResult.options.configFile.parseDiagnostics, configFileParseResult.errors) :
99830             configFileParseResult.errors;
99831     }
99832     ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
99833     /**
99834      * Determine if source file needs to be re-created even if its text hasn't changed
99835      */
99836     function shouldProgramCreateNewSourceFiles(program, newOptions) {
99837         if (!program)
99838             return false;
99839         // If any compiler options change, we can't reuse old source file even if version match
99840         // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
99841         var oldOptions = program.getCompilerOptions();
99842         return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
99843             return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
99844         });
99845     }
99846     function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
99847         return {
99848             rootNames: rootNames,
99849             options: options,
99850             host: host,
99851             oldProgram: oldProgram,
99852             configFileParsingDiagnostics: configFileParsingDiagnostics
99853         };
99854     }
99855     function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
99856         var _a;
99857         var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
99858         var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
99859         var oldProgram = createProgramOptions.oldProgram;
99860         var processingDefaultLibFiles;
99861         var processingOtherFiles;
99862         var files;
99863         var symlinks;
99864         var commonSourceDirectory;
99865         var diagnosticsProducingTypeChecker;
99866         var noDiagnosticsTypeChecker;
99867         var classifiableNames;
99868         var ambientModuleNameToUnmodifiedFileName = ts.createMap();
99869         // Todo:: Use this to report why file was included in --extendedDiagnostics
99870         var refFileMap;
99871         var cachedBindAndCheckDiagnosticsForFile = {};
99872         var cachedDeclarationDiagnosticsForFile = {};
99873         var resolvedTypeReferenceDirectives = ts.createMap();
99874         var fileProcessingDiagnostics = ts.createDiagnosticCollection();
99875         // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
99876         // This works as imported modules are discovered recursively in a depth first manner, specifically:
99877         // - For each root file, findSourceFile is called.
99878         // - This calls processImportedModules for each module imported in the source file.
99879         // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
99880         // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
99881         // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
99882         var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
99883         var currentNodeModulesDepth = 0;
99884         // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
99885         // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
99886         var modulesWithElidedImports = ts.createMap();
99887         // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
99888         var sourceFilesFoundSearchingNodeModules = ts.createMap();
99889         ts.performance.mark("beforeProgram");
99890         var host = createProgramOptions.host || createCompilerHost(options);
99891         var configParsingHost = parseConfigHostFromCompilerHostLike(host);
99892         var skipDefaultLib = options.noLib;
99893         var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
99894         var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
99895         var programDiagnostics = ts.createDiagnosticCollection();
99896         var currentDirectory = host.getCurrentDirectory();
99897         var supportedExtensions = ts.getSupportedExtensions(options);
99898         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
99899         // Map storing if there is emit blocking diagnostics for given input
99900         var hasEmitBlockingDiagnostics = ts.createMap();
99901         var _compilerOptionsObjectLiteralSyntax;
99902         var moduleResolutionCache;
99903         var actualResolveModuleNamesWorker;
99904         var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
99905         if (host.resolveModuleNames) {
99906             actualResolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) {
99907                 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
99908                 if (!resolved || resolved.extension !== undefined) {
99909                     return resolved;
99910                 }
99911                 var withExtension = ts.clone(resolved);
99912                 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
99913                 return withExtension;
99914             }); };
99915         }
99916         else {
99917             moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options);
99918             var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
99919             actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
99920         }
99921         var actualResolveTypeReferenceDirectiveNamesWorker;
99922         if (host.resolveTypeReferenceDirectives) {
99923             actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
99924         }
99925         else {
99926             var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
99927             actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
99928         }
99929         // Map from a stringified PackageId to the source file with that id.
99930         // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
99931         // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
99932         var packageIdToSourceFile = ts.createMap();
99933         // Maps from a SourceFile's `.path` to the name of the package it was imported with.
99934         var sourceFileToPackageName = ts.createMap();
99935         // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
99936         var redirectTargetsMap = ts.createMultiMap();
99937         /**
99938          * map with
99939          * - SourceFile if present
99940          * - false if sourceFile missing for source of project reference redirect
99941          * - undefined otherwise
99942          */
99943         var filesByName = ts.createMap();
99944         var missingFilePaths;
99945         // stores 'filename -> file association' ignoring case
99946         // used to track cases when two file names differ only in casing
99947         var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
99948         // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
99949         var resolvedProjectReferences;
99950         var projectReferenceRedirects;
99951         var mapFromFileToProjectReferenceRedirects;
99952         var mapFromToProjectReferenceRedirectSource;
99953         var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) &&
99954             !options.disableSourceOfProjectReferenceRedirect;
99955         var _b = updateHostForUseSourceOfProjectReferenceRedirect({
99956             compilerHost: host,
99957             useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
99958             toPath: toPath,
99959             getResolvedProjectReferences: getResolvedProjectReferences,
99960             getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
99961             forEachResolvedProjectReference: forEachResolvedProjectReference
99962         }), onProgramCreateComplete = _b.onProgramCreateComplete, fileExists = _b.fileExists;
99963         var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
99964         // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
99965         // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
99966         var structuralIsReused;
99967         structuralIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
99968         if (structuralIsReused !== 2 /* Completely */) {
99969             processingDefaultLibFiles = [];
99970             processingOtherFiles = [];
99971             if (projectReferences) {
99972                 if (!resolvedProjectReferences) {
99973                     resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
99974                 }
99975                 if (rootNames.length) {
99976                     for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
99977                         var parsedRef = resolvedProjectReferences_1[_i];
99978                         if (!parsedRef)
99979                             continue;
99980                         var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
99981                         if (useSourceOfProjectReferenceRedirect) {
99982                             if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
99983                                 for (var _c = 0, _d = parsedRef.commandLine.fileNames; _c < _d.length; _c++) {
99984                                     var fileName = _d[_c];
99985                                     processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
99986                                 }
99987                             }
99988                         }
99989                         else {
99990                             if (out) {
99991                                 processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
99992                             }
99993                             else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
99994                                 for (var _e = 0, _f = parsedRef.commandLine.fileNames; _e < _f.length; _e++) {
99995                                     var fileName = _f[_e];
99996                                     if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
99997                                         processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
99998                                     }
99999                                 }
100000                             }
100001                         }
100002                     }
100003                 }
100004             }
100005             ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
100006             // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
100007             var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
100008             if (typeReferences.length) {
100009                 // This containingFilename needs to match with the one used in managed-side
100010                 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
100011                 var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
100012                 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
100013                 for (var i = 0; i < typeReferences.length; i++) {
100014                     processTypeReferenceDirective(typeReferences[i], resolutions[i]);
100015                 }
100016             }
100017             // Do not process the default library if:
100018             //  - The '--noLib' flag is used.
100019             //  - A 'no-default-lib' reference comment is encountered in
100020             //      processing the root files.
100021             if (rootNames.length && !skipDefaultLib) {
100022                 // If '--lib' is not specified, include default library file according to '--target'
100023                 // otherwise, using options specified in '--lib' instead of '--target' default library file
100024                 var defaultLibraryFileName = getDefaultLibraryFileName();
100025                 if (!options.lib && defaultLibraryFileName) {
100026                     processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
100027                 }
100028                 else {
100029                     ts.forEach(options.lib, function (libFileName) {
100030                         processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
100031                     });
100032                 }
100033             }
100034             missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
100035                 var path = _a[0], file = _a[1];
100036                 return file === undefined ? path : undefined;
100037             }));
100038             files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
100039             processingDefaultLibFiles = undefined;
100040             processingOtherFiles = undefined;
100041         }
100042         ts.Debug.assert(!!missingFilePaths);
100043         // Release any files we have acquired in the old program but are
100044         // not part of the new program.
100045         if (oldProgram && host.onReleaseOldSourceFile) {
100046             var oldSourceFiles = oldProgram.getSourceFiles();
100047             for (var _g = 0, oldSourceFiles_1 = oldSourceFiles; _g < oldSourceFiles_1.length; _g++) {
100048                 var oldSourceFile = oldSourceFiles_1[_g];
100049                 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
100050                 if (shouldCreateNewSourceFile || !newFile ||
100051                     // old file wasnt redirect but new file is
100052                     (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
100053                     host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
100054                 }
100055             }
100056             oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) {
100057                 if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) {
100058                     host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
100059                 }
100060             });
100061         }
100062         // unconditionally set oldProgram to undefined to prevent it from being captured in closure
100063         oldProgram = undefined;
100064         var program = {
100065             getRootFileNames: function () { return rootNames; },
100066             getSourceFile: getSourceFile,
100067             getSourceFileByPath: getSourceFileByPath,
100068             getSourceFiles: function () { return files; },
100069             getMissingFilePaths: function () { return missingFilePaths; },
100070             getRefFileMap: function () { return refFileMap; },
100071             getFilesByNameMap: function () { return filesByName; },
100072             getCompilerOptions: function () { return options; },
100073             getSyntacticDiagnostics: getSyntacticDiagnostics,
100074             getOptionsDiagnostics: getOptionsDiagnostics,
100075             getGlobalDiagnostics: getGlobalDiagnostics,
100076             getSemanticDiagnostics: getSemanticDiagnostics,
100077             getSuggestionDiagnostics: getSuggestionDiagnostics,
100078             getDeclarationDiagnostics: getDeclarationDiagnostics,
100079             getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
100080             getProgramDiagnostics: getProgramDiagnostics,
100081             getTypeChecker: getTypeChecker,
100082             getClassifiableNames: getClassifiableNames,
100083             getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
100084             getCommonSourceDirectory: getCommonSourceDirectory,
100085             emit: emit,
100086             getCurrentDirectory: function () { return currentDirectory; },
100087             getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
100088             getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
100089             getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
100090             getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
100091             getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); },
100092             getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
100093             getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
100094             getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
100095             isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100096             isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
100097             dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
100098             getSourceFileFromReference: getSourceFileFromReference,
100099             getLibFileFromReference: getLibFileFromReference,
100100             sourceFileToPackageName: sourceFileToPackageName,
100101             redirectTargetsMap: redirectTargetsMap,
100102             isEmittedFile: isEmittedFile,
100103             getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
100104             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
100105             getProjectReferences: getProjectReferences,
100106             getResolvedProjectReferences: getResolvedProjectReferences,
100107             getProjectReferenceRedirect: getProjectReferenceRedirect,
100108             getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100109             getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
100110             forEachResolvedProjectReference: forEachResolvedProjectReference,
100111             isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100112             emitBuildInfo: emitBuildInfo,
100113             fileExists: fileExists,
100114             getProbableSymlinks: getProbableSymlinks,
100115             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100116         };
100117         onProgramCreateComplete();
100118         verifyCompilerOptions();
100119         ts.performance.mark("afterProgram");
100120         ts.performance.measure("Program", "beforeProgram", "afterProgram");
100121         return program;
100122         function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference) {
100123             ts.performance.mark("beforeResolveModule");
100124             var result = actualResolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference);
100125             ts.performance.mark("afterResolveModule");
100126             ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
100127             return result;
100128         }
100129         function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference) {
100130             ts.performance.mark("beforeResolveTypeReference");
100131             var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference);
100132             ts.performance.mark("afterResolveTypeReference");
100133             ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
100134             return result;
100135         }
100136         function compareDefaultLibFiles(a, b) {
100137             return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
100138         }
100139         function getDefaultLibFilePriority(a) {
100140             if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
100141                 var basename = ts.getBaseFileName(a.fileName);
100142                 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
100143                     return 0;
100144                 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
100145                 var index = ts.libs.indexOf(name);
100146                 if (index !== -1)
100147                     return index + 1;
100148             }
100149             return ts.libs.length + 2;
100150         }
100151         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
100152             return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
100153         }
100154         function toPath(fileName) {
100155             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
100156         }
100157         function getCommonSourceDirectory() {
100158             if (commonSourceDirectory === undefined) {
100159                 var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
100160                 if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
100161                     // If a rootDir is specified use it as the commonSourceDirectory
100162                     commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
100163                 }
100164                 else if (options.composite && options.configFilePath) {
100165                     // Project compilations never infer their root from the input source paths
100166                     commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
100167                     checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
100168                 }
100169                 else {
100170                     commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
100171                 }
100172                 if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
100173                     // Make sure directory path ends with directory separator so this string can directly
100174                     // used to replace with "" to get the relative path of the source file and the relative path doesn't
100175                     // start with / making it rooted path
100176                     commonSourceDirectory += ts.directorySeparator;
100177                 }
100178             }
100179             return commonSourceDirectory;
100180         }
100181         function getClassifiableNames() {
100182             if (!classifiableNames) {
100183                 // Initialize a checker so that all our files are bound.
100184                 getTypeChecker();
100185                 classifiableNames = ts.createUnderscoreEscapedMap();
100186                 for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
100187                     var sourceFile = files_2[_i];
100188                     ts.copyEntries(sourceFile.classifiableNames, classifiableNames);
100189                 }
100190             }
100191             return classifiableNames;
100192         }
100193         function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) {
100194             if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
100195                 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
100196                 // the best we can do is fallback to the default logic.
100197                 return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName));
100198             }
100199             var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile);
100200             if (oldSourceFile !== file && file.resolvedModules) {
100201                 // `file` was created for the new program.
100202                 //
100203                 // We only set `file.resolvedModules` via work from the current function,
100204                 // so it is defined iff we already called the current function on `file`.
100205                 // That call happened no later than the creation of the `file` object,
100206                 // which per above occurred during the current program creation.
100207                 // Since we assume the filesystem does not change during program creation,
100208                 // it is safe to reuse resolutions from the earlier call.
100209                 var result_11 = [];
100210                 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
100211                     var moduleName = moduleNames_1[_i];
100212                     var resolvedModule = file.resolvedModules.get(moduleName);
100213                     result_11.push(resolvedModule);
100214                 }
100215                 return result_11;
100216             }
100217             // At this point, we know at least one of the following hold:
100218             // - file has local declarations for ambient modules
100219             // - old program state is available
100220             // With this information, we can infer some module resolutions without performing resolution.
100221             /** An ordered list of module names for which we cannot recover the resolution. */
100222             var unknownModuleNames;
100223             /**
100224              * The indexing of elements in this list matches that of `moduleNames`.
100225              *
100226              * Before combining results, result[i] is in one of the following states:
100227              * * undefined: needs to be recomputed,
100228              * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
100229              * Needs to be reset to undefined before returning,
100230              * * ResolvedModuleFull instance: can be reused.
100231              */
100232             var result;
100233             var reusedNames;
100234             /** A transient placeholder used to mark predicted resolution in the result list. */
100235             var predictedToResolveToAmbientModuleMarker = {};
100236             for (var i = 0; i < moduleNames.length; i++) {
100237                 var moduleName = moduleNames[i];
100238                 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
100239                 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
100240                     var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName);
100241                     if (oldResolvedModule) {
100242                         if (ts.isTraceEnabled(options, host)) {
100243                             ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile);
100244                         }
100245                         (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
100246                         (reusedNames || (reusedNames = [])).push(moduleName);
100247                         continue;
100248                     }
100249                 }
100250                 // We know moduleName resolves to an ambient module provided that moduleName:
100251                 // - is in the list of ambient modules locally declared in the current source file.
100252                 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
100253                 //   (so the same module declaration will land in the new program)
100254                 var resolvesToAmbientModuleInNonModifiedFile = false;
100255                 if (ts.contains(file.ambientModuleNames, moduleName)) {
100256                     resolvesToAmbientModuleInNonModifiedFile = true;
100257                     if (ts.isTraceEnabled(options, host)) {
100258                         ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile);
100259                     }
100260                 }
100261                 else {
100262                     resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
100263                 }
100264                 if (resolvesToAmbientModuleInNonModifiedFile) {
100265                     (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
100266                 }
100267                 else {
100268                     // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
100269                     (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
100270                 }
100271             }
100272             var resolutions = unknownModuleNames && unknownModuleNames.length
100273                 ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName))
100274                 : ts.emptyArray;
100275             // Combine results of resolutions and predicted results
100276             if (!result) {
100277                 // There were no unresolved/ambient resolutions.
100278                 ts.Debug.assert(resolutions.length === moduleNames.length);
100279                 return resolutions;
100280             }
100281             var j = 0;
100282             for (var i = 0; i < result.length; i++) {
100283                 if (result[i]) {
100284                     // `result[i]` is either a `ResolvedModuleFull` or a marker.
100285                     // If it is the former, we can leave it as is.
100286                     if (result[i] === predictedToResolveToAmbientModuleMarker) {
100287                         result[i] = undefined; // TODO: GH#18217
100288                     }
100289                 }
100290                 else {
100291                     result[i] = resolutions[j];
100292                     j++;
100293                 }
100294             }
100295             ts.Debug.assert(j === resolutions.length);
100296             return result;
100297             // If we change our policy of rechecking failed lookups on each program create,
100298             // we should adjust the value returned here.
100299             function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
100300                 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
100301                 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
100302                 if (resolutionToFile && resolvedFile) {
100303                     // In the old program, we resolved to an ambient module that was in the same
100304                     //   place as we expected to find an actual module file.
100305                     // We actually need to return 'false' here even though this seems like a 'true' case
100306                     //   because the normal module resolution algorithm will find this anyway.
100307                     return false;
100308                 }
100309                 // at least one of declarations should come from non-modified source file
100310                 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
100311                 if (!unmodifiedFile) {
100312                     return false;
100313                 }
100314                 if (ts.isTraceEnabled(options, host)) {
100315                     ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
100316                 }
100317                 return true;
100318             }
100319         }
100320         function canReuseProjectReferences() {
100321             return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) {
100322                 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
100323                 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
100324                 if (oldResolvedRef) {
100325                     // Resolved project reference has gone missing or changed
100326                     return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
100327                 }
100328                 else {
100329                     // A previously-unresolved reference may be resolved now
100330                     return newResolvedRef !== undefined;
100331                 }
100332             }, function (oldProjectReferences, parent) {
100333                 // If array of references is changed, we cant resue old program
100334                 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
100335                 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
100336             });
100337         }
100338         function tryReuseStructureFromOldProgram() {
100339             if (!oldProgram) {
100340                 return 0 /* Not */;
100341             }
100342             // check properties that can affect structure of the program or module resolution strategy
100343             // if any of these properties has changed - structure cannot be reused
100344             var oldOptions = oldProgram.getCompilerOptions();
100345             if (ts.changesAffectModuleResolution(oldOptions, options)) {
100346                 return oldProgram.structureIsReused = 0 /* Not */;
100347             }
100348             ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */)));
100349             // there is an old program, check if we can reuse its structure
100350             var oldRootNames = oldProgram.getRootFileNames();
100351             if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
100352                 return oldProgram.structureIsReused = 0 /* Not */;
100353             }
100354             if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
100355                 return oldProgram.structureIsReused = 0 /* Not */;
100356             }
100357             // Check if any referenced project tsconfig files are different
100358             if (!canReuseProjectReferences()) {
100359                 return oldProgram.structureIsReused = 0 /* Not */;
100360             }
100361             if (projectReferences) {
100362                 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
100363             }
100364             // check if program source files has changed in the way that can affect structure of the program
100365             var newSourceFiles = [];
100366             var modifiedSourceFiles = [];
100367             oldProgram.structureIsReused = 2 /* Completely */;
100368             // If the missing file paths are now present, it can change the progam structure,
100369             // and hence cant reuse the structure.
100370             // This is same as how we dont reuse the structure if one of the file from old program is now missing
100371             if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
100372                 return oldProgram.structureIsReused = 0 /* Not */;
100373             }
100374             var oldSourceFiles = oldProgram.getSourceFiles();
100375             var SeenPackageName;
100376             (function (SeenPackageName) {
100377                 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
100378                 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
100379             })(SeenPackageName || (SeenPackageName = {}));
100380             var seenPackageNames = ts.createMap();
100381             for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
100382                 var oldSourceFile = oldSourceFiles_2[_i];
100383                 var newSourceFile = host.getSourceFileByPath
100384                     ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
100385                     : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
100386                 if (!newSourceFile) {
100387                     return oldProgram.structureIsReused = 0 /* Not */;
100388                 }
100389                 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
100390                 var fileChanged = void 0;
100391                 if (oldSourceFile.redirectInfo) {
100392                     // We got `newSourceFile` by path, so it is actually for the unredirected file.
100393                     // This lets us know if the unredirected file has changed. If it has we should break the redirect.
100394                     if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
100395                         // Underlying file has changed. Might not redirect anymore. Must rebuild program.
100396                         return oldProgram.structureIsReused = 0 /* Not */;
100397                     }
100398                     fileChanged = false;
100399                     newSourceFile = oldSourceFile; // Use the redirect.
100400                 }
100401                 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
100402                     // If a redirected-to source file changes, the redirect may be broken.
100403                     if (newSourceFile !== oldSourceFile) {
100404                         return oldProgram.structureIsReused = 0 /* Not */;
100405                     }
100406                     fileChanged = false;
100407                 }
100408                 else {
100409                     fileChanged = newSourceFile !== oldSourceFile;
100410                 }
100411                 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
100412                 newSourceFile.path = oldSourceFile.path;
100413                 newSourceFile.originalFileName = oldSourceFile.originalFileName;
100414                 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
100415                 newSourceFile.fileName = oldSourceFile.fileName;
100416                 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
100417                 if (packageName !== undefined) {
100418                     // If there are 2 different source files for the same package name and at least one of them changes,
100419                     // they might become redirects. So we must rebuild the program.
100420                     var prevKind = seenPackageNames.get(packageName);
100421                     var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
100422                     if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
100423                         return oldProgram.structureIsReused = 0 /* Not */;
100424                     }
100425                     seenPackageNames.set(packageName, newKind);
100426                 }
100427                 if (fileChanged) {
100428                     // The `newSourceFile` object was created for the new program.
100429                     if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
100430                         // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
100431                         return oldProgram.structureIsReused = 0 /* Not */;
100432                     }
100433                     if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
100434                         // value of no-default-lib has changed
100435                         // this will affect if default library is injected into the list of files
100436                         oldProgram.structureIsReused = 1 /* SafeModules */;
100437                     }
100438                     // check tripleslash references
100439                     if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
100440                         // tripleslash references has changed
100441                         oldProgram.structureIsReused = 1 /* SafeModules */;
100442                     }
100443                     // check imports and module augmentations
100444                     collectExternalModuleReferences(newSourceFile);
100445                     if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
100446                         // imports has changed
100447                         oldProgram.structureIsReused = 1 /* SafeModules */;
100448                     }
100449                     if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
100450                         // moduleAugmentations has changed
100451                         oldProgram.structureIsReused = 1 /* SafeModules */;
100452                     }
100453                     if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
100454                         // dynamicImport has changed
100455                         oldProgram.structureIsReused = 1 /* SafeModules */;
100456                     }
100457                     if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
100458                         // 'types' references has changed
100459                         oldProgram.structureIsReused = 1 /* SafeModules */;
100460                     }
100461                     // tentatively approve the file
100462                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100463                 }
100464                 else if (hasInvalidatedResolution(oldSourceFile.path)) {
100465                     // 'module/types' references could have changed
100466                     oldProgram.structureIsReused = 1 /* SafeModules */;
100467                     // add file to the modified list so that we will resolve it later
100468                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100469                 }
100470                 // if file has passed all checks it should be safe to reuse it
100471                 newSourceFiles.push(newSourceFile);
100472             }
100473             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100474                 return oldProgram.structureIsReused;
100475             }
100476             var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
100477             for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) {
100478                 var oldFile = oldSourceFiles_3[_a];
100479                 if (!ts.contains(modifiedFiles, oldFile)) {
100480                     for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) {
100481                         var moduleName = _c[_b];
100482                         ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
100483                     }
100484                 }
100485             }
100486             // try to verify results of module resolution
100487             for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) {
100488                 var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile;
100489                 var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory);
100490                 var moduleNames = getModuleNames(newSourceFile);
100491                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile);
100492                 // ensure that module resolution results are still correct
100493                 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
100494                 if (resolutionsChanged) {
100495                     oldProgram.structureIsReused = 1 /* SafeModules */;
100496                     newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
100497                 }
100498                 else {
100499                     newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
100500                 }
100501                 if (resolveTypeReferenceDirectiveNamesWorker) {
100502                     // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
100503                     var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
100504                     var resolutions_1 = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName));
100505                     // ensure that types resolutions are still correct
100506                     var resolutionsChanged_1 = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions_1, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
100507                     if (resolutionsChanged_1) {
100508                         oldProgram.structureIsReused = 1 /* SafeModules */;
100509                         newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions_1);
100510                     }
100511                     else {
100512                         newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
100513                     }
100514                 }
100515             }
100516             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100517                 return oldProgram.structureIsReused;
100518             }
100519             if (host.hasChangedAutomaticTypeDirectiveNames) {
100520                 return oldProgram.structureIsReused = 1 /* SafeModules */;
100521             }
100522             missingFilePaths = oldProgram.getMissingFilePaths();
100523             refFileMap = oldProgram.getRefFileMap();
100524             // update fileName -> file mapping
100525             ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
100526             for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) {
100527                 var newSourceFile = newSourceFiles_1[_f];
100528                 filesByName.set(newSourceFile.path, newSourceFile);
100529             }
100530             var oldFilesByNameMap = oldProgram.getFilesByNameMap();
100531             oldFilesByNameMap.forEach(function (oldFile, path) {
100532                 if (!oldFile) {
100533                     filesByName.set(path, oldFile);
100534                     return;
100535                 }
100536                 if (oldFile.path === path) {
100537                     // Set the file as found during node modules search if it was found that way in old progra,
100538                     if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
100539                         sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
100540                     }
100541                     return;
100542                 }
100543                 filesByName.set(path, filesByName.get(oldFile.path));
100544             });
100545             files = newSourceFiles;
100546             fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
100547             for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) {
100548                 var modifiedFile = modifiedSourceFiles_2[_g];
100549                 fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
100550             }
100551             resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
100552             sourceFileToPackageName = oldProgram.sourceFileToPackageName;
100553             redirectTargetsMap = oldProgram.redirectTargetsMap;
100554             return oldProgram.structureIsReused = 2 /* Completely */;
100555         }
100556         function getEmitHost(writeFileCallback) {
100557             return {
100558                 getPrependNodes: getPrependNodes,
100559                 getCanonicalFileName: getCanonicalFileName,
100560                 getCommonSourceDirectory: program.getCommonSourceDirectory,
100561                 getCompilerOptions: program.getCompilerOptions,
100562                 getCurrentDirectory: function () { return currentDirectory; },
100563                 getNewLine: function () { return host.getNewLine(); },
100564                 getSourceFile: program.getSourceFile,
100565                 getSourceFileByPath: program.getSourceFileByPath,
100566                 getSourceFiles: program.getSourceFiles,
100567                 getLibFileFromReference: program.getLibFileFromReference,
100568                 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100569                 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100570                 getProjectReferenceRedirect: getProjectReferenceRedirect,
100571                 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100572                 getProbableSymlinks: getProbableSymlinks,
100573                 writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }),
100574                 isEmitBlocked: isEmitBlocked,
100575                 readFile: function (f) { return host.readFile(f); },
100576                 fileExists: function (f) {
100577                     // Use local caches
100578                     var path = toPath(f);
100579                     if (getSourceFileByPath(path))
100580                         return true;
100581                     if (ts.contains(missingFilePaths, path))
100582                         return false;
100583                     // Before falling back to the host
100584                     return host.fileExists(f);
100585                 },
100586                 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100587                 getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
100588                 getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
100589                 redirectTargetsMap: redirectTargetsMap,
100590             };
100591         }
100592         function emitBuildInfo(writeFileCallback) {
100593             ts.Debug.assert(!options.out && !options.outFile);
100594             ts.performance.mark("beforeEmit");
100595             var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), 
100596             /*targetSourceFile*/ undefined, 
100597             /*transformers*/ ts.noTransformers, 
100598             /*emitOnlyDtsFiles*/ false, 
100599             /*onlyBuildInfo*/ true);
100600             ts.performance.mark("afterEmit");
100601             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100602             return emitResult;
100603         }
100604         function getResolvedProjectReferences() {
100605             return resolvedProjectReferences;
100606         }
100607         function getProjectReferences() {
100608             return projectReferences;
100609         }
100610         function getPrependNodes() {
100611             return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
100612                 var path = toPath(fileName);
100613                 var sourceFile = getSourceFileByPath(path);
100614                 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
100615             });
100616         }
100617         function isSourceFileFromExternalLibrary(file) {
100618             return !!sourceFilesFoundSearchingNodeModules.get(file.path);
100619         }
100620         function isSourceFileDefaultLibrary(file) {
100621             if (file.hasNoDefaultLib) {
100622                 return true;
100623             }
100624             if (!options.noLib) {
100625                 return false;
100626             }
100627             // If '--lib' is not specified, include default library file according to '--target'
100628             // otherwise, using options specified in '--lib' instead of '--target' default library file
100629             var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
100630             if (!options.lib) {
100631                 return equalityComparer(file.fileName, getDefaultLibraryFileName());
100632             }
100633             else {
100634                 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
100635             }
100636         }
100637         function getDiagnosticsProducingTypeChecker() {
100638             return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
100639         }
100640         function dropDiagnosticsProducingTypeChecker() {
100641             diagnosticsProducingTypeChecker = undefined;
100642         }
100643         function getTypeChecker() {
100644             return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
100645         }
100646         function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
100647             return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
100648         }
100649         function isEmitBlocked(emitFileName) {
100650             return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
100651         }
100652         function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
100653             if (!forceDtsEmit) {
100654                 var result = handleNoEmitOptions(program, sourceFile, cancellationToken);
100655                 if (result)
100656                     return result;
100657             }
100658             // Create the emit resolver outside of the "emitTime" tracking code below.  That way
100659             // any cost associated with it (like type checking) are appropriate associated with
100660             // the type-checking counter.
100661             //
100662             // If the -out option is specified, we should not pass the source file to getEmitResolver.
100663             // This is because in the -out scenario all files need to be emitted, and therefore all
100664             // files need to be type checked. And the way to specify that all files need to be type
100665             // checked is to not pass the file to getEmitResolver.
100666             var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
100667             ts.performance.mark("beforeEmit");
100668             var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles, 
100669             /*onlyBuildInfo*/ false, forceDtsEmit);
100670             ts.performance.mark("afterEmit");
100671             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100672             return emitResult;
100673         }
100674         function getSourceFile(fileName) {
100675             return getSourceFileByPath(toPath(fileName));
100676         }
100677         function getSourceFileByPath(path) {
100678             return filesByName.get(path) || undefined;
100679         }
100680         function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
100681             if (sourceFile) {
100682                 return getDiagnostics(sourceFile, cancellationToken);
100683             }
100684             return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
100685                 if (cancellationToken) {
100686                     cancellationToken.throwIfCancellationRequested();
100687                 }
100688                 return getDiagnostics(sourceFile, cancellationToken);
100689             }));
100690         }
100691         function getSyntacticDiagnostics(sourceFile, cancellationToken) {
100692             return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
100693         }
100694         function getSemanticDiagnostics(sourceFile, cancellationToken) {
100695             return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
100696         }
100697         function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
100698             return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
100699         }
100700         function getProgramDiagnostics(sourceFile) {
100701             if (ts.skipTypeChecking(sourceFile, options, program)) {
100702                 return ts.emptyArray;
100703             }
100704             var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
100705             var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
100706             return getMergedProgramDiagnostics(sourceFile, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
100707         }
100708         function getMergedProgramDiagnostics(sourceFile) {
100709             var _a;
100710             var allDiagnostics = [];
100711             for (var _i = 1; _i < arguments.length; _i++) {
100712                 allDiagnostics[_i - 1] = arguments[_i];
100713             }
100714             var flatDiagnostics = ts.flatten(allDiagnostics);
100715             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100716                 return flatDiagnostics;
100717             }
100718             return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics).diagnostics;
100719         }
100720         function getDeclarationDiagnostics(sourceFile, cancellationToken) {
100721             var options = program.getCompilerOptions();
100722             // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
100723             if (!sourceFile || options.out || options.outFile) {
100724                 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
100725             }
100726             else {
100727                 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
100728             }
100729         }
100730         function getSyntacticDiagnosticsForFile(sourceFile) {
100731             // For JavaScript files, we report semantic errors for using TypeScript-only
100732             // constructs from within a JavaScript file as syntactic errors.
100733             if (ts.isSourceFileJS(sourceFile)) {
100734                 if (!sourceFile.additionalSyntacticDiagnostics) {
100735                     sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
100736                 }
100737                 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
100738             }
100739             return sourceFile.parseDiagnostics;
100740         }
100741         function runWithCancellationToken(func) {
100742             try {
100743                 return func();
100744             }
100745             catch (e) {
100746                 if (e instanceof ts.OperationCanceledException) {
100747                     // We were canceled while performing the operation.  Because our type checker
100748                     // might be a bad state, we need to throw it away.
100749                     //
100750                     // Note: we are overly aggressive here.  We do not actually *have* to throw away
100751                     // the "noDiagnosticsTypeChecker".  However, for simplicity, i'd like to keep
100752                     // the lifetimes of these two TypeCheckers the same.  Also, we generally only
100753                     // cancel when the user has made a change anyways.  And, in that case, we (the
100754                     // program instance) will get thrown away anyways.  So trying to keep one of
100755                     // these type checkers alive doesn't serve much purpose.
100756                     noDiagnosticsTypeChecker = undefined;
100757                     diagnosticsProducingTypeChecker = undefined;
100758                 }
100759                 throw e;
100760             }
100761         }
100762         function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
100763             return ts.concatenate(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), getProgramDiagnostics(sourceFile));
100764         }
100765         function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
100766             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
100767         }
100768         function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
100769             return runWithCancellationToken(function () {
100770                 if (ts.skipTypeChecking(sourceFile, options, program)) {
100771                     return ts.emptyArray;
100772                 }
100773                 var typeChecker = getDiagnosticsProducingTypeChecker();
100774                 ts.Debug.assert(!!sourceFile.bindDiagnostics);
100775                 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
100776                 var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
100777                 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
100778                 var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
100779                     sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
100780                 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
100781                 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
100782                 return getMergedBindAndCheckDiagnostics(sourceFile, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
100783             });
100784         }
100785         function getMergedBindAndCheckDiagnostics(sourceFile) {
100786             var _a;
100787             var allDiagnostics = [];
100788             for (var _i = 1; _i < arguments.length; _i++) {
100789                 allDiagnostics[_i - 1] = arguments[_i];
100790             }
100791             var flatDiagnostics = ts.flatten(allDiagnostics);
100792             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100793                 return flatDiagnostics;
100794             }
100795             var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives;
100796             for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) {
100797                 var errorExpectation = _d[_c];
100798                 diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive));
100799             }
100800             return diagnostics;
100801         }
100802         /**
100803          * Creates a map of comment directives along with the diagnostics immediately preceded by one of them.
100804          * Comments that match to any of those diagnostics are marked as used.
100805          */
100806         function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
100807             // Diagnostics are only reported if there is no comment directive preceding them
100808             // This will modify the directives map by marking "used" ones with a corresponding diagnostic
100809             var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives);
100810             var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; });
100811             return { diagnostics: diagnostics, directives: directives };
100812         }
100813         function getSuggestionDiagnostics(sourceFile, cancellationToken) {
100814             return runWithCancellationToken(function () {
100815                 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
100816             });
100817         }
100818         /**
100819          * @returns The line index marked as preceding the diagnostic, or -1 if none was.
100820          */
100821         function markPrecedingCommentDirectiveLine(diagnostic, directives) {
100822             var file = diagnostic.file, start = diagnostic.start;
100823             if (!file) {
100824                 return -1;
100825             }
100826             // Start out with the line just before the text
100827             var lineStarts = ts.getLineStarts(file);
100828             var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217
100829             while (line >= 0) {
100830                 // As soon as that line is known to have a comment directive, use that
100831                 if (directives.markUsed(line)) {
100832                     return line;
100833                 }
100834                 // Stop searching if the line is not empty and not a comment
100835                 var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
100836                 if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
100837                     return -1;
100838                 }
100839                 line--;
100840             }
100841             return -1;
100842         }
100843         function getJSSyntacticDiagnosticsForFile(sourceFile) {
100844             return runWithCancellationToken(function () {
100845                 var diagnostics = [];
100846                 walk(sourceFile, sourceFile);
100847                 ts.forEachChildRecursively(sourceFile, walk, walkArray);
100848                 return diagnostics;
100849                 function walk(node, parent) {
100850                     // Return directly from the case if the given node doesnt want to visit each child
100851                     // Otherwise break to visit each child
100852                     switch (parent.kind) {
100853                         case 156 /* Parameter */:
100854                         case 159 /* PropertyDeclaration */:
100855                         case 161 /* MethodDeclaration */:
100856                             if (parent.questionToken === node) {
100857                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
100858                                 return "skip";
100859                             }
100860                         // falls through
100861                         case 160 /* MethodSignature */:
100862                         case 162 /* Constructor */:
100863                         case 163 /* GetAccessor */:
100864                         case 164 /* SetAccessor */:
100865                         case 201 /* FunctionExpression */:
100866                         case 244 /* FunctionDeclaration */:
100867                         case 202 /* ArrowFunction */:
100868                         case 242 /* VariableDeclaration */:
100869                             // type annotation
100870                             if (parent.type === node) {
100871                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
100872                                 return "skip";
100873                             }
100874                     }
100875                     switch (node.kind) {
100876                         case 255 /* ImportClause */:
100877                             if (node.isTypeOnly) {
100878                                 diagnostics.push(createDiagnosticForNode(node.parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
100879                                 return "skip";
100880                             }
100881                             break;
100882                         case 260 /* ExportDeclaration */:
100883                             if (node.isTypeOnly) {
100884                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
100885                                 return "skip";
100886                             }
100887                             break;
100888                         case 253 /* ImportEqualsDeclaration */:
100889                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
100890                             return "skip";
100891                         case 259 /* ExportAssignment */:
100892                             if (node.isExportEquals) {
100893                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
100894                                 return "skip";
100895                             }
100896                             break;
100897                         case 279 /* HeritageClause */:
100898                             var heritageClause = node;
100899                             if (heritageClause.token === 113 /* ImplementsKeyword */) {
100900                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
100901                                 return "skip";
100902                             }
100903                             break;
100904                         case 246 /* InterfaceDeclaration */:
100905                             var interfaceKeyword = ts.tokenToString(114 /* InterfaceKeyword */);
100906                             ts.Debug.assertIsDefined(interfaceKeyword);
100907                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
100908                             return "skip";
100909                         case 249 /* ModuleDeclaration */:
100910                             var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(136 /* NamespaceKeyword */) : ts.tokenToString(135 /* ModuleKeyword */);
100911                             ts.Debug.assertIsDefined(moduleKeyword);
100912                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
100913                             return "skip";
100914                         case 247 /* TypeAliasDeclaration */:
100915                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
100916                             return "skip";
100917                         case 248 /* EnumDeclaration */:
100918                             var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(88 /* EnumKeyword */));
100919                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
100920                             return "skip";
100921                         case 218 /* NonNullExpression */:
100922                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
100923                             return "skip";
100924                         case 217 /* AsExpression */:
100925                             diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
100926                             return "skip";
100927                         case 199 /* TypeAssertionExpression */:
100928                             ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
100929                     }
100930                 }
100931                 function walkArray(nodes, parent) {
100932                     if (parent.decorators === nodes && !options.experimentalDecorators) {
100933                         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));
100934                     }
100935                     switch (parent.kind) {
100936                         case 245 /* ClassDeclaration */:
100937                         case 214 /* ClassExpression */:
100938                         case 161 /* MethodDeclaration */:
100939                         case 162 /* Constructor */:
100940                         case 163 /* GetAccessor */:
100941                         case 164 /* SetAccessor */:
100942                         case 201 /* FunctionExpression */:
100943                         case 244 /* FunctionDeclaration */:
100944                         case 202 /* ArrowFunction */:
100945                             // Check type parameters
100946                             if (nodes === parent.typeParameters) {
100947                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
100948                                 return "skip";
100949                             }
100950                         // falls through
100951                         case 225 /* VariableStatement */:
100952                             // Check modifiers
100953                             if (nodes === parent.modifiers) {
100954                                 checkModifiers(parent.modifiers, parent.kind === 225 /* VariableStatement */);
100955                                 return "skip";
100956                             }
100957                             break;
100958                         case 159 /* PropertyDeclaration */:
100959                             // Check modifiers of property declaration
100960                             if (nodes === parent.modifiers) {
100961                                 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
100962                                     var modifier = _a[_i];
100963                                     if (modifier.kind !== 120 /* StaticKeyword */) {
100964                                         diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
100965                                     }
100966                                 }
100967                                 return "skip";
100968                             }
100969                             break;
100970                         case 156 /* Parameter */:
100971                             // Check modifiers of parameter declaration
100972                             if (nodes === parent.modifiers) {
100973                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
100974                                 return "skip";
100975                             }
100976                             break;
100977                         case 196 /* CallExpression */:
100978                         case 197 /* NewExpression */:
100979                         case 216 /* ExpressionWithTypeArguments */:
100980                         case 267 /* JsxSelfClosingElement */:
100981                         case 268 /* JsxOpeningElement */:
100982                         case 198 /* TaggedTemplateExpression */:
100983                             // Check type arguments
100984                             if (nodes === parent.typeArguments) {
100985                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
100986                                 return "skip";
100987                             }
100988                             break;
100989                     }
100990                 }
100991                 function checkModifiers(modifiers, isConstValid) {
100992                     for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
100993                         var modifier = modifiers_1[_i];
100994                         switch (modifier.kind) {
100995                             case 81 /* ConstKeyword */:
100996                                 if (isConstValid) {
100997                                     continue;
100998                                 }
100999                             // to report error,
101000                             // falls through
101001                             case 119 /* PublicKeyword */:
101002                             case 117 /* PrivateKeyword */:
101003                             case 118 /* ProtectedKeyword */:
101004                             case 138 /* ReadonlyKeyword */:
101005                             case 130 /* DeclareKeyword */:
101006                             case 122 /* AbstractKeyword */:
101007                                 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
101008                                 break;
101009                             // These are all legal modifiers.
101010                             case 120 /* StaticKeyword */:
101011                             case 89 /* ExportKeyword */:
101012                             case 84 /* DefaultKeyword */:
101013                         }
101014                     }
101015                 }
101016                 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
101017                     var start = nodes.pos;
101018                     return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
101019                 }
101020                 // Since these are syntactic diagnostics, parent might not have been set
101021                 // this means the sourceFile cannot be infered from the node
101022                 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
101023                     return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
101024                 }
101025             });
101026         }
101027         function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
101028             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
101029         }
101030         function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
101031             return runWithCancellationToken(function () {
101032                 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
101033                 // Don't actually write any files since we're just getting diagnostics.
101034                 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
101035             });
101036         }
101037         function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
101038             var cachedResult = sourceFile
101039                 ? cache.perFile && cache.perFile.get(sourceFile.path)
101040                 : cache.allDiagnostics;
101041             if (cachedResult) {
101042                 return cachedResult;
101043             }
101044             var result = getDiagnostics(sourceFile, cancellationToken);
101045             if (sourceFile) {
101046                 if (!cache.perFile) {
101047                     cache.perFile = ts.createMap();
101048                 }
101049                 cache.perFile.set(sourceFile.path, result);
101050             }
101051             else {
101052                 cache.allDiagnostics = result;
101053             }
101054             return result;
101055         }
101056         function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
101057             return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
101058         }
101059         function getOptionsDiagnostics() {
101060             return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
101061         }
101062         function getOptionsDiagnosticsOfConfigFile() {
101063             if (!options.configFile) {
101064                 return ts.emptyArray;
101065             }
101066             var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
101067             forEachResolvedProjectReference(function (resolvedRef) {
101068                 if (resolvedRef) {
101069                     diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
101070                 }
101071             });
101072             return diagnostics;
101073         }
101074         function getGlobalDiagnostics() {
101075             return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
101076         }
101077         function getConfigFileParsingDiagnostics() {
101078             return configFileParsingDiagnostics || ts.emptyArray;
101079         }
101080         function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
101081             processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
101082         }
101083         function fileReferenceIsEqualTo(a, b) {
101084             return a.fileName === b.fileName;
101085         }
101086         function moduleNameIsEqualTo(a, b) {
101087             return a.kind === 75 /* Identifier */
101088                 ? b.kind === 75 /* Identifier */ && a.escapedText === b.escapedText
101089                 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
101090         }
101091         function collectExternalModuleReferences(file) {
101092             if (file.imports) {
101093                 return;
101094             }
101095             var isJavaScriptFile = ts.isSourceFileJS(file);
101096             var isExternalModuleFile = ts.isExternalModule(file);
101097             // file.imports may not be undefined if there exists dynamic import
101098             var imports;
101099             var moduleAugmentations;
101100             var ambientModules;
101101             // If we are importing helpers, we need to add a synthetic reference to resolve the
101102             // helpers library.
101103             if (options.importHelpers
101104                 && (options.isolatedModules || isExternalModuleFile)
101105                 && !file.isDeclarationFile) {
101106                 // synthesize 'import "tslib"' declaration
101107                 var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText);
101108                 var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
101109                 ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
101110                 externalHelpersModuleReference.parent = importDecl;
101111                 importDecl.parent = file;
101112                 imports = [externalHelpersModuleReference];
101113             }
101114             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
101115                 var node = _a[_i];
101116                 collectModuleReferences(node, /*inAmbientModule*/ false);
101117             }
101118             if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
101119                 collectDynamicImportOrRequireCalls(file);
101120             }
101121             file.imports = imports || ts.emptyArray;
101122             file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
101123             file.ambientModuleNames = ambientModules || ts.emptyArray;
101124             return;
101125             function collectModuleReferences(node, inAmbientModule) {
101126                 if (ts.isAnyImportOrReExport(node)) {
101127                     var moduleNameExpr = ts.getExternalModuleName(node);
101128                     // TypeScript 1.0 spec (April 2014): 12.1.6
101129                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
101130                     // only through top - level external module names. Relative external module names are not permitted.
101131                     if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
101132                         imports = ts.append(imports, moduleNameExpr);
101133                     }
101134                 }
101135                 else if (ts.isModuleDeclaration(node)) {
101136                     if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
101137                         var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
101138                         // Ambient module declarations can be interpreted as augmentations for some existing external modules.
101139                         // This will happen in two cases:
101140                         // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
101141                         // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
101142                         //   immediately nested in top level ambient module declaration .
101143                         if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
101144                             (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
101145                         }
101146                         else if (!inAmbientModule) {
101147                             if (file.isDeclarationFile) {
101148                                 // for global .d.ts files record name of ambient module
101149                                 (ambientModules || (ambientModules = [])).push(nameText);
101150                             }
101151                             // An AmbientExternalModuleDeclaration declares an external module.
101152                             // This type of declaration is permitted only in the global module.
101153                             // The StringLiteral must specify a top - level external module name.
101154                             // Relative external module names are not permitted
101155                             // NOTE: body of ambient module is always a module block, if it exists
101156                             var body = node.body;
101157                             if (body) {
101158                                 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
101159                                     var statement = _a[_i];
101160                                     collectModuleReferences(statement, /*inAmbientModule*/ true);
101161                                 }
101162                             }
101163                         }
101164                     }
101165                 }
101166             }
101167             function collectDynamicImportOrRequireCalls(file) {
101168                 var r = /import|require/g;
101169                 while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
101170                     var node = getNodeAtPosition(file, r.lastIndex);
101171                     if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
101172                         imports = ts.append(imports, node.arguments[0]);
101173                     }
101174                     // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
101175                     else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
101176                         imports = ts.append(imports, node.arguments[0]);
101177                     }
101178                     else if (ts.isLiteralImportTypeNode(node)) {
101179                         imports = ts.append(imports, node.argument.literal);
101180                     }
101181                 }
101182             }
101183             /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
101184             function getNodeAtPosition(sourceFile, position) {
101185                 var current = sourceFile;
101186                 var getContainingChild = function (child) {
101187                     if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
101188                         return child;
101189                     }
101190                 };
101191                 while (true) {
101192                     var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
101193                     if (!child) {
101194                         return current;
101195                     }
101196                     current = child;
101197                 }
101198             }
101199         }
101200         function getLibFileFromReference(ref) {
101201             var libName = ts.toFileNameLowerCase(ref.fileName);
101202             var libFileName = ts.libMap.get(libName);
101203             if (libFileName) {
101204                 return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
101205             }
101206         }
101207         /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
101208         function getSourceFileFromReference(referencingFile, ref) {
101209             return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
101210         }
101211         function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
101212             if (ts.hasExtension(fileName)) {
101213                 var canonicalFileName_1 = host.getCanonicalFileName(fileName);
101214                 if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
101215                     if (fail) {
101216                         if (ts.hasJSFileExtension(canonicalFileName_1)) {
101217                             fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
101218                         }
101219                         else {
101220                             fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101221                         }
101222                     }
101223                     return undefined;
101224                 }
101225                 var sourceFile = getSourceFile(fileName);
101226                 if (fail) {
101227                     if (!sourceFile) {
101228                         var redirect = getProjectReferenceRedirect(fileName);
101229                         if (redirect) {
101230                             fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
101231                         }
101232                         else {
101233                             fail(ts.Diagnostics.File_0_not_found, fileName);
101234                         }
101235                     }
101236                     else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) {
101237                         fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
101238                     }
101239                 }
101240                 return sourceFile;
101241             }
101242             else {
101243                 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
101244                 if (sourceFileNoExtension)
101245                     return sourceFileNoExtension;
101246                 if (fail && options.allowNonTsExtensions) {
101247                     fail(ts.Diagnostics.File_0_not_found, fileName);
101248                     return undefined;
101249                 }
101250                 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
101251                 if (fail && !sourceFileWithAddedExtension)
101252                     fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101253                 return sourceFileWithAddedExtension;
101254             }
101255         }
101256         /** This has side effects through `findSourceFile`. */
101257         function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile) {
101258             getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, packageId); }, // TODO: GH#18217
101259             function (diagnostic) {
101260                 var args = [];
101261                 for (var _i = 1; _i < arguments.length; _i++) {
101262                     args[_i - 1] = arguments[_i];
101263                 }
101264                 return fileProcessingDiagnostics.add(createRefFileDiagnostic.apply(void 0, __spreadArrays([refFile, diagnostic], args)));
101265             }, refFile && refFile.file);
101266         }
101267         function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile) {
101268             var refs = !refFile ? refFileMap && refFileMap.get(existingFile.path) : undefined;
101269             var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile.fileName; });
101270             fileProcessingDiagnostics.add(refToReportErrorOn ?
101271                 createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, existingFile.fileName, fileName) :
101272                 createRefFileDiagnostic(refFile, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFile.fileName));
101273         }
101274         function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
101275             var redirect = Object.create(redirectTarget);
101276             redirect.fileName = fileName;
101277             redirect.path = path;
101278             redirect.resolvedPath = resolvedPath;
101279             redirect.originalFileName = originalFileName;
101280             redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
101281             sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101282             Object.defineProperties(redirect, {
101283                 id: {
101284                     get: function () { return this.redirectInfo.redirectTarget.id; },
101285                     set: function (value) { this.redirectInfo.redirectTarget.id = value; },
101286                 },
101287                 symbol: {
101288                     get: function () { return this.redirectInfo.redirectTarget.symbol; },
101289                     set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
101290                 },
101291             });
101292             return redirect;
101293         }
101294         // Get source file from normalized fileName
101295         function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
101296             if (useSourceOfProjectReferenceRedirect) {
101297                 var source = getSourceOfProjectReferenceRedirect(fileName);
101298                 // If preserveSymlinks is true, module resolution wont jump the symlink
101299                 // but the resolved real path may be the .d.ts from project reference
101300                 // Note:: Currently we try the real path only if the
101301                 // file is from node_modules to avoid having to run real path on all file paths
101302                 if (!source &&
101303                     host.realpath &&
101304                     options.preserveSymlinks &&
101305                     ts.isDeclarationFileName(fileName) &&
101306                     ts.stringContains(fileName, ts.nodeModulesPathPart)) {
101307                     var realPath = host.realpath(fileName);
101308                     if (realPath !== fileName)
101309                         source = getSourceOfProjectReferenceRedirect(realPath);
101310                 }
101311                 if (source) {
101312                     var file_1 = ts.isString(source) ?
101313                         findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
101314                         undefined;
101315                     if (file_1)
101316                         addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
101317                     return file_1;
101318                 }
101319             }
101320             var originalFileName = fileName;
101321             if (filesByName.has(path)) {
101322                 var file_2 = filesByName.get(path);
101323                 addFileToRefFileMap(fileName, file_2 || undefined, refFile);
101324                 // try to check if we've already seen this file but with a different casing in path
101325                 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
101326                 if (file_2 && options.forceConsistentCasingInFileNames) {
101327                     var checkedName = file_2.fileName;
101328                     var isRedirect = toPath(checkedName) !== toPath(fileName);
101329                     if (isRedirect) {
101330                         fileName = getProjectReferenceRedirect(fileName) || fileName;
101331                     }
101332                     // Check if it differs only in drive letters its ok to ignore that error:
101333                     var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
101334                     var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
101335                     if (checkedAbsolutePath !== inputAbsolutePath) {
101336                         reportFileNamesDifferOnlyInCasingError(fileName, file_2, refFile);
101337                     }
101338                 }
101339                 // If the file was previously found via a node_modules search, but is now being processed as a root file,
101340                 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
101341                 if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
101342                     sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
101343                     if (!options.noResolve) {
101344                         processReferencedFiles(file_2, isDefaultLib);
101345                         processTypeReferenceDirectives(file_2);
101346                     }
101347                     if (!options.noLib) {
101348                         processLibReferenceDirectives(file_2);
101349                     }
101350                     modulesWithElidedImports.set(file_2.path, false);
101351                     processImportedModules(file_2);
101352                 }
101353                 // See if we need to reprocess the imports due to prior skipped imports
101354                 else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
101355                     if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
101356                         modulesWithElidedImports.set(file_2.path, false);
101357                         processImportedModules(file_2);
101358                     }
101359                 }
101360                 return file_2 || undefined;
101361             }
101362             var redirectedPath;
101363             if (refFile && !useSourceOfProjectReferenceRedirect) {
101364                 var redirectProject = getProjectReferenceRedirectProject(fileName);
101365                 if (redirectProject) {
101366                     if (redirectProject.commandLine.options.outFile || redirectProject.commandLine.options.out) {
101367                         // Shouldnt create many to 1 mapping file in --out scenario
101368                         return undefined;
101369                     }
101370                     var redirect = getProjectReferenceOutputName(redirectProject, fileName);
101371                     fileName = redirect;
101372                     // Once we start redirecting to a file, we can potentially come back to it
101373                     // via a back-reference from another file in the .d.ts folder. If that happens we'll
101374                     // end up trying to add it to the program *again* because we were tracking it via its
101375                     // original (un-redirected) name. So we have to map both the original path and the redirected path
101376                     // to the source file we're about to find/create
101377                     redirectedPath = toPath(redirect);
101378                 }
101379             }
101380             // We haven't looked for this file, do so now and cache result
101381             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);
101382             if (packageId) {
101383                 var packageIdKey = ts.packageIdToString(packageId);
101384                 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
101385                 if (fileFromPackageId) {
101386                     // Some other SourceFile already exists with this package name and version.
101387                     // Instead of creating a duplicate, just redirect to the existing one.
101388                     var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
101389                     redirectTargetsMap.add(fileFromPackageId.path, fileName);
101390                     addFileToFilesByName(dupFile, path, redirectedPath);
101391                     sourceFileToPackageName.set(path, packageId.name);
101392                     processingOtherFiles.push(dupFile);
101393                     return dupFile;
101394                 }
101395                 else if (file) {
101396                     // This is the first source file to have this packageId.
101397                     packageIdToSourceFile.set(packageIdKey, file);
101398                     sourceFileToPackageName.set(path, packageId.name);
101399                 }
101400             }
101401             addFileToFilesByName(file, path, redirectedPath);
101402             if (file) {
101403                 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101404                 file.fileName = fileName; // Ensure that source file has same name as what we were looking for
101405                 file.path = path;
101406                 file.resolvedPath = toPath(fileName);
101407                 file.originalFileName = originalFileName;
101408                 addFileToRefFileMap(fileName, file, refFile);
101409                 if (host.useCaseSensitiveFileNames()) {
101410                     var pathLowerCase = ts.toFileNameLowerCase(path);
101411                     // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
101412                     var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
101413                     if (existingFile) {
101414                         reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile);
101415                     }
101416                     else {
101417                         filesByNameIgnoreCase.set(pathLowerCase, file);
101418                     }
101419                 }
101420                 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
101421                 if (!options.noResolve) {
101422                     processReferencedFiles(file, isDefaultLib);
101423                     processTypeReferenceDirectives(file);
101424                 }
101425                 if (!options.noLib) {
101426                     processLibReferenceDirectives(file);
101427                 }
101428                 // always process imported modules to record module name resolutions
101429                 processImportedModules(file);
101430                 if (isDefaultLib) {
101431                     processingDefaultLibFiles.push(file);
101432                 }
101433                 else {
101434                     processingOtherFiles.push(file);
101435                 }
101436             }
101437             return file;
101438         }
101439         function addFileToRefFileMap(referencedFileName, file, refFile) {
101440             if (refFile && file) {
101441                 (refFileMap || (refFileMap = ts.createMultiMap())).add(file.path, {
101442                     referencedFileName: referencedFileName,
101443                     kind: refFile.kind,
101444                     index: refFile.index,
101445                     file: refFile.file.path
101446                 });
101447             }
101448         }
101449         function addFileToFilesByName(file, path, redirectedPath) {
101450             if (redirectedPath) {
101451                 filesByName.set(redirectedPath, file);
101452                 filesByName.set(path, file || false);
101453             }
101454             else {
101455                 filesByName.set(path, file);
101456             }
101457         }
101458         function getProjectReferenceRedirect(fileName) {
101459             var referencedProject = getProjectReferenceRedirectProject(fileName);
101460             return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
101461         }
101462         function getProjectReferenceRedirectProject(fileName) {
101463             // Ignore dts or any json files
101464             if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101465                 return undefined;
101466             }
101467             // If this file is produced by a referenced project, we need to rewrite it to
101468             // look in the output folder of the referenced project rather than the input
101469             return getResolvedProjectReferenceToRedirect(fileName);
101470         }
101471         function getProjectReferenceOutputName(referencedProject, fileName) {
101472             var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
101473             return out ?
101474                 ts.changeExtension(out, ".d.ts" /* Dts */) :
101475                 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
101476         }
101477         /**
101478          * Get the referenced project if the file is input file from that reference project
101479          */
101480         function getResolvedProjectReferenceToRedirect(fileName) {
101481             if (mapFromFileToProjectReferenceRedirects === undefined) {
101482                 mapFromFileToProjectReferenceRedirects = ts.createMap();
101483                 forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
101484                     // not input file from the referenced project, ignore
101485                     if (referencedProject &&
101486                         toPath(options.configFilePath) !== referenceProjectPath) {
101487                         referencedProject.commandLine.fileNames.forEach(function (f) {
101488                             return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
101489                         });
101490                     }
101491                 });
101492             }
101493             var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
101494             return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
101495         }
101496         function forEachResolvedProjectReference(cb) {
101497             return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
101498                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
101499                 var resolvedRefPath = toPath(resolveProjectReferencePath(ref));
101500                 return cb(resolvedRef, resolvedRefPath);
101501             });
101502         }
101503         function getSourceOfProjectReferenceRedirect(file) {
101504             if (!ts.isDeclarationFileName(file))
101505                 return undefined;
101506             if (mapFromToProjectReferenceRedirectSource === undefined) {
101507                 mapFromToProjectReferenceRedirectSource = ts.createMap();
101508                 forEachResolvedProjectReference(function (resolvedRef) {
101509                     if (resolvedRef) {
101510                         var out = resolvedRef.commandLine.options.outFile || resolvedRef.commandLine.options.out;
101511                         if (out) {
101512                             // Dont know which source file it means so return true?
101513                             var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
101514                             mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
101515                         }
101516                         else {
101517                             ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
101518                                 if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101519                                     var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
101520                                     mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
101521                                 }
101522                             });
101523                         }
101524                     }
101525                 });
101526             }
101527             return mapFromToProjectReferenceRedirectSource.get(toPath(file));
101528         }
101529         function isSourceOfProjectReferenceRedirect(fileName) {
101530             return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
101531         }
101532         function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
101533             var seenResolvedRefs;
101534             return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef);
101535             function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) {
101536                 // Visit project references first
101537                 if (cbRef) {
101538                     var result = cbRef(projectReferences, parent);
101539                     if (result) {
101540                         return result;
101541                     }
101542                 }
101543                 return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
101544                     if (ts.contains(seenResolvedRefs, resolvedRef)) {
101545                         // ignore recursives
101546                         return undefined;
101547                     }
101548                     var result = cbResolvedRef(resolvedRef, index, parent);
101549                     if (result) {
101550                         return result;
101551                     }
101552                     if (!resolvedRef)
101553                         return undefined;
101554                     (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef);
101555                     return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef);
101556                 });
101557             }
101558         }
101559         function getResolvedProjectReferenceByPath(projectReferencePath) {
101560             if (!projectReferenceRedirects) {
101561                 return undefined;
101562             }
101563             return projectReferenceRedirects.get(projectReferencePath) || undefined;
101564         }
101565         function processReferencedFiles(file, isDefaultLib) {
101566             ts.forEach(file.referencedFiles, function (ref, index) {
101567                 var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName);
101568                 processSourceFile(referencedFileName, isDefaultLib, 
101569                 /*ignoreNoDefaultLib*/ false, 
101570                 /*packageId*/ undefined, {
101571                     kind: ts.RefFileKind.ReferenceFile,
101572                     index: index,
101573                     file: file,
101574                     pos: ref.pos,
101575                     end: ref.end
101576                 });
101577             });
101578         }
101579         function processTypeReferenceDirectives(file) {
101580             // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
101581             var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
101582             if (!typeDirectives) {
101583                 return;
101584             }
101585             var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName));
101586             for (var i = 0; i < typeDirectives.length; i++) {
101587                 var ref = file.typeReferenceDirectives[i];
101588                 var resolvedTypeReferenceDirective = resolutions[i];
101589                 // store resolved type directive on the file
101590                 var fileName = ts.toFileNameLowerCase(ref.fileName);
101591                 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
101592                 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, {
101593                     kind: ts.RefFileKind.TypeReferenceDirective,
101594                     index: i,
101595                     file: file,
101596                     pos: ref.pos,
101597                     end: ref.end
101598                 });
101599             }
101600         }
101601         function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
101602             // If we already found this library as a primary reference - nothing to do
101603             var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
101604             if (previousResolution && previousResolution.primary) {
101605                 return;
101606             }
101607             var saveResolution = true;
101608             if (resolvedTypeReferenceDirective) {
101609                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101610                     currentNodeModulesDepth++;
101611                 if (resolvedTypeReferenceDirective.primary) {
101612                     // resolved from the primary path
101613                     processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile); // TODO: GH#18217
101614                 }
101615                 else {
101616                     // If we already resolved to this file, it must have been a secondary reference. Check file contents
101617                     // for sameness and possibly issue an error
101618                     if (previousResolution) {
101619                         // Don't bother reading the file again if it's the same file.
101620                         if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
101621                             var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
101622                             var existingFile_1 = getSourceFile(previousResolution.resolvedFileName);
101623                             if (otherFileText !== existingFile_1.text) {
101624                                 // Try looking up ref for original file
101625                                 var refs = !refFile ? refFileMap && refFileMap.get(existingFile_1.path) : undefined;
101626                                 var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile_1.fileName; });
101627                                 fileProcessingDiagnostics.add(refToReportErrorOn ?
101628                                     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) :
101629                                     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));
101630                             }
101631                         }
101632                         // don't overwrite previous resolution result
101633                         saveResolution = false;
101634                     }
101635                     else {
101636                         // First resolution of this library
101637                         processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile);
101638                     }
101639                 }
101640                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101641                     currentNodeModulesDepth--;
101642             }
101643             else {
101644                 fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
101645             }
101646             if (saveResolution) {
101647                 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
101648             }
101649         }
101650         function processLibReferenceDirectives(file) {
101651             ts.forEach(file.libReferenceDirectives, function (libReference) {
101652                 var libName = ts.toFileNameLowerCase(libReference.fileName);
101653                 var libFileName = ts.libMap.get(libName);
101654                 if (libFileName) {
101655                     // we ignore any 'no-default-lib' reference set on this file.
101656                     processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
101657                 }
101658                 else {
101659                     var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
101660                     var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
101661                     var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
101662                     fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, libReference.pos, libReference.end - libReference.pos, message, libName, suggestion));
101663                 }
101664             });
101665         }
101666         function createRefFileDiagnostic(refFile, message) {
101667             var args = [];
101668             for (var _i = 2; _i < arguments.length; _i++) {
101669                 args[_i - 2] = arguments[_i];
101670             }
101671             if (!refFile) {
101672                 return ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args));
101673             }
101674             else {
101675                 return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile.file, refFile.pos, refFile.end - refFile.pos, message], args));
101676             }
101677         }
101678         function getCanonicalFileName(fileName) {
101679             return host.getCanonicalFileName(fileName);
101680         }
101681         function processImportedModules(file) {
101682             collectExternalModuleReferences(file);
101683             if (file.imports.length || file.moduleAugmentations.length) {
101684                 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
101685                 var moduleNames = getModuleNames(file);
101686                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file);
101687                 ts.Debug.assert(resolutions.length === moduleNames.length);
101688                 for (var i = 0; i < moduleNames.length; i++) {
101689                     var resolution = resolutions[i];
101690                     ts.setResolvedModule(file, moduleNames[i], resolution);
101691                     if (!resolution) {
101692                         continue;
101693                     }
101694                     var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
101695                     var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
101696                     var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
101697                     var resolvedFileName = resolution.resolvedFileName;
101698                     if (isFromNodeModulesSearch) {
101699                         currentNodeModulesDepth++;
101700                     }
101701                     // add file to program only if:
101702                     // - resolution was successful
101703                     // - noResolve is falsy
101704                     // - module name comes from the list of imports
101705                     // - it's not a top level JavaScript module that exceeded the search max
101706                     var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
101707                     // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
101708                     // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
101709                     var shouldAddFile = resolvedFileName
101710                         && !getResolutionDiagnostic(options, resolution)
101711                         && !options.noResolve
101712                         && i < file.imports.length
101713                         && !elideImport
101714                         && !(isJsFile && !options.allowJs)
101715                         && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 4194304 /* JSDoc */));
101716                     if (elideImport) {
101717                         modulesWithElidedImports.set(file.path, true);
101718                     }
101719                     else if (shouldAddFile) {
101720                         var path = toPath(resolvedFileName);
101721                         var pos = ts.skipTrivia(file.text, file.imports[i].pos);
101722                         findSourceFile(resolvedFileName, path, 
101723                         /*isDefaultLib*/ false, 
101724                         /*ignoreNoDefaultLib*/ false, {
101725                             kind: ts.RefFileKind.Import,
101726                             index: i,
101727                             file: file,
101728                             pos: pos,
101729                             end: file.imports[i].end
101730                         }, resolution.packageId);
101731                     }
101732                     if (isFromNodeModulesSearch) {
101733                         currentNodeModulesDepth--;
101734                     }
101735                 }
101736             }
101737             else {
101738                 // no imports - drop cached module resolutions
101739                 file.resolvedModules = undefined;
101740             }
101741         }
101742         function computeCommonSourceDirectory(sourceFiles) {
101743             var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
101744             return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
101745         }
101746         function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
101747             var allFilesBelongToPath = true;
101748             var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
101749             var rootPaths;
101750             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
101751                 var sourceFile = sourceFiles_2[_i];
101752                 if (!sourceFile.isDeclarationFile) {
101753                     var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
101754                     if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
101755                         if (!rootPaths)
101756                             rootPaths = ts.arrayToSet(rootNames, toPath);
101757                         addProgramDiagnosticAtRefPath(sourceFile, rootPaths, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory);
101758                         allFilesBelongToPath = false;
101759                     }
101760                 }
101761             }
101762             return allFilesBelongToPath;
101763         }
101764         function parseProjectReferenceConfigFile(ref) {
101765             if (!projectReferenceRedirects) {
101766                 projectReferenceRedirects = ts.createMap();
101767             }
101768             // The actual filename (i.e. add "/tsconfig.json" if necessary)
101769             var refPath = resolveProjectReferencePath(ref);
101770             var sourceFilePath = toPath(refPath);
101771             var fromCache = projectReferenceRedirects.get(sourceFilePath);
101772             if (fromCache !== undefined) {
101773                 return fromCache || undefined;
101774             }
101775             var commandLine;
101776             var sourceFile;
101777             if (host.getParsedCommandLine) {
101778                 commandLine = host.getParsedCommandLine(refPath);
101779                 if (!commandLine) {
101780                     addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
101781                     projectReferenceRedirects.set(sourceFilePath, false);
101782                     return undefined;
101783                 }
101784                 sourceFile = ts.Debug.checkDefined(commandLine.options.configFile);
101785                 ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
101786                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101787             }
101788             else {
101789                 // An absolute path pointing to the containing directory of the config file
101790                 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
101791                 sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
101792                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101793                 if (sourceFile === undefined) {
101794                     projectReferenceRedirects.set(sourceFilePath, false);
101795                     return undefined;
101796                 }
101797                 commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
101798             }
101799             sourceFile.fileName = refPath;
101800             sourceFile.path = sourceFilePath;
101801             sourceFile.resolvedPath = sourceFilePath;
101802             sourceFile.originalFileName = refPath;
101803             var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
101804             projectReferenceRedirects.set(sourceFilePath, resolvedRef);
101805             if (commandLine.projectReferences) {
101806                 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
101807             }
101808             return resolvedRef;
101809         }
101810         function verifyCompilerOptions() {
101811             if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
101812                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
101813             }
101814             if (options.isolatedModules) {
101815                 if (options.out) {
101816                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
101817                 }
101818                 if (options.outFile) {
101819                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
101820                 }
101821             }
101822             if (options.inlineSourceMap) {
101823                 if (options.sourceMap) {
101824                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
101825                 }
101826                 if (options.mapRoot) {
101827                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
101828                 }
101829             }
101830             if (options.paths && options.baseUrl === undefined) {
101831                 createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
101832             }
101833             if (options.composite) {
101834                 if (options.declaration === false) {
101835                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
101836                 }
101837                 if (options.incremental === false) {
101838                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
101839                 }
101840             }
101841             if (options.tsBuildInfoFile) {
101842                 if (!ts.isIncrementalCompilation(options)) {
101843                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
101844                 }
101845             }
101846             else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) {
101847                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
101848             }
101849             if (!options.listFilesOnly && options.noEmit && ts.isIncrementalCompilation(options)) {
101850                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite");
101851             }
101852             verifyProjectReferences();
101853             // List of collected files is complete; validate exhautiveness if this is a project with a file list
101854             if (options.composite) {
101855                 var rootPaths = ts.arrayToSet(rootNames, toPath);
101856                 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
101857                     var file = files_3[_i];
101858                     // Ignore file that is not emitted
101859                     if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
101860                         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 || "");
101861                     }
101862                 }
101863             }
101864             if (options.paths) {
101865                 for (var key in options.paths) {
101866                     if (!ts.hasProperty(options.paths, key)) {
101867                         continue;
101868                     }
101869                     if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
101870                         createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
101871                     }
101872                     if (ts.isArray(options.paths[key])) {
101873                         var len = options.paths[key].length;
101874                         if (len === 0) {
101875                             createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
101876                         }
101877                         for (var i = 0; i < len; i++) {
101878                             var subst = options.paths[key][i];
101879                             var typeOfSubst = typeof subst;
101880                             if (typeOfSubst === "string") {
101881                                 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
101882                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
101883                                 }
101884                             }
101885                             else {
101886                                 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
101887                             }
101888                         }
101889                     }
101890                     else {
101891                         createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
101892                     }
101893                 }
101894             }
101895             if (!options.sourceMap && !options.inlineSourceMap) {
101896                 if (options.inlineSources) {
101897                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
101898                 }
101899                 if (options.sourceRoot) {
101900                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
101901                 }
101902             }
101903             if (options.out && options.outFile) {
101904                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
101905             }
101906             if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
101907                 // Error to specify --mapRoot without --sourcemap
101908                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
101909             }
101910             if (options.declarationDir) {
101911                 if (!ts.getEmitDeclarations(options)) {
101912                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
101913                 }
101914                 if (options.out || options.outFile) {
101915                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
101916                 }
101917             }
101918             if (options.declarationMap && !ts.getEmitDeclarations(options)) {
101919                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
101920             }
101921             if (options.lib && options.noLib) {
101922                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
101923             }
101924             if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
101925                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
101926             }
101927             var languageVersion = options.target || 0 /* ES3 */;
101928             var outFile = options.outFile || options.out;
101929             var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
101930             if (options.isolatedModules) {
101931                 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
101932                     createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
101933                 }
101934                 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
101935                 if (firstNonExternalModuleSourceFile) {
101936                     var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
101937                     programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.All_files_must_be_modules_when_the_isolatedModules_flag_is_provided));
101938                 }
101939             }
101940             else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
101941                 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
101942                 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
101943                 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
101944             }
101945             // Cannot specify module gen that isn't amd or system with --out
101946             if (outFile && !options.emitDeclarationOnly) {
101947                 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
101948                     createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
101949                 }
101950                 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
101951                     var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
101952                     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"));
101953                 }
101954             }
101955             if (options.resolveJsonModule) {
101956                 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
101957                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
101958                 }
101959                 // Any emit other than common js, amd, es2015 or esnext is error
101960                 else if (!ts.hasJsonModuleEmitEnabled(options)) {
101961                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
101962                 }
101963             }
101964             // there has to be common source directory if user specified --outdir || --sourceRoot
101965             // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
101966             if (options.outDir || // there is --outDir specified
101967                 options.sourceRoot || // there is --sourceRoot specified
101968                 options.mapRoot) { // there is --mapRoot specified
101969                 // Precalculate and cache the common source directory
101970                 var dir = getCommonSourceDirectory();
101971                 // 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
101972                 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
101973                     createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
101974                 }
101975             }
101976             if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
101977                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
101978             }
101979             if (options.checkJs && !options.allowJs) {
101980                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
101981             }
101982             if (options.emitDeclarationOnly) {
101983                 if (!ts.getEmitDeclarations(options)) {
101984                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
101985                 }
101986                 if (options.noEmit) {
101987                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
101988                 }
101989             }
101990             if (options.emitDecoratorMetadata &&
101991                 !options.experimentalDecorators) {
101992                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
101993             }
101994             if (options.jsxFactory) {
101995                 if (options.reactNamespace) {
101996                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
101997                 }
101998                 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
101999                     createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
102000                 }
102001             }
102002             else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
102003                 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
102004             }
102005             // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
102006             if (!options.noEmit && !options.suppressOutputPathCheck) {
102007                 var emitHost = getEmitHost();
102008                 var emitFilesSeen_1 = ts.createMap();
102009                 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
102010                     if (!options.emitDeclarationOnly) {
102011                         verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
102012                     }
102013                     verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
102014                 });
102015             }
102016             // Verify that all the emit files are unique and don't overwrite input files
102017             function verifyEmitFilePath(emitFileName, emitFilesSeen) {
102018                 if (emitFileName) {
102019                     var emitFilePath = toPath(emitFileName);
102020                     // Report error if the output overwrites input file
102021                     if (filesByName.has(emitFilePath)) {
102022                         var chain = void 0;
102023                         if (!options.configFilePath) {
102024                             // The program is from either an inferred project or an external project
102025                             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);
102026                         }
102027                         chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
102028                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
102029                     }
102030                     var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
102031                     // Report error if multiple files write into same file
102032                     if (emitFilesSeen.has(emitFileKey)) {
102033                         // Already seen the same emit file - report error
102034                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
102035                     }
102036                     else {
102037                         emitFilesSeen.set(emitFileKey, true);
102038                     }
102039                 }
102040             }
102041         }
102042         function createFileDiagnosticAtReference(refPathToReportErrorOn, message) {
102043             var _a, _b;
102044             var args = [];
102045             for (var _i = 2; _i < arguments.length; _i++) {
102046                 args[_i - 2] = arguments[_i];
102047             }
102048             var refFile = ts.Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
102049             var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index;
102050             var pos, end;
102051             switch (kind) {
102052                 case ts.RefFileKind.Import:
102053                     pos = ts.skipTrivia(refFile.text, refFile.imports[index].pos);
102054                     end = refFile.imports[index].end;
102055                     break;
102056                 case ts.RefFileKind.ReferenceFile:
102057                     (_a = refFile.referencedFiles[index], pos = _a.pos, end = _a.end);
102058                     break;
102059                 case ts.RefFileKind.TypeReferenceDirective:
102060                     (_b = refFile.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
102061                     break;
102062                 default:
102063                     return ts.Debug.assertNever(kind);
102064             }
102065             return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile, pos, end - pos, message], args));
102066         }
102067         function addProgramDiagnosticAtRefPath(file, rootPaths, message) {
102068             var args = [];
102069             for (var _i = 3; _i < arguments.length; _i++) {
102070                 args[_i - 3] = arguments[_i];
102071             }
102072             var refPaths = refFileMap && refFileMap.get(file.path);
102073             var refPathToReportErrorOn = ts.forEach(refPaths, function (refPath) { return rootPaths.has(refPath.file) ? refPath : undefined; }) ||
102074                 ts.elementAt(refPaths, 0);
102075             programDiagnostics.add(refPathToReportErrorOn ? createFileDiagnosticAtReference.apply(void 0, __spreadArrays([refPathToReportErrorOn, message], args)) : ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
102076         }
102077         function verifyProjectReferences() {
102078             var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
102079             forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
102080                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
102081                 var parentFile = parent && parent.sourceFile;
102082                 if (!resolvedRef) {
102083                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
102084                     return;
102085                 }
102086                 var options = resolvedRef.commandLine.options;
102087                 if (!options.composite) {
102088                     // ok to not have composite if the current program is container only
102089                     var inputs = parent ? parent.commandLine.fileNames : rootNames;
102090                     if (inputs.length) {
102091                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
102092                     }
102093                 }
102094                 if (ref.prepend) {
102095                     var out = options.outFile || options.out;
102096                     if (out) {
102097                         if (!host.fileExists(out)) {
102098                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
102099                         }
102100                     }
102101                     else {
102102                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
102103                     }
102104                 }
102105                 if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
102106                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
102107                     hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
102108                 }
102109             });
102110         }
102111         function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
102112             var needCompilerDiagnostic = true;
102113             var pathsSyntax = getOptionPathsSyntax();
102114             for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
102115                 var pathProp = pathsSyntax_1[_i];
102116                 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
102117                     for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
102118                         var keyProps = _b[_a];
102119                         var initializer = keyProps.initializer;
102120                         if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
102121                             programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
102122                             needCompilerDiagnostic = false;
102123                         }
102124                     }
102125                 }
102126             }
102127             if (needCompilerDiagnostic) {
102128                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102129             }
102130         }
102131         function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
102132             var needCompilerDiagnostic = true;
102133             var pathsSyntax = getOptionPathsSyntax();
102134             for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
102135                 var pathProp = pathsSyntax_2[_i];
102136                 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
102137                     createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
102138                     needCompilerDiagnostic = false;
102139                 }
102140             }
102141             if (needCompilerDiagnostic) {
102142                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
102143             }
102144         }
102145         function getOptionsSyntaxByName(name) {
102146             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102147             if (compilerOptionsObjectLiteralSyntax) {
102148                 return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
102149             }
102150             return undefined;
102151         }
102152         function getOptionPathsSyntax() {
102153             return getOptionsSyntaxByName("paths") || ts.emptyArray;
102154         }
102155         function createDiagnosticForOptionName(message, option1, option2, option3) {
102156             createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
102157         }
102158         function createOptionValueDiagnostic(option1, message, arg0) {
102159             createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
102160         }
102161         function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
102162             var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
102163             if (referencesSyntax && referencesSyntax.elements.length > index) {
102164                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
102165             }
102166             else {
102167                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
102168             }
102169         }
102170         function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
102171             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102172             var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
102173                 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
102174             if (needCompilerDiagnostic) {
102175                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102176             }
102177         }
102178         function getCompilerOptionsObjectLiteralSyntax() {
102179             if (_compilerOptionsObjectLiteralSyntax === undefined) {
102180                 _compilerOptionsObjectLiteralSyntax = null; // eslint-disable-line no-null/no-null
102181                 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
102182                 if (jsonObjectLiteral) {
102183                     for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
102184                         var prop = _a[_i];
102185                         if (ts.isObjectLiteralExpression(prop.initializer)) {
102186                             _compilerOptionsObjectLiteralSyntax = prop.initializer;
102187                             break;
102188                         }
102189                     }
102190                 }
102191             }
102192             return _compilerOptionsObjectLiteralSyntax;
102193         }
102194         function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
102195             var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
102196             for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
102197                 var prop = props_3[_i];
102198                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
102199             }
102200             return !!props.length;
102201         }
102202         function blockEmittingOfFile(emitFileName, diag) {
102203             hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
102204             programDiagnostics.add(diag);
102205         }
102206         function isEmittedFile(file) {
102207             if (options.noEmit) {
102208                 return false;
102209             }
102210             // If this is source file, its not emitted file
102211             var filePath = toPath(file);
102212             if (getSourceFileByPath(filePath)) {
102213                 return false;
102214             }
102215             // If options have --outFile or --out just check that
102216             var out = options.outFile || options.out;
102217             if (out) {
102218                 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
102219             }
102220             // If declarationDir is specified, return if its a file in that directory
102221             if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
102222                 return true;
102223             }
102224             // If --outDir, check if file is in that directory
102225             if (options.outDir) {
102226                 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
102227             }
102228             if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
102229                 // Otherwise just check if sourceFile with the name exists
102230                 var filePathWithoutExtension = ts.removeFileExtension(filePath);
102231                 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
102232                     !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
102233             }
102234             return false;
102235         }
102236         function isSameFile(file1, file2) {
102237             return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
102238         }
102239         function getProbableSymlinks() {
102240             if (host.getSymlinks) {
102241                 return host.getSymlinks();
102242             }
102243             return symlinks || (symlinks = ts.discoverProbableSymlinks(files, getCanonicalFileName, host.getCurrentDirectory()));
102244         }
102245     }
102246     ts.createProgram = createProgram;
102247     function updateHostForUseSourceOfProjectReferenceRedirect(host) {
102248         var mapOfDeclarationDirectories;
102249         var symlinkedDirectories;
102250         var symlinkedFiles;
102251         var originalFileExists = host.compilerHost.fileExists;
102252         var originalDirectoryExists = host.compilerHost.directoryExists;
102253         var originalGetDirectories = host.compilerHost.getDirectories;
102254         var originalRealpath = host.compilerHost.realpath;
102255         if (!host.useSourceOfProjectReferenceRedirect)
102256             return { onProgramCreateComplete: ts.noop, fileExists: fileExists };
102257         host.compilerHost.fileExists = fileExists;
102258         if (originalDirectoryExists) {
102259             // This implementation of directoryExists checks if the directory being requested is
102260             // directory of .d.ts file for the referenced Project.
102261             // If it is it returns true irrespective of whether that directory exists on host
102262             host.compilerHost.directoryExists = function (path) {
102263                 if (originalDirectoryExists.call(host.compilerHost, path)) {
102264                     handleDirectoryCouldBeSymlink(path);
102265                     return true;
102266                 }
102267                 if (!host.getResolvedProjectReferences())
102268                     return false;
102269                 if (!mapOfDeclarationDirectories) {
102270                     mapOfDeclarationDirectories = ts.createMap();
102271                     host.forEachResolvedProjectReference(function (ref) {
102272                         if (!ref)
102273                             return;
102274                         var out = ref.commandLine.options.outFile || ref.commandLine.options.out;
102275                         if (out) {
102276                             mapOfDeclarationDirectories.set(ts.getDirectoryPath(host.toPath(out)), true);
102277                         }
102278                         else {
102279                             // Set declaration's in different locations only, if they are next to source the directory present doesnt change
102280                             var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
102281                             if (declarationDir) {
102282                                 mapOfDeclarationDirectories.set(host.toPath(declarationDir), true);
102283                             }
102284                         }
102285                     });
102286                 }
102287                 return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false);
102288             };
102289         }
102290         if (originalGetDirectories) {
102291             // Call getDirectories only if directory actually present on the host
102292             // This is needed to ensure that we arent getting directories that we fake about presence for
102293             host.compilerHost.getDirectories = function (path) {
102294                 return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ?
102295                     originalGetDirectories.call(host.compilerHost, path) :
102296                     [];
102297             };
102298         }
102299         // This is something we keep for life time of the host
102300         if (originalRealpath) {
102301             host.compilerHost.realpath = function (s) {
102302                 return (symlinkedFiles === null || symlinkedFiles === void 0 ? void 0 : symlinkedFiles.get(host.toPath(s))) ||
102303                     originalRealpath.call(host.compilerHost, s);
102304             };
102305         }
102306         return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists };
102307         function onProgramCreateComplete() {
102308             host.compilerHost.fileExists = originalFileExists;
102309             host.compilerHost.directoryExists = originalDirectoryExists;
102310             host.compilerHost.getDirectories = originalGetDirectories;
102311             // DO not revert realpath as it could be used later
102312         }
102313         // This implementation of fileExists checks if the file being requested is
102314         // .d.ts file for the referenced Project.
102315         // If it is it returns true irrespective of whether that file exists on host
102316         function fileExists(file) {
102317             if (originalFileExists.call(host.compilerHost, file))
102318                 return true;
102319             if (!host.getResolvedProjectReferences())
102320                 return false;
102321             if (!ts.isDeclarationFileName(file))
102322                 return false;
102323             // Project references go to source file instead of .d.ts file
102324             return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true);
102325         }
102326         function fileExistsIfProjectReferenceDts(file) {
102327             var source = host.getSourceOfProjectReferenceRedirect(file);
102328             return source !== undefined ?
102329                 ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true :
102330                 undefined;
102331         }
102332         function directoryExistsIfProjectReferenceDeclDir(dir) {
102333             var dirPath = host.toPath(dir);
102334             var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator;
102335             return ts.forEachKey(mapOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath ||
102336                 // Any parent directory of declaration dir
102337                 ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) ||
102338                 // Any directory inside declaration dir
102339                 ts.startsWith(dirPath, declDirPath + "/"); });
102340         }
102341         function handleDirectoryCouldBeSymlink(directory) {
102342             if (!host.getResolvedProjectReferences())
102343                 return;
102344             // Because we already watch node_modules, handle symlinks in there
102345             if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
102346                 return;
102347             if (!symlinkedDirectories)
102348                 symlinkedDirectories = ts.createMap();
102349             var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory));
102350             if (symlinkedDirectories.has(directoryPath))
102351                 return;
102352             var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory));
102353             var realPath;
102354             if (real === directory ||
102355                 (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
102356                 // not symlinked
102357                 symlinkedDirectories.set(directoryPath, false);
102358                 return;
102359             }
102360             symlinkedDirectories.set(directoryPath, {
102361                 real: ts.ensureTrailingDirectorySeparator(real),
102362                 realPath: realPath
102363             });
102364         }
102365         function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
102366             var fileOrDirectoryExistsUsingSource = isFile ?
102367                 function (file) { return fileExistsIfProjectReferenceDts(file); } :
102368                 function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); };
102369             // Check current directory or file
102370             var result = fileOrDirectoryExistsUsingSource(fileOrDirectory);
102371             if (result !== undefined)
102372                 return result;
102373             if (!symlinkedDirectories)
102374                 return false;
102375             var fileOrDirectoryPath = host.toPath(fileOrDirectory);
102376             if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart))
102377                 return false;
102378             if (isFile && symlinkedFiles && symlinkedFiles.has(fileOrDirectoryPath))
102379                 return true;
102380             // If it contains node_modules check if its one of the symlinked path we know of
102381             return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) {
102382                 var directoryPath = _a[0], symlinkedDirectory = _a[1];
102383                 if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath))
102384                     return undefined;
102385                 var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
102386                 if (isFile && result) {
102387                     if (!symlinkedFiles)
102388                         symlinkedFiles = ts.createMap();
102389                     // Store the real path for the file'
102390                     var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
102391                     symlinkedFiles.set(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), ""));
102392                 }
102393                 return result;
102394             }) || false;
102395         }
102396     }
102397     /*@internal*/
102398     function handleNoEmitOptions(program, sourceFile, cancellationToken) {
102399         var options = program.getCompilerOptions();
102400         if (options.noEmit) {
102401             return { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
102402         }
102403         // If the noEmitOnError flag is set, then check if we have any errors so far.  If so,
102404         // immediately bail out.  Note that we pass 'undefined' for 'sourceFile' so that we
102405         // get any preEmit diagnostics, not just the ones
102406         if (!options.noEmitOnError)
102407             return undefined;
102408         var diagnostics = __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
102409         if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
102410             diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
102411         }
102412         return diagnostics.length > 0 ?
102413             { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true } :
102414             undefined;
102415     }
102416     ts.handleNoEmitOptions = handleNoEmitOptions;
102417     /* @internal */
102418     function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
102419         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
102420         return {
102421             fileExists: function (f) { return directoryStructureHost.fileExists(f); },
102422             readDirectory: function (root, extensions, excludes, includes, depth) {
102423                 ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
102424                 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
102425             },
102426             readFile: function (f) { return directoryStructureHost.readFile(f); },
102427             useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
102428             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
102429             onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
102430             trace: host.trace ? function (s) { return host.trace(s); } : undefined
102431         };
102432     }
102433     ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
102434     /* @internal */
102435     function createPrependNodes(projectReferences, getCommandLine, readFile) {
102436         if (!projectReferences)
102437             return ts.emptyArray;
102438         var nodes;
102439         for (var i = 0; i < projectReferences.length; i++) {
102440             var ref = projectReferences[i];
102441             var resolvedRefOpts = getCommandLine(ref, i);
102442             if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
102443                 var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
102444                 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
102445                 if (!out)
102446                     continue;
102447                 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
102448                 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
102449                 (nodes || (nodes = [])).push(node);
102450             }
102451         }
102452         return nodes || ts.emptyArray;
102453     }
102454     ts.createPrependNodes = createPrependNodes;
102455     function resolveProjectReferencePath(hostOrRef, ref) {
102456         var passedInRef = ref ? ref : hostOrRef;
102457         return ts.resolveConfigFileProjectName(passedInRef.path);
102458     }
102459     ts.resolveProjectReferencePath = resolveProjectReferencePath;
102460     /* @internal */
102461     /**
102462      * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
102463      * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
102464      * This returns a diagnostic even if the module will be an untyped module.
102465      */
102466     function getResolutionDiagnostic(options, _a) {
102467         var extension = _a.extension;
102468         switch (extension) {
102469             case ".ts" /* Ts */:
102470             case ".d.ts" /* Dts */:
102471                 // These are always allowed.
102472                 return undefined;
102473             case ".tsx" /* Tsx */:
102474                 return needJsx();
102475             case ".jsx" /* Jsx */:
102476                 return needJsx() || needAllowJs();
102477             case ".js" /* Js */:
102478                 return needAllowJs();
102479             case ".json" /* Json */:
102480                 return needResolveJsonModule();
102481         }
102482         function needJsx() {
102483             return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
102484         }
102485         function needAllowJs() {
102486             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;
102487         }
102488         function needResolveJsonModule() {
102489             return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
102490         }
102491     }
102492     ts.getResolutionDiagnostic = getResolutionDiagnostic;
102493     function getModuleNames(_a) {
102494         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
102495         var res = imports.map(function (i) { return i.text; });
102496         for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
102497             var aug = moduleAugmentations_1[_i];
102498             if (aug.kind === 10 /* StringLiteral */) {
102499                 res.push(aug.text);
102500             }
102501             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
102502         }
102503         return res;
102504     }
102505 })(ts || (ts = {}));
102506 /*@internal*/
102507 var ts;
102508 (function (ts) {
102509     function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
102510         var outputFiles = [];
102511         var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit;
102512         return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit };
102513         function writeFile(fileName, text, writeByteOrderMark) {
102514             outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
102515         }
102516     }
102517     ts.getFileEmitOutput = getFileEmitOutput;
102518     var BuilderState;
102519     (function (BuilderState) {
102520         /**
102521          * Get the referencedFile from the imported module symbol
102522          */
102523         function getReferencedFileFromImportedModuleSymbol(symbol) {
102524             if (symbol.declarations && symbol.declarations[0]) {
102525                 var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
102526                 return declarationSourceFile && declarationSourceFile.resolvedPath;
102527             }
102528         }
102529         /**
102530          * Get the referencedFile from the import name node from file
102531          */
102532         function getReferencedFileFromImportLiteral(checker, importName) {
102533             var symbol = checker.getSymbolAtLocation(importName);
102534             return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
102535         }
102536         /**
102537          * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
102538          */
102539         function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
102540             return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
102541         }
102542         /**
102543          * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
102544          */
102545         function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
102546             var referencedFiles;
102547             // We need to use a set here since the code can contain the same import twice,
102548             // but that will only be one dependency.
102549             // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
102550             if (sourceFile.imports && sourceFile.imports.length > 0) {
102551                 var checker = program.getTypeChecker();
102552                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
102553                     var importName = _a[_i];
102554                     var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
102555                     if (declarationSourceFilePath) {
102556                         addReferencedFile(declarationSourceFilePath);
102557                     }
102558                 }
102559             }
102560             var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
102561             // Handle triple slash references
102562             if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
102563                 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
102564                     var referencedFile = _c[_b];
102565                     var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
102566                     addReferencedFile(referencedPath);
102567                 }
102568             }
102569             // Handle type reference directives
102570             if (sourceFile.resolvedTypeReferenceDirectiveNames) {
102571                 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
102572                     if (!resolvedTypeReferenceDirective) {
102573                         return;
102574                     }
102575                     var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
102576                     var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
102577                     addReferencedFile(typeFilePath);
102578                 });
102579             }
102580             // Add module augmentation as references
102581             if (sourceFile.moduleAugmentations.length) {
102582                 var checker = program.getTypeChecker();
102583                 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
102584                     var moduleName = _e[_d];
102585                     if (!ts.isStringLiteral(moduleName)) {
102586                         continue;
102587                     }
102588                     var symbol = checker.getSymbolAtLocation(moduleName);
102589                     if (!symbol) {
102590                         continue;
102591                     }
102592                     // Add any file other than our own as reference
102593                     addReferenceFromAmbientModule(symbol);
102594                 }
102595             }
102596             // From ambient modules
102597             for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
102598                 var ambientModule = _g[_f];
102599                 if (ambientModule.declarations.length > 1) {
102600                     addReferenceFromAmbientModule(ambientModule);
102601                 }
102602             }
102603             return referencedFiles;
102604             function addReferenceFromAmbientModule(symbol) {
102605                 // Add any file other than our own as reference
102606                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
102607                     var declaration = _a[_i];
102608                     var declarationSourceFile = ts.getSourceFileOfNode(declaration);
102609                     if (declarationSourceFile &&
102610                         declarationSourceFile !== sourceFile) {
102611                         addReferencedFile(declarationSourceFile.resolvedPath);
102612                     }
102613                 }
102614             }
102615             function addReferencedFile(referencedPath) {
102616                 if (!referencedFiles) {
102617                     referencedFiles = ts.createMap();
102618                 }
102619                 referencedFiles.set(referencedPath, true);
102620             }
102621         }
102622         /**
102623          * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
102624          */
102625         function canReuseOldState(newReferencedMap, oldState) {
102626             return oldState && !oldState.referencedMap === !newReferencedMap;
102627         }
102628         BuilderState.canReuseOldState = canReuseOldState;
102629         /**
102630          * Creates the state of file references and signature for the new program from oldState if it is safe
102631          */
102632         function create(newProgram, getCanonicalFileName, oldState) {
102633             var fileInfos = ts.createMap();
102634             var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined;
102635             var exportedModulesMap = referencedMap ? ts.createMap() : undefined;
102636             var hasCalledUpdateShapeSignature = ts.createMap();
102637             var useOldState = canReuseOldState(referencedMap, oldState);
102638             // Create the reference map, and set the file infos
102639             for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
102640                 var sourceFile = _a[_i];
102641                 var version_1 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
102642                 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
102643                 if (referencedMap) {
102644                     var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
102645                     if (newReferences) {
102646                         referencedMap.set(sourceFile.resolvedPath, newReferences);
102647                     }
102648                     // Copy old visible to outside files map
102649                     if (useOldState) {
102650                         var exportedModules = oldState.exportedModulesMap.get(sourceFile.resolvedPath);
102651                         if (exportedModules) {
102652                             exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
102653                         }
102654                     }
102655                 }
102656                 fileInfos.set(sourceFile.resolvedPath, { version: version_1, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) });
102657             }
102658             return {
102659                 fileInfos: fileInfos,
102660                 referencedMap: referencedMap,
102661                 exportedModulesMap: exportedModulesMap,
102662                 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
102663             };
102664         }
102665         BuilderState.create = create;
102666         /**
102667          * Releases needed properties
102668          */
102669         function releaseCache(state) {
102670             state.allFilesExcludingDefaultLibraryFile = undefined;
102671             state.allFileNames = undefined;
102672         }
102673         BuilderState.releaseCache = releaseCache;
102674         /**
102675          * Creates a clone of the state
102676          */
102677         function clone(state) {
102678             var fileInfos = ts.createMap();
102679             state.fileInfos.forEach(function (value, key) {
102680                 fileInfos.set(key, __assign({}, value));
102681             });
102682             // Dont need to backup allFiles info since its cache anyway
102683             return {
102684                 fileInfos: fileInfos,
102685                 referencedMap: cloneMapOrUndefined(state.referencedMap),
102686                 exportedModulesMap: cloneMapOrUndefined(state.exportedModulesMap),
102687                 hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature),
102688             };
102689         }
102690         BuilderState.clone = clone;
102691         /**
102692          * Gets the files affected by the path from the program
102693          */
102694         function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
102695             // Since the operation could be cancelled, the signatures are always stored in the cache
102696             // They will be committed once it is safe to use them
102697             // eg when calling this api from tsserver, if there is no cancellation of the operation
102698             // In the other cases the affected files signatures are committed only after the iteration through the result is complete
102699             var signatureCache = cacheToUpdateSignature || ts.createMap();
102700             var sourceFile = programOfThisState.getSourceFileByPath(path);
102701             if (!sourceFile) {
102702                 return ts.emptyArray;
102703             }
102704             if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
102705                 return [sourceFile];
102706             }
102707             var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
102708             if (!cacheToUpdateSignature) {
102709                 // Commit all the signatures in the signature cache
102710                 updateSignaturesFromCache(state, signatureCache);
102711             }
102712             return result;
102713         }
102714         BuilderState.getFilesAffectedBy = getFilesAffectedBy;
102715         /**
102716          * Updates the signatures from the cache into state's fileinfo signatures
102717          * This should be called whenever it is safe to commit the state of the builder
102718          */
102719         function updateSignaturesFromCache(state, signatureCache) {
102720             signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); });
102721         }
102722         BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
102723         function updateSignatureOfFile(state, signature, path) {
102724             state.fileInfos.get(path).signature = signature;
102725             state.hasCalledUpdateShapeSignature.set(path, true);
102726         }
102727         BuilderState.updateSignatureOfFile = updateSignatureOfFile;
102728         /**
102729          * Returns if the shape of the signature has changed since last emit
102730          */
102731         function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
102732             ts.Debug.assert(!!sourceFile);
102733             ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
102734             // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
102735             if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
102736                 return false;
102737             }
102738             var info = state.fileInfos.get(sourceFile.resolvedPath);
102739             if (!info)
102740                 return ts.Debug.fail();
102741             var prevSignature = info.signature;
102742             var latestSignature;
102743             if (sourceFile.isDeclarationFile) {
102744                 latestSignature = sourceFile.version;
102745                 if (exportedModulesMapCache && latestSignature !== prevSignature) {
102746                     // All the references in this file are exported
102747                     var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined;
102748                     exportedModulesMapCache.set(sourceFile.resolvedPath, references || false);
102749                 }
102750             }
102751             else {
102752                 var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, 
102753                 /*emitOnlyDtsFiles*/ true, cancellationToken, 
102754                 /*customTransformers*/ undefined, 
102755                 /*forceDtsEmit*/ true);
102756                 var firstDts_1 = emitOutput_1.outputFiles &&
102757                     programOfThisState.getCompilerOptions().declarationMap ?
102758                     emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined :
102759                     emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined;
102760                 if (firstDts_1) {
102761                     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; })); });
102762                     latestSignature = computeHash(firstDts_1.text);
102763                     if (exportedModulesMapCache && latestSignature !== prevSignature) {
102764                         updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
102765                     }
102766                 }
102767                 else {
102768                     latestSignature = prevSignature; // TODO: GH#18217
102769                 }
102770             }
102771             cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
102772             return !prevSignature || latestSignature !== prevSignature;
102773         }
102774         BuilderState.updateShapeSignature = updateShapeSignature;
102775         /**
102776          * Coverts the declaration emit result into exported modules map
102777          */
102778         function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
102779             if (!exportedModulesFromDeclarationEmit) {
102780                 exportedModulesMapCache.set(sourceFile.resolvedPath, false);
102781                 return;
102782             }
102783             var exportedModules;
102784             exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
102785             exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules || false);
102786             function addExportedModule(exportedModulePath) {
102787                 if (exportedModulePath) {
102788                     if (!exportedModules) {
102789                         exportedModules = ts.createMap();
102790                     }
102791                     exportedModules.set(exportedModulePath, true);
102792                 }
102793             }
102794         }
102795         /**
102796          * Updates the exported modules from cache into state's exported modules map
102797          * This should be called whenever it is safe to commit the state of the builder
102798          */
102799         function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
102800             if (exportedModulesMapCache) {
102801                 ts.Debug.assert(!!state.exportedModulesMap);
102802                 exportedModulesMapCache.forEach(function (exportedModules, path) {
102803                     if (exportedModules) {
102804                         state.exportedModulesMap.set(path, exportedModules);
102805                     }
102806                     else {
102807                         state.exportedModulesMap.delete(path);
102808                     }
102809                 });
102810             }
102811         }
102812         BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
102813         /**
102814          * Get all the dependencies of the sourceFile
102815          */
102816         function getAllDependencies(state, programOfThisState, sourceFile) {
102817             var compilerOptions = programOfThisState.getCompilerOptions();
102818             // With --out or --outFile all outputs go into single file, all files depend on each other
102819             if (compilerOptions.outFile || compilerOptions.out) {
102820                 return getAllFileNames(state, programOfThisState);
102821             }
102822             // If this is non module emit, or its a global file, it depends on all the source files
102823             if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
102824                 return getAllFileNames(state, programOfThisState);
102825             }
102826             // Get the references, traversing deep from the referenceMap
102827             var seenMap = ts.createMap();
102828             var queue = [sourceFile.resolvedPath];
102829             while (queue.length) {
102830                 var path = queue.pop();
102831                 if (!seenMap.has(path)) {
102832                     seenMap.set(path, true);
102833                     var references = state.referencedMap.get(path);
102834                     if (references) {
102835                         var iterator = references.keys();
102836                         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
102837                             queue.push(iterResult.value);
102838                         }
102839                     }
102840                 }
102841             }
102842             return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) {
102843                 var file = programOfThisState.getSourceFileByPath(path);
102844                 return file ? file.fileName : path;
102845             }));
102846         }
102847         BuilderState.getAllDependencies = getAllDependencies;
102848         /**
102849          * Gets the names of all files from the program
102850          */
102851         function getAllFileNames(state, programOfThisState) {
102852             if (!state.allFileNames) {
102853                 var sourceFiles = programOfThisState.getSourceFiles();
102854                 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
102855             }
102856             return state.allFileNames;
102857         }
102858         /**
102859          * Gets the files referenced by the the file path
102860          */
102861         function getReferencedByPaths(state, referencedFilePath) {
102862             return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
102863                 var filePath = _a[0], referencesInFile = _a[1];
102864                 return referencesInFile.has(referencedFilePath) ? filePath : undefined;
102865             }));
102866         }
102867         BuilderState.getReferencedByPaths = getReferencedByPaths;
102868         /**
102869          * For script files that contains only ambient external modules, although they are not actually external module files,
102870          * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
102871          * there are no point to rebuild all script files if these special files have changed. However, if any statement
102872          * in the file is not ambient external module, we treat it as a regular script file.
102873          */
102874         function containsOnlyAmbientModules(sourceFile) {
102875             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
102876                 var statement = _a[_i];
102877                 if (!ts.isModuleWithStringLiteralName(statement)) {
102878                     return false;
102879                 }
102880             }
102881             return true;
102882         }
102883         /**
102884          * Return true if file contains anything that augments to global scope we need to build them as if
102885          * they are global files as well as module
102886          */
102887         function containsGlobalScopeAugmentation(sourceFile) {
102888             return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
102889         }
102890         /**
102891          * Return true if the file will invalidate all files because it affectes global scope
102892          */
102893         function isFileAffectingGlobalScope(sourceFile) {
102894             return containsGlobalScopeAugmentation(sourceFile) ||
102895                 !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
102896         }
102897         /**
102898          * Gets all files of the program excluding the default library file
102899          */
102900         function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
102901             // Use cached result
102902             if (state.allFilesExcludingDefaultLibraryFile) {
102903                 return state.allFilesExcludingDefaultLibraryFile;
102904             }
102905             var result;
102906             if (firstSourceFile)
102907                 addSourceFile(firstSourceFile);
102908             for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
102909                 var sourceFile = _a[_i];
102910                 if (sourceFile !== firstSourceFile) {
102911                     addSourceFile(sourceFile);
102912                 }
102913             }
102914             state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
102915             return state.allFilesExcludingDefaultLibraryFile;
102916             function addSourceFile(sourceFile) {
102917                 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
102918                     (result || (result = [])).push(sourceFile);
102919                 }
102920             }
102921         }
102922         BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
102923         /**
102924          * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
102925          */
102926         function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
102927             var compilerOptions = programOfThisState.getCompilerOptions();
102928             // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
102929             // so returning the file itself is good enough.
102930             if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) {
102931                 return [sourceFileWithUpdatedShape];
102932             }
102933             return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
102934         }
102935         /**
102936          * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
102937          */
102938         function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
102939             if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
102940                 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
102941             }
102942             var compilerOptions = programOfThisState.getCompilerOptions();
102943             if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) {
102944                 return [sourceFileWithUpdatedShape];
102945             }
102946             // Now we need to if each file in the referencedBy list has a shape change as well.
102947             // Because if so, its own referencedBy files need to be saved as well to make the
102948             // emitting result consistent with files on disk.
102949             var seenFileNamesMap = ts.createMap();
102950             // Start with the paths this file was referenced by
102951             seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
102952             var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
102953             while (queue.length > 0) {
102954                 var currentPath = queue.pop();
102955                 if (!seenFileNamesMap.has(currentPath)) {
102956                     var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
102957                     seenFileNamesMap.set(currentPath, currentSourceFile);
102958                     if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217
102959                         queue.push.apply(// TODO: GH#18217
102960                         queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
102961                     }
102962                 }
102963             }
102964             // Return array of values that needs emit
102965             // Return array of values that needs emit
102966             return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
102967         }
102968     })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
102969     function cloneMapOrUndefined(map) {
102970         return map ? ts.cloneMap(map) : undefined;
102971     }
102972     ts.cloneMapOrUndefined = cloneMapOrUndefined;
102973 })(ts || (ts = {}));
102974 /*@internal*/
102975 var ts;
102976 (function (ts) {
102977     var BuilderFileEmit;
102978     (function (BuilderFileEmit) {
102979         BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
102980         BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
102981     })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
102982     function hasSameKeys(map1, map2) {
102983         // Has same size and every key is present in both maps
102984         return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
102985     }
102986     /**
102987      * Create the state so that we can iterate on changedFiles/affected files
102988      */
102989     function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
102990         var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
102991         state.program = newProgram;
102992         var compilerOptions = newProgram.getCompilerOptions();
102993         state.compilerOptions = compilerOptions;
102994         // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
102995         if (!compilerOptions.outFile && !compilerOptions.out) {
102996             state.semanticDiagnosticsPerFile = ts.createMap();
102997         }
102998         state.changedFilesSet = ts.createMap();
102999         var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
103000         var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
103001         var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
103002             !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
103003         if (useOldState) {
103004             // Verify the sanity of old state
103005             if (!oldState.currentChangedFilePath) {
103006                 var affectedSignatures = oldState.currentAffectedFilesSignatures;
103007                 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
103008             }
103009             var changedFilesSet = oldState.changedFilesSet;
103010             if (canCopySemanticDiagnostics) {
103011                 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
103012             }
103013             // Copy old state's changed files set
103014             if (changedFilesSet) {
103015                 ts.copyEntries(changedFilesSet, state.changedFilesSet);
103016             }
103017             if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
103018                 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
103019                 state.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(oldState.affectedFilesPendingEmitKind);
103020                 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
103021                 state.seenAffectedFiles = ts.createMap();
103022             }
103023         }
103024         // Update changed files and copy semantic diagnostics if we can
103025         var referencedMap = state.referencedMap;
103026         var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
103027         var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
103028         var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
103029         state.fileInfos.forEach(function (info, sourceFilePath) {
103030             var oldInfo;
103031             var newReferences;
103032             // if not using old state, every file is changed
103033             if (!useOldState ||
103034                 // File wasnt present in old state
103035                 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
103036                 // versions dont match
103037                 oldInfo.version !== info.version ||
103038                 // Referenced files changed
103039                 !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
103040                 // Referenced file was deleted in the new program
103041                 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
103042                 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
103043                 state.changedFilesSet.set(sourceFilePath, true);
103044             }
103045             else if (canCopySemanticDiagnostics) {
103046                 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
103047                 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
103048                     return;
103049                 }
103050                 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
103051                     return;
103052                 }
103053                 // Unchanged file copy diagnostics
103054                 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
103055                 if (diagnostics) {
103056                     state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
103057                     if (!state.semanticDiagnosticsFromOldState) {
103058                         state.semanticDiagnosticsFromOldState = ts.createMap();
103059                     }
103060                     state.semanticDiagnosticsFromOldState.set(sourceFilePath, true);
103061                 }
103062             }
103063         });
103064         // If the global file is removed, add all files as changed
103065         if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) {
103066             ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
103067                 .forEach(function (file) { return state.changedFilesSet.set(file.resolvedPath, true); });
103068         }
103069         else if (oldCompilerOptions && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
103070             // Add all files to affectedFilesPendingEmit since emit changed
103071             newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
103072             ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
103073             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103074         }
103075         state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit;
103076         return state;
103077     }
103078     function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
103079         if (!diagnostics.length)
103080             return ts.emptyArray;
103081         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
103082         return diagnostics.map(function (diagnostic) {
103083             var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
103084             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103085             result.source = diagnostic.source;
103086             var relatedInformation = diagnostic.relatedInformation;
103087             result.relatedInformation = relatedInformation ?
103088                 relatedInformation.length ?
103089                     relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
103090                     ts.emptyArray :
103091                 undefined;
103092             return result;
103093         });
103094         function toPath(path) {
103095             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
103096         }
103097     }
103098     function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
103099         var file = diagnostic.file;
103100         return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
103101     }
103102     /**
103103      * Releases program and other related not needed properties
103104      */
103105     function releaseCache(state) {
103106         ts.BuilderState.releaseCache(state);
103107         state.program = undefined;
103108     }
103109     /**
103110      * Creates a clone of the state
103111      */
103112     function cloneBuilderProgramState(state) {
103113         var newState = ts.BuilderState.clone(state);
103114         newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile);
103115         newState.changedFilesSet = ts.cloneMap(state.changedFilesSet);
103116         newState.affectedFiles = state.affectedFiles;
103117         newState.affectedFilesIndex = state.affectedFilesIndex;
103118         newState.currentChangedFilePath = state.currentChangedFilePath;
103119         newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures);
103120         newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap);
103121         newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles);
103122         newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
103123         newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState);
103124         newState.program = state.program;
103125         newState.compilerOptions = state.compilerOptions;
103126         newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
103127         newState.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(state.affectedFilesPendingEmitKind);
103128         newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
103129         newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles);
103130         newState.programEmitComplete = state.programEmitComplete;
103131         return newState;
103132     }
103133     /**
103134      * Verifies that source file is ok to be used in calls that arent handled by next
103135      */
103136     function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
103137         ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
103138     }
103139     /**
103140      * This function returns the next affected file to be processed.
103141      * Note that until doneAffected is called it would keep reporting same result
103142      * This is to allow the callers to be able to actually remove affected file only when the operation is complete
103143      * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
103144      */
103145     function getNextAffectedFile(state, cancellationToken, computeHash) {
103146         while (true) {
103147             var affectedFiles = state.affectedFiles;
103148             if (affectedFiles) {
103149                 var seenAffectedFiles = state.seenAffectedFiles;
103150                 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
103151                 while (affectedFilesIndex < affectedFiles.length) {
103152                     var affectedFile = affectedFiles[affectedFilesIndex];
103153                     if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
103154                         // Set the next affected file as seen and remove the cached semantic diagnostics
103155                         state.affectedFilesIndex = affectedFilesIndex;
103156                         handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
103157                         return affectedFile;
103158                     }
103159                     affectedFilesIndex++;
103160                 }
103161                 // Remove the changed file from the change set
103162                 state.changedFilesSet.delete(state.currentChangedFilePath);
103163                 state.currentChangedFilePath = undefined;
103164                 // Commit the changes in file signature
103165                 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
103166                 state.currentAffectedFilesSignatures.clear();
103167                 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
103168                 state.affectedFiles = undefined;
103169             }
103170             // Get next changed file
103171             var nextKey = state.changedFilesSet.keys().next();
103172             if (nextKey.done) {
103173                 // Done
103174                 return undefined;
103175             }
103176             // With --out or --outFile all outputs go into single file
103177             // so operations are performed directly on program, return program
103178             var program = ts.Debug.checkDefined(state.program);
103179             var compilerOptions = program.getCompilerOptions();
103180             if (compilerOptions.outFile || compilerOptions.out) {
103181                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103182                 return program;
103183             }
103184             // Get next batch of affected files
103185             state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap();
103186             if (state.exportedModulesMap) {
103187                 state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap();
103188             }
103189             state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
103190             state.currentChangedFilePath = nextKey.value;
103191             state.affectedFilesIndex = 0;
103192             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103193         }
103194     }
103195     /**
103196      * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
103197      */
103198     function getNextAffectedFilePendingEmit(state) {
103199         var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
103200         if (affectedFilesPendingEmit) {
103201             var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap());
103202             for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
103203                 var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
103204                 if (affectedFile) {
103205                     var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
103206                     var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
103207                     if (seenKind === undefined || seenKind < emitKind) {
103208                         // emit this file
103209                         state.affectedFilesPendingEmitIndex = i;
103210                         return { affectedFile: affectedFile, emitKind: emitKind };
103211                     }
103212                 }
103213             }
103214             state.affectedFilesPendingEmit = undefined;
103215             state.affectedFilesPendingEmitKind = undefined;
103216             state.affectedFilesPendingEmitIndex = undefined;
103217         }
103218         return undefined;
103219     }
103220     /**
103221      *  Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
103222      *  This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
103223      */
103224     function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
103225         removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
103226         // If affected files is everything except default library, then nothing more to do
103227         if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
103228             if (!state.cleanedDiagnosticsOfLibFiles) {
103229                 state.cleanedDiagnosticsOfLibFiles = true;
103230                 var program_1 = ts.Debug.checkDefined(state.program);
103231                 var options_2 = program_1.getCompilerOptions();
103232                 ts.forEach(program_1.getSourceFiles(), function (f) {
103233                     return program_1.isSourceFileDefaultLibrary(f) &&
103234                         !ts.skipTypeChecking(f, options_2, program_1) &&
103235                         removeSemanticDiagnosticsOf(state, f.resolvedPath);
103236                 });
103237             }
103238             return;
103239         }
103240         if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
103241             forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
103242         }
103243     }
103244     /**
103245      * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
103246      * Also we need to make sure signature is updated for these files
103247      */
103248     function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
103249         removeSemanticDiagnosticsOf(state, path);
103250         if (!state.changedFilesSet.has(path)) {
103251             var program = ts.Debug.checkDefined(state.program);
103252             var sourceFile = program.getSourceFileByPath(path);
103253             if (sourceFile) {
103254                 // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
103255                 // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
103256                 // This ensures that we dont later during incremental builds considering wrong signature.
103257                 // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
103258                 ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
103259                 // If not dts emit, nothing more to do
103260                 if (ts.getEmitDeclarations(state.compilerOptions)) {
103261                     addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
103262                 }
103263             }
103264         }
103265         return false;
103266     }
103267     /**
103268      * Removes semantic diagnostics for path and
103269      * returns true if there are no more semantic diagnostics from the old state
103270      */
103271     function removeSemanticDiagnosticsOf(state, path) {
103272         if (!state.semanticDiagnosticsFromOldState) {
103273             return true;
103274         }
103275         state.semanticDiagnosticsFromOldState.delete(path);
103276         state.semanticDiagnosticsPerFile.delete(path);
103277         return !state.semanticDiagnosticsFromOldState.size;
103278     }
103279     function isChangedSignagure(state, path) {
103280         var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
103281         var oldSignagure = ts.Debug.checkDefined(state.fileInfos.get(path)).signature;
103282         return newSignature !== oldSignagure;
103283     }
103284     /**
103285      * Iterate on referencing modules that export entities from affected file
103286      */
103287     function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
103288         // If there was change in signature (dts output) for the changed file,
103289         // then only we need to handle pending file emit
103290         if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
103291             return;
103292         }
103293         if (!isChangedSignagure(state, affectedFile.resolvedPath))
103294             return;
103295         // Since isolated modules dont change js files, files affected by change in signature is itself
103296         // But we need to cleanup semantic diagnostics and queue dts emit for affected files
103297         if (state.compilerOptions.isolatedModules) {
103298             var seenFileNamesMap = ts.createMap();
103299             seenFileNamesMap.set(affectedFile.resolvedPath, true);
103300             var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
103301             while (queue.length > 0) {
103302                 var currentPath = queue.pop();
103303                 if (!seenFileNamesMap.has(currentPath)) {
103304                     seenFileNamesMap.set(currentPath, true);
103305                     var result = fn(state, currentPath);
103306                     if (result && isChangedSignagure(state, currentPath)) {
103307                         var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
103308                         queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
103309                     }
103310                 }
103311             }
103312         }
103313         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103314         var seenFileAndExportsOfFile = ts.createMap();
103315         // Go through exported modules from cache first
103316         // If exported modules has path, all files referencing file exported from are affected
103317         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103318             return exportedModules &&
103319                 exportedModules.has(affectedFile.resolvedPath) &&
103320                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103321         })) {
103322             return;
103323         }
103324         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103325         ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103326             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103327                 exportedModules.has(affectedFile.resolvedPath) &&
103328                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103329         });
103330     }
103331     /**
103332      * Iterate on files referencing referencedPath
103333      */
103334     function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
103335         return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
103336             return referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
103337         });
103338     }
103339     /**
103340      * fn on file and iterate on anything that exports this file
103341      */
103342     function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
103343         if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) {
103344             return false;
103345         }
103346         if (fn(state, filePath)) {
103347             // If there are no more diagnostics from old cache, done
103348             return true;
103349         }
103350         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103351         // Go through exported modules from cache first
103352         // If exported modules has path, all files referencing file exported from are affected
103353         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103354             return exportedModules &&
103355                 exportedModules.has(filePath) &&
103356                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103357         })) {
103358             return true;
103359         }
103360         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103361         if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103362             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103363                 exportedModules.has(filePath) &&
103364                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103365         })) {
103366             return true;
103367         }
103368         // Remove diagnostics of files that import this file (without going to exports of referencing files)
103369         return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
103370             return referencesInFile.has(filePath) &&
103371                 !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
103372                 fn(state, referencingFilePath);
103373         } // Dont add to seen since this is not yet done with the export removal
103374         );
103375     }
103376     /**
103377      * This is called after completing operation on the next affected file.
103378      * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
103379      */
103380     function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103381         if (isBuildInfoEmit) {
103382             state.emittedBuildInfo = true;
103383         }
103384         else if (affected === state.program) {
103385             state.changedFilesSet.clear();
103386             state.programEmitComplete = true;
103387         }
103388         else {
103389             state.seenAffectedFiles.set(affected.resolvedPath, true);
103390             if (emitKind !== undefined) {
103391                 (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.resolvedPath, emitKind);
103392             }
103393             if (isPendingEmit) {
103394                 state.affectedFilesPendingEmitIndex++;
103395             }
103396             else {
103397                 state.affectedFilesIndex++;
103398             }
103399         }
103400     }
103401     /**
103402      * Returns the result with affected file
103403      */
103404     function toAffectedFileResult(state, result, affected) {
103405         doneWithAffectedFile(state, affected);
103406         return { result: result, affected: affected };
103407     }
103408     /**
103409      * Returns the result with affected file
103410      */
103411     function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103412         doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
103413         return { result: result, affected: affected };
103414     }
103415     /**
103416      * Gets semantic diagnostics for the file which are
103417      * bindAndCheckDiagnostics (from cache) and program diagnostics
103418      */
103419     function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103420         return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
103421     }
103422     /**
103423      * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
103424      * 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
103425      */
103426     function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103427         var path = sourceFile.resolvedPath;
103428         if (state.semanticDiagnosticsPerFile) {
103429             var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
103430             // Report the bind and check diagnostics from the cache if we already have those diagnostics present
103431             if (cachedDiagnostics) {
103432                 return cachedDiagnostics;
103433             }
103434         }
103435         // Diagnostics werent cached, get them from program, and cache the result
103436         var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
103437         if (state.semanticDiagnosticsPerFile) {
103438             state.semanticDiagnosticsPerFile.set(path, diagnostics);
103439         }
103440         return diagnostics;
103441     }
103442     /**
103443      * Gets the program information to be emitted in buildInfo so that we can use it to create new program
103444      */
103445     function getProgramBuildInfo(state, getCanonicalFileName) {
103446         if (state.compilerOptions.outFile || state.compilerOptions.out)
103447             return undefined;
103448         var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory();
103449         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
103450         var fileInfos = {};
103451         state.fileInfos.forEach(function (value, key) {
103452             var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
103453             fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope };
103454         });
103455         var result = {
103456             fileInfos: fileInfos,
103457             options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
103458         };
103459         if (state.referencedMap) {
103460             var referencedMap = {};
103461             for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
103462                 var key = _a[_i];
103463                 referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103464             }
103465             result.referencedMap = referencedMap;
103466         }
103467         if (state.exportedModulesMap) {
103468             var exportedModulesMap = {};
103469             for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) {
103470                 var key = _c[_b];
103471                 var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
103472                 // Not in temporary cache, use existing value
103473                 if (newValue === undefined)
103474                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103475                 // Value in cache and has updated value map, use that
103476                 else if (newValue)
103477                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103478             }
103479             result.exportedModulesMap = exportedModulesMap;
103480         }
103481         if (state.semanticDiagnosticsPerFile) {
103482             var semanticDiagnosticsPerFile = [];
103483             for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) {
103484                 var key = _e[_d];
103485                 var value = state.semanticDiagnosticsPerFile.get(key);
103486                 semanticDiagnosticsPerFile.push(value.length ?
103487                     [
103488                         relativeToBuildInfo(key),
103489                         state.hasReusableDiagnostic ?
103490                             value :
103491                             convertToReusableDiagnostics(value, relativeToBuildInfo)
103492                     ] :
103493                     relativeToBuildInfo(key));
103494             }
103495             result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
103496         }
103497         return result;
103498         function relativeToBuildInfoEnsuringAbsolutePath(path) {
103499             return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
103500         }
103501         function relativeToBuildInfo(path) {
103502             return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
103503         }
103504     }
103505     function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
103506         var result = {};
103507         var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
103508         for (var name in options) {
103509             if (ts.hasProperty(options, name)) {
103510                 result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo);
103511             }
103512         }
103513         if (result.configFilePath) {
103514             result.configFilePath = relativeToBuildInfo(result.configFilePath);
103515         }
103516         return result;
103517     }
103518     function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
103519         if (option) {
103520             if (option.type === "list") {
103521                 var values = value;
103522                 if (option.element.isFilePath && values.length) {
103523                     return values.map(relativeToBuildInfo);
103524                 }
103525             }
103526             else if (option.isFilePath) {
103527                 return relativeToBuildInfo(value);
103528             }
103529         }
103530         return value;
103531     }
103532     function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
103533         ts.Debug.assert(!!diagnostics.length);
103534         return diagnostics.map(function (diagnostic) {
103535             var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
103536             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103537             result.source = diagnostic.source;
103538             var relatedInformation = diagnostic.relatedInformation;
103539             result.relatedInformation = relatedInformation ?
103540                 relatedInformation.length ?
103541                     relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
103542                     ts.emptyArray :
103543                 undefined;
103544             return result;
103545         });
103546     }
103547     function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
103548         var file = diagnostic.file;
103549         return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
103550     }
103551     var BuilderProgramKind;
103552     (function (BuilderProgramKind) {
103553         BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
103554         BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
103555     })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
103556     function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103557         var host;
103558         var newProgram;
103559         var oldProgram;
103560         if (newProgramOrRootNames === undefined) {
103561             ts.Debug.assert(hostOrOptions === undefined);
103562             host = oldProgramOrHost;
103563             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103564             ts.Debug.assert(!!oldProgram);
103565             newProgram = oldProgram.getProgram();
103566         }
103567         else if (ts.isArray(newProgramOrRootNames)) {
103568             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103569             newProgram = ts.createProgram({
103570                 rootNames: newProgramOrRootNames,
103571                 options: hostOrOptions,
103572                 host: oldProgramOrHost,
103573                 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
103574                 configFileParsingDiagnostics: configFileParsingDiagnostics,
103575                 projectReferences: projectReferences
103576             });
103577             host = oldProgramOrHost;
103578         }
103579         else {
103580             newProgram = newProgramOrRootNames;
103581             host = hostOrOptions;
103582             oldProgram = oldProgramOrHost;
103583             configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
103584         }
103585         return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
103586     }
103587     ts.getBuilderCreationParameters = getBuilderCreationParameters;
103588     function createBuilderProgram(kind, _a) {
103589         var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
103590         // Return same program if underlying program doesnt change
103591         var oldState = oldProgram && oldProgram.getState();
103592         if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
103593             newProgram = undefined; // TODO: GH#18217
103594             oldState = undefined;
103595             return oldProgram;
103596         }
103597         /**
103598          * Create the canonical file name for identity
103599          */
103600         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103601         /**
103602          * Computing hash to for signature verification
103603          */
103604         var computeHash = host.createHash || ts.generateDjb2Hash;
103605         var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
103606         var backupState;
103607         newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
103608         // To ensure that we arent storing any references to old program or new program without state
103609         newProgram = undefined; // TODO: GH#18217
103610         oldProgram = undefined;
103611         oldState = undefined;
103612         var builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
103613         builderProgram.getState = function () { return state; };
103614         builderProgram.backupState = function () {
103615             ts.Debug.assert(backupState === undefined);
103616             backupState = cloneBuilderProgramState(state);
103617         };
103618         builderProgram.restoreState = function () {
103619             state = ts.Debug.checkDefined(backupState);
103620             backupState = undefined;
103621         };
103622         builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); };
103623         builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
103624         builderProgram.emit = emit;
103625         builderProgram.releaseProgram = function () {
103626             releaseCache(state);
103627             backupState = undefined;
103628         };
103629         if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
103630             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103631         }
103632         else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103633             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103634             builderProgram.emitNextAffectedFile = emitNextAffectedFile;
103635         }
103636         else {
103637             ts.notImplemented();
103638         }
103639         return builderProgram;
103640         /**
103641          * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
103642          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103643          * in that order would be used to write the files
103644          */
103645         function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103646             var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103647             var emitKind = 1 /* Full */;
103648             var isPendingEmitFile = false;
103649             if (!affected) {
103650                 if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
103651                     var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
103652                     if (!pendingAffectedFile) {
103653                         if (state.emittedBuildInfo) {
103654                             return undefined;
103655                         }
103656                         var affected_1 = ts.Debug.checkDefined(state.program);
103657                         return toAffectedFileEmitResult(state, 
103658                         // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103659                         // Otherwise just affected file
103660                         affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */, 
103661                         /*isPendingEmitFile*/ false, 
103662                         /*isBuildInfoEmit*/ true);
103663                     }
103664                     (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
103665                     isPendingEmitFile = true;
103666                 }
103667                 else {
103668                     var program = ts.Debug.checkDefined(state.program);
103669                     if (state.programEmitComplete)
103670                         return undefined;
103671                     affected = program;
103672                 }
103673             }
103674             return toAffectedFileEmitResult(state, 
103675             // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103676             // Otherwise just affected file
103677             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);
103678         }
103679         /**
103680          * Emits the JavaScript and declaration files.
103681          * When targetSource file is specified, emits the files corresponding to that source file,
103682          * otherwise for the whole program.
103683          * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
103684          * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
103685          * it will only emit all the affected files instead of whole program
103686          *
103687          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103688          * in that order would be used to write the files
103689          */
103690         function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103691             if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103692                 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
103693                 var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, cancellationToken);
103694                 if (result)
103695                     return result;
103696                 if (!targetSourceFile) {
103697                     // Emit and report any errors we ran into.
103698                     var sourceMaps = [];
103699                     var emitSkipped = false;
103700                     var diagnostics = void 0;
103701                     var emittedFiles = [];
103702                     var affectedEmitResult = void 0;
103703                     while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
103704                         emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
103705                         diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
103706                         emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
103707                         sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
103708                     }
103709                     return {
103710                         emitSkipped: emitSkipped,
103711                         diagnostics: diagnostics || ts.emptyArray,
103712                         emittedFiles: emittedFiles,
103713                         sourceMaps: sourceMaps
103714                     };
103715                 }
103716             }
103717             return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
103718         }
103719         /**
103720          * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
103721          * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
103722          */
103723         function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
103724             while (true) {
103725                 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103726                 if (!affected) {
103727                     // Done
103728                     return undefined;
103729                 }
103730                 else if (affected === state.program) {
103731                     // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
103732                     return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
103733                 }
103734                 // Add file to affected file pending emit to handle for later emit time
103735                 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103736                     addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
103737                 }
103738                 // Get diagnostics for the affected file if its not ignored
103739                 if (ignoreSourceFile && ignoreSourceFile(affected)) {
103740                     // Get next affected file
103741                     doneWithAffectedFile(state, affected);
103742                     continue;
103743                 }
103744                 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
103745             }
103746         }
103747         /**
103748          * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
103749          * The semantic diagnostics are cached and managed here
103750          * Note that it is assumed that when asked about semantic diagnostics through this API,
103751          * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
103752          * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
103753          * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
103754          */
103755         function getSemanticDiagnostics(sourceFile, cancellationToken) {
103756             assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
103757             var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions();
103758             if (compilerOptions.outFile || compilerOptions.out) {
103759                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103760                 // We dont need to cache the diagnostics just return them from program
103761                 return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
103762             }
103763             if (sourceFile) {
103764                 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
103765             }
103766             // When semantic builder asks for diagnostics of the whole program,
103767             // ensure that all the affected files are handled
103768             // eslint-disable-next-line no-empty
103769             while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
103770             }
103771             var diagnostics;
103772             for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
103773                 var sourceFile_1 = _a[_i];
103774                 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
103775             }
103776             return diagnostics || ts.emptyArray;
103777         }
103778     }
103779     ts.createBuilderProgram = createBuilderProgram;
103780     function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
103781         if (!state.affectedFilesPendingEmit)
103782             state.affectedFilesPendingEmit = [];
103783         if (!state.affectedFilesPendingEmitKind)
103784             state.affectedFilesPendingEmitKind = ts.createMap();
103785         var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
103786         state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
103787         state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
103788         // affectedFilesPendingEmitIndex === undefined
103789         // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
103790         //   so start from 0 as array would be affectedFilesPendingEmit
103791         // else, continue to iterate from existing index, the current set is appended to existing files
103792         if (state.affectedFilesPendingEmitIndex === undefined) {
103793             state.affectedFilesPendingEmitIndex = 0;
103794         }
103795     }
103796     function getMapOfReferencedSet(mapLike, toPath) {
103797         if (!mapLike)
103798             return undefined;
103799         var map = ts.createMap();
103800         // Copies keys/values from template. Note that for..in will not throw if
103801         // template is undefined, and instead will just exit the loop.
103802         for (var key in mapLike) {
103803             if (ts.hasProperty(mapLike, key)) {
103804                 map.set(toPath(key), ts.arrayToSet(mapLike[key], toPath));
103805             }
103806         }
103807         return map;
103808     }
103809     function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
103810         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
103811         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103812         var fileInfos = ts.createMap();
103813         for (var key in program.fileInfos) {
103814             if (ts.hasProperty(program.fileInfos, key)) {
103815                 fileInfos.set(toPath(key), program.fileInfos[key]);
103816             }
103817         }
103818         var state = {
103819             fileInfos: fileInfos,
103820             compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
103821             referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
103822             exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
103823             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]; }),
103824             hasReusableDiagnostic: true
103825         };
103826         return {
103827             getState: function () { return state; },
103828             backupState: ts.noop,
103829             restoreState: ts.noop,
103830             getProgram: ts.notImplemented,
103831             getProgramOrUndefined: ts.returnUndefined,
103832             releaseProgram: ts.noop,
103833             getCompilerOptions: function () { return state.compilerOptions; },
103834             getSourceFile: ts.notImplemented,
103835             getSourceFiles: ts.notImplemented,
103836             getOptionsDiagnostics: ts.notImplemented,
103837             getGlobalDiagnostics: ts.notImplemented,
103838             getConfigFileParsingDiagnostics: ts.notImplemented,
103839             getSyntacticDiagnostics: ts.notImplemented,
103840             getDeclarationDiagnostics: ts.notImplemented,
103841             getSemanticDiagnostics: ts.notImplemented,
103842             emit: ts.notImplemented,
103843             getAllDependencies: ts.notImplemented,
103844             getCurrentDirectory: ts.notImplemented,
103845             emitNextAffectedFile: ts.notImplemented,
103846             getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
103847             close: ts.noop,
103848         };
103849         function toPath(path) {
103850             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
103851         }
103852         function toAbsolutePath(path) {
103853             return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
103854         }
103855     }
103856     ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
103857     function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
103858         return {
103859             getState: ts.notImplemented,
103860             backupState: ts.noop,
103861             restoreState: ts.noop,
103862             getProgram: getProgram,
103863             getProgramOrUndefined: function () { return state.program; },
103864             releaseProgram: function () { return state.program = undefined; },
103865             getCompilerOptions: function () { return state.compilerOptions; },
103866             getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
103867             getSourceFiles: function () { return getProgram().getSourceFiles(); },
103868             getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
103869             getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
103870             getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
103871             getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
103872             getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
103873             getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
103874             emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
103875             getAllDependencies: ts.notImplemented,
103876             getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
103877             close: ts.noop,
103878         };
103879         function getProgram() {
103880             return ts.Debug.checkDefined(state.program);
103881         }
103882     }
103883     ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
103884 })(ts || (ts = {}));
103885 var ts;
103886 (function (ts) {
103887     function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103888         return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
103889     }
103890     ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
103891     function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103892         return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
103893     }
103894     ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
103895     function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103896         var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
103897         return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
103898     }
103899     ts.createAbstractBuilder = createAbstractBuilder;
103900 })(ts || (ts = {}));
103901 /*@internal*/
103902 var ts;
103903 (function (ts) {
103904     function removeIgnoredPath(path) {
103905         // Consider whole staging folder as if node_modules changed.
103906         if (ts.endsWith(path, "/node_modules/.staging")) {
103907             return ts.removeSuffix(path, "/.staging");
103908         }
103909         return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
103910             undefined :
103911             path;
103912     }
103913     ts.removeIgnoredPath = removeIgnoredPath;
103914     /**
103915      * Filter out paths like
103916      * "/", "/user", "/user/username", "/user/username/folderAtRoot",
103917      * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
103918      * @param dirPath
103919      */
103920     function canWatchDirectory(dirPath) {
103921         var rootLength = ts.getRootLength(dirPath);
103922         if (dirPath.length === rootLength) {
103923             // Ignore "/", "c:/"
103924             return false;
103925         }
103926         var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
103927         if (nextDirectorySeparator === -1) {
103928             // ignore "/user", "c:/users" or "c:/folderAtRoot"
103929             return false;
103930         }
103931         var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
103932         var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
103933         if (isNonDirectorySeparatorRoot &&
103934             dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
103935             pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
103936             nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
103937             if (nextDirectorySeparator === -1) {
103938                 // ignore "//vda1cs4850/c$/folderAtRoot"
103939                 return false;
103940             }
103941             pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
103942         }
103943         if (isNonDirectorySeparatorRoot &&
103944             pathPartForUserCheck.search(/users\//i) !== 0) {
103945             // Paths like c:/folderAtRoot/subFolder are allowed
103946             return true;
103947         }
103948         for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
103949             searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
103950             if (searchIndex === 0) {
103951                 // Folder isnt at expected minimum levels
103952                 return false;
103953             }
103954         }
103955         return true;
103956     }
103957     ts.canWatchDirectory = canWatchDirectory;
103958     function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
103959         var filesWithChangedSetOfUnresolvedImports;
103960         var filesWithInvalidatedResolutions;
103961         var filesWithInvalidatedNonRelativeUnresolvedImports;
103962         var nonRelativeExternalModuleResolutions = ts.createMultiMap();
103963         var resolutionsWithFailedLookups = [];
103964         var resolvedFileToResolution = ts.createMultiMap();
103965         var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
103966         var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
103967         // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
103968         // The key in the map is source file's path.
103969         // The values are Map of resolutions with key being name lookedup.
103970         var resolvedModuleNames = ts.createMap();
103971         var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
103972         var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
103973         var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
103974         var resolvedTypeReferenceDirectives = ts.createMap();
103975         var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
103976         /**
103977          * These are the extensions that failed lookup files will have by default,
103978          * any other extension of failed lookup will be store that path in custom failed lookup path
103979          * This helps in not having to comb through all resolutions when files are added/removed
103980          * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
103981          */
103982         var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
103983         var customFailedLookupPaths = ts.createMap();
103984         var directoryWatchesOfFailedLookups = ts.createMap();
103985         var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
103986         var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
103987         var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
103988         // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
103989         var typeRootsWatches = ts.createMap();
103990         return {
103991             startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
103992             finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
103993             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
103994             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
103995             startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
103996             finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
103997             resolveModuleNames: resolveModuleNames,
103998             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
103999             resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
104000             removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
104001             removeResolutionsOfFile: removeResolutionsOfFile,
104002             invalidateResolutionOfFile: invalidateResolutionOfFile,
104003             setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
104004             createHasInvalidatedResolution: createHasInvalidatedResolution,
104005             updateTypeRootsWatch: updateTypeRootsWatch,
104006             closeTypeRootsWatch: closeTypeRootsWatch,
104007             clear: clear
104008         };
104009         function getResolvedModule(resolution) {
104010             return resolution.resolvedModule;
104011         }
104012         function getResolvedTypeReferenceDirective(resolution) {
104013             return resolution.resolvedTypeReferenceDirective;
104014         }
104015         function isInDirectoryPath(dir, file) {
104016             if (dir === undefined || file.length <= dir.length) {
104017                 return false;
104018             }
104019             return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
104020         }
104021         function clear() {
104022             ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
104023             customFailedLookupPaths.clear();
104024             nonRelativeExternalModuleResolutions.clear();
104025             closeTypeRootsWatch();
104026             resolvedModuleNames.clear();
104027             resolvedTypeReferenceDirectives.clear();
104028             resolvedFileToResolution.clear();
104029             resolutionsWithFailedLookups.length = 0;
104030             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
104031             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
104032             clearPerDirectoryResolutions();
104033         }
104034         function startRecordingFilesWithChangedResolutions() {
104035             filesWithChangedSetOfUnresolvedImports = [];
104036         }
104037         function finishRecordingFilesWithChangedResolutions() {
104038             var collected = filesWithChangedSetOfUnresolvedImports;
104039             filesWithChangedSetOfUnresolvedImports = undefined;
104040             return collected;
104041         }
104042         function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
104043             if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
104044                 return false;
104045             }
104046             // Invalidated if file has unresolved imports
104047             var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
104048             return !!value && !!value.length;
104049         }
104050         function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
104051             if (forceAllFilesAsInvalidated) {
104052                 // Any file asked would have invalidated resolution
104053                 filesWithInvalidatedResolutions = undefined;
104054                 return ts.returnTrue;
104055             }
104056             var collected = filesWithInvalidatedResolutions;
104057             filesWithInvalidatedResolutions = undefined;
104058             return function (path) { return (!!collected && collected.has(path)) ||
104059                 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
104060         }
104061         function clearPerDirectoryResolutions() {
104062             perDirectoryResolvedModuleNames.clear();
104063             nonRelativeModuleNameCache.clear();
104064             perDirectoryResolvedTypeReferenceDirectives.clear();
104065             nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
104066             nonRelativeExternalModuleResolutions.clear();
104067         }
104068         function finishCachingPerDirectoryResolution() {
104069             filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
104070             clearPerDirectoryResolutions();
104071             directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
104072                 if (watcher.refCount === 0) {
104073                     directoryWatchesOfFailedLookups.delete(path);
104074                     watcher.watcher.close();
104075                 }
104076             });
104077         }
104078         function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
104079             var _a;
104080             var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
104081             // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
104082             if (!resolutionHost.getGlobalCache) {
104083                 return primaryResult;
104084             }
104085             // otherwise try to load typings from @types
104086             var globalCache = resolutionHost.getGlobalCache();
104087             if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
104088                 // create different collection of failed lookup locations for second pass
104089                 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
104090                 var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations;
104091                 if (resolvedModule) {
104092                     // Modify existing resolution so its saved in the directory cache as well
104093                     primaryResult.resolvedModule = resolvedModule;
104094                     (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations);
104095                     return primaryResult;
104096                 }
104097             }
104098             // Default return the result from the first pass
104099             return primaryResult;
104100         }
104101         function resolveNamesWithLocalCache(_a) {
104102             var _b;
104103             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;
104104             var path = resolutionHost.toPath(containingFile);
104105             var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path);
104106             var dirPath = ts.getDirectoryPath(path);
104107             var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
104108             var perDirectoryResolution = perDirectoryCache.get(dirPath);
104109             if (!perDirectoryResolution) {
104110                 perDirectoryResolution = ts.createMap();
104111                 perDirectoryCache.set(dirPath, perDirectoryResolution);
104112             }
104113             var resolvedModules = [];
104114             var compilerOptions = resolutionHost.getCompilationSettings();
104115             var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
104116             // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
104117             var program = resolutionHost.getCurrentProgram();
104118             var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
104119             var unmatchedRedirects = oldRedirect ?
104120                 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
104121                 !!redirectedReference;
104122             var seenNamesInFile = ts.createMap();
104123             for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
104124                 var name = names_3[_i];
104125                 var resolution = resolutionsInFile.get(name);
104126                 // Resolution is valid if it is present and not invalidated
104127                 if (!seenNamesInFile.has(name) &&
104128                     unmatchedRedirects || !resolution || resolution.isInvalidated ||
104129                     // If the name is unresolved import that was invalidated, recalculate
104130                     (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
104131                     var existingResolution = resolution;
104132                     var resolutionInDirectory = perDirectoryResolution.get(name);
104133                     if (resolutionInDirectory) {
104134                         resolution = resolutionInDirectory;
104135                     }
104136                     else {
104137                         resolution = loader(name, containingFile, compilerOptions, ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost, redirectedReference);
104138                         perDirectoryResolution.set(name, resolution);
104139                     }
104140                     resolutionsInFile.set(name, resolution);
104141                     watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
104142                     if (existingResolution) {
104143                         stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
104144                     }
104145                     if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
104146                         filesWithChangedSetOfUnresolvedImports.push(path);
104147                         // reset log changes to avoid recording the same file multiple times
104148                         logChanges = false;
104149                     }
104150                 }
104151                 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
104152                 seenNamesInFile.set(name, true);
104153                 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
104154             }
104155             // Stop watching and remove the unused name
104156             resolutionsInFile.forEach(function (resolution, name) {
104157                 if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
104158                     stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
104159                     resolutionsInFile.delete(name);
104160                 }
104161             });
104162             return resolvedModules;
104163             function resolutionIsEqualTo(oldResolution, newResolution) {
104164                 if (oldResolution === newResolution) {
104165                     return true;
104166                 }
104167                 if (!oldResolution || !newResolution) {
104168                     return false;
104169                 }
104170                 var oldResult = getResolutionWithResolvedFileName(oldResolution);
104171                 var newResult = getResolutionWithResolvedFileName(newResolution);
104172                 if (oldResult === newResult) {
104173                     return true;
104174                 }
104175                 if (!oldResult || !newResult) {
104176                     return false;
104177                 }
104178                 return oldResult.resolvedFileName === newResult.resolvedFileName;
104179             }
104180         }
104181         function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
104182             return resolveNamesWithLocalCache({
104183                 names: typeDirectiveNames,
104184                 containingFile: containingFile,
104185                 redirectedReference: redirectedReference,
104186                 cache: resolvedTypeReferenceDirectives,
104187                 perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives,
104188                 loader: ts.resolveTypeReferenceDirective,
104189                 getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
104190                 shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
104191             });
104192         }
104193         function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
104194             return resolveNamesWithLocalCache({
104195                 names: moduleNames,
104196                 containingFile: containingFile,
104197                 redirectedReference: redirectedReference,
104198                 cache: resolvedModuleNames,
104199                 perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
104200                 loader: resolveModuleName,
104201                 getResolutionWithResolvedFileName: getResolvedModule,
104202                 shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
104203                 reusedNames: reusedNames,
104204                 logChanges: logChangesWhenResolvingModule
104205             });
104206         }
104207         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
104208             var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
104209             return cache && cache.get(moduleName);
104210         }
104211         function isNodeModulesAtTypesDirectory(dirPath) {
104212             return ts.endsWith(dirPath, "/node_modules/@types");
104213         }
104214         function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
104215             if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
104216                 // Ensure failed look up is normalized path
104217                 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
104218                 var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
104219                 var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
104220                 ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath);
104221                 if (failedLookupPathSplit.length > rootSplitLength + 1) {
104222                     // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
104223                     return {
104224                         dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
104225                         dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
104226                     };
104227                 }
104228                 else {
104229                     // Always watch root directory non recursively
104230                     return {
104231                         dir: rootDir,
104232                         dirPath: rootPath,
104233                         nonRecursive: false
104234                     };
104235                 }
104236             }
104237             return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
104238         }
104239         function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
104240             // If directory path contains node module, get the most parent node_modules directory for watching
104241             while (ts.pathContainsNodeModules(dirPath)) {
104242                 dir = ts.getDirectoryPath(dir);
104243                 dirPath = ts.getDirectoryPath(dirPath);
104244             }
104245             // If the directory is node_modules use it to watch, always watch it recursively
104246             if (ts.isNodeModulesDirectory(dirPath)) {
104247                 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
104248             }
104249             var nonRecursive = true;
104250             // Use some ancestor of the root directory
104251             var subDirectoryPath, subDirectory;
104252             if (rootPath !== undefined) {
104253                 while (!isInDirectoryPath(dirPath, rootPath)) {
104254                     var parentPath = ts.getDirectoryPath(dirPath);
104255                     if (parentPath === dirPath) {
104256                         break;
104257                     }
104258                     nonRecursive = false;
104259                     subDirectoryPath = dirPath;
104260                     subDirectory = dir;
104261                     dirPath = parentPath;
104262                     dir = ts.getDirectoryPath(dir);
104263                 }
104264             }
104265             return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
104266         }
104267         function isPathWithDefaultFailedLookupExtension(path) {
104268             return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
104269         }
104270         function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) {
104271             if (resolution.refCount) {
104272                 resolution.refCount++;
104273                 ts.Debug.assertDefined(resolution.files);
104274             }
104275             else {
104276                 resolution.refCount = 1;
104277                 ts.Debug.assert(resolution.files === undefined);
104278                 if (ts.isExternalModuleNameRelative(name)) {
104279                     watchFailedLookupLocationOfResolution(resolution);
104280                 }
104281                 else {
104282                     nonRelativeExternalModuleResolutions.add(name, resolution);
104283                 }
104284                 var resolved = getResolutionWithResolvedFileName(resolution);
104285                 if (resolved && resolved.resolvedFileName) {
104286                     resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104287                 }
104288             }
104289             (resolution.files || (resolution.files = [])).push(filePath);
104290         }
104291         function watchFailedLookupLocationOfResolution(resolution) {
104292             ts.Debug.assert(!!resolution.refCount);
104293             var failedLookupLocations = resolution.failedLookupLocations;
104294             if (!failedLookupLocations.length)
104295                 return;
104296             resolutionsWithFailedLookups.push(resolution);
104297             var setAtRoot = false;
104298             for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
104299                 var failedLookupLocation = failedLookupLocations_1[_i];
104300                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104301                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104302                 if (toWatch) {
104303                     var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
104304                     // If the failed lookup location path is not one of the supported extensions,
104305                     // store it in the custom path
104306                     if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
104307                         var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
104308                         customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
104309                     }
104310                     if (dirPath === rootPath) {
104311                         ts.Debug.assert(!nonRecursive);
104312                         setAtRoot = true;
104313                     }
104314                     else {
104315                         setDirectoryWatcher(dir, dirPath, nonRecursive);
104316                     }
104317                 }
104318             }
104319             if (setAtRoot) {
104320                 // This is always non recursive
104321                 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
104322             }
104323         }
104324         function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
104325             var program = resolutionHost.getCurrentProgram();
104326             if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
104327                 resolutions.forEach(watchFailedLookupLocationOfResolution);
104328             }
104329         }
104330         function setDirectoryWatcher(dir, dirPath, nonRecursive) {
104331             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104332             if (dirWatcher) {
104333                 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
104334                 dirWatcher.refCount++;
104335             }
104336             else {
104337                 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
104338             }
104339         }
104340         function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
104341             ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath);
104342             resolution.refCount--;
104343             if (resolution.refCount) {
104344                 return;
104345             }
104346             var resolved = getResolutionWithResolvedFileName(resolution);
104347             if (resolved && resolved.resolvedFileName) {
104348                 resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104349             }
104350             if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) {
104351                 // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups
104352                 return;
104353             }
104354             var failedLookupLocations = resolution.failedLookupLocations;
104355             var removeAtRoot = false;
104356             for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
104357                 var failedLookupLocation = failedLookupLocations_2[_i];
104358                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104359                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104360                 if (toWatch) {
104361                     var dirPath = toWatch.dirPath;
104362                     var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
104363                     if (refCount) {
104364                         if (refCount === 1) {
104365                             customFailedLookupPaths.delete(failedLookupLocationPath);
104366                         }
104367                         else {
104368                             ts.Debug.assert(refCount > 1);
104369                             customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
104370                         }
104371                     }
104372                     if (dirPath === rootPath) {
104373                         removeAtRoot = true;
104374                     }
104375                     else {
104376                         removeDirectoryWatcher(dirPath);
104377                     }
104378                 }
104379             }
104380             if (removeAtRoot) {
104381                 removeDirectoryWatcher(rootPath);
104382             }
104383         }
104384         function removeDirectoryWatcher(dirPath) {
104385             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104386             // Do not close the watcher yet since it might be needed by other failed lookup locations.
104387             dirWatcher.refCount--;
104388         }
104389         function createDirectoryWatcher(directory, dirPath, nonRecursive) {
104390             return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
104391                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104392                 if (cachedDirectoryStructureHost) {
104393                     // Since the file existence changed, update the sourceFiles cache
104394                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104395                 }
104396                 if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104397                     resolutionHost.onInvalidatedResolution();
104398                 }
104399             }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
104400         }
104401         function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
104402             // Deleted file, stop watching failed lookups for all the resolutions in the file
104403             var resolutions = cache.get(filePath);
104404             if (resolutions) {
104405                 resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); });
104406                 cache.delete(filePath);
104407             }
104408         }
104409         function removeResolutionsFromProjectReferenceRedirects(filePath) {
104410             if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
104411                 return;
104412             }
104413             var program = resolutionHost.getCurrentProgram();
104414             if (!program) {
104415                 return;
104416             }
104417             // If this file is input file for the referenced project, get it
104418             var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
104419             if (!resolvedProjectReference) {
104420                 return;
104421             }
104422             // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
104423             resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
104424         }
104425         function removeResolutionsOfFile(filePath) {
104426             removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule);
104427             removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective);
104428         }
104429         function invalidateResolution(resolution) {
104430             resolution.isInvalidated = true;
104431             var changedInAutoTypeReferenced = false;
104432             for (var _i = 0, _a = ts.Debug.assertDefined(resolution.files); _i < _a.length; _i++) {
104433                 var containingFilePath = _a[_i];
104434                 (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true);
104435                 // When its a file with inferred types resolution, invalidate type reference directive resolution
104436                 changedInAutoTypeReferenced = changedInAutoTypeReferenced || containingFilePath.endsWith(ts.inferredTypesContainingFile);
104437             }
104438             if (changedInAutoTypeReferenced) {
104439                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104440             }
104441         }
104442         function invalidateResolutionOfFile(filePath) {
104443             removeResolutionsOfFile(filePath);
104444             // Resolution is invalidated if the resulting file name is same as the deleted file path
104445             ts.forEach(resolvedFileToResolution.get(filePath), invalidateResolution);
104446         }
104447         function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
104448             ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
104449             filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
104450         }
104451         function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
104452             var isChangedFailedLookupLocation;
104453             if (isCreatingWatchedDirectory) {
104454                 // Watching directory is created
104455                 // Invalidate any resolution has failed lookup in this directory
104456                 isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); };
104457             }
104458             else {
104459                 // If something to do with folder/file starting with "." in node_modules folder, skip it
104460                 var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
104461                 if (!updatedPath)
104462                     return false;
104463                 fileOrDirectoryPath = updatedPath;
104464                 // prevent saving an open file from over-eagerly triggering invalidation
104465                 if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
104466                     return false;
104467                 }
104468                 // Some file or directory in the watching directory is created
104469                 // Return early if it does not have any of the watching extension or not the custom failed lookup path
104470                 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
104471                 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) ||
104472                     isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) {
104473                     // Invalidate any resolution from this directory
104474                     isChangedFailedLookupLocation = function (location) {
104475                         var locationPath = resolutionHost.toPath(location);
104476                         return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath);
104477                     };
104478                 }
104479                 else {
104480                     if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
104481                         return false;
104482                     }
104483                     // Ignore emits from the program
104484                     if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
104485                         return false;
104486                     }
104487                     // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
104488                     isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; };
104489                 }
104490             }
104491             var invalidated = false;
104492             // Resolution is invalidated if the resulting file name is same as the deleted file path
104493             for (var _i = 0, resolutionsWithFailedLookups_1 = resolutionsWithFailedLookups; _i < resolutionsWithFailedLookups_1.length; _i++) {
104494                 var resolution = resolutionsWithFailedLookups_1[_i];
104495                 if (resolution.failedLookupLocations.some(isChangedFailedLookupLocation)) {
104496                     invalidateResolution(resolution);
104497                     invalidated = true;
104498                 }
104499             }
104500             return invalidated;
104501         }
104502         function closeTypeRootsWatch() {
104503             ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
104504         }
104505         function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
104506             if (isInDirectoryPath(rootPath, typeRootPath)) {
104507                 return rootPath;
104508             }
104509             var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
104510             return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
104511         }
104512         function createTypeRootsWatch(typeRootPath, typeRoot) {
104513             // Create new watch and recursive info
104514             return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
104515                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104516                 if (cachedDirectoryStructureHost) {
104517                     // Since the file existence changed, update the sourceFiles cache
104518                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104519                 }
104520                 // For now just recompile
104521                 // We could potentially store more data here about whether it was/would be really be used or not
104522                 // and with that determine to trigger compilation but for now this is enough
104523                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104524                 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
104525                 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
104526                 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
104527                 if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104528                     resolutionHost.onInvalidatedResolution();
104529                 }
104530             }, 1 /* Recursive */);
104531         }
104532         /**
104533          * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
104534          * To be called when compiler options change
104535          */
104536         function updateTypeRootsWatch() {
104537             var options = resolutionHost.getCompilationSettings();
104538             if (options.types) {
104539                 // No need to do any watch since resolution cache is going to handle the failed lookups
104540                 // for the types added by this
104541                 closeTypeRootsWatch();
104542                 return;
104543             }
104544             // we need to assume the directories exist to ensure that we can get all the type root directories that get included
104545             // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
104546             var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
104547             if (typeRoots) {
104548                 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
104549                     createNewValue: createTypeRootsWatch,
104550                     onDeleteValue: ts.closeFileWatcher
104551                 });
104552             }
104553             else {
104554                 closeTypeRootsWatch();
104555             }
104556         }
104557         /**
104558          * Use this function to return if directory exists to get type roots to watch
104559          * If we return directory exists then only the paths will be added to type roots
104560          * Hence return true for all directories except root directories which are filtered from watching
104561          */
104562         function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
104563             var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
104564             var dirPath = resolutionHost.toPath(dir);
104565             return dirPath === rootPath || canWatchDirectory(dirPath);
104566         }
104567     }
104568     ts.createResolutionCache = createResolutionCache;
104569 })(ts || (ts = {}));
104570 // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
104571 /* @internal */
104572 var ts;
104573 (function (ts) {
104574     var moduleSpecifiers;
104575     (function (moduleSpecifiers) {
104576         var RelativePreference;
104577         (function (RelativePreference) {
104578             RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
104579             RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
104580             RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
104581         })(RelativePreference || (RelativePreference = {}));
104582         // See UserPreferences#importPathEnding
104583         var Ending;
104584         (function (Ending) {
104585             Ending[Ending["Minimal"] = 0] = "Minimal";
104586             Ending[Ending["Index"] = 1] = "Index";
104587             Ending[Ending["JsExtension"] = 2] = "JsExtension";
104588         })(Ending || (Ending = {}));
104589         function getPreferences(_a, compilerOptions, importingSourceFile) {
104590             var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
104591             return {
104592                 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
104593                 ending: getEnding(),
104594             };
104595             function getEnding() {
104596                 switch (importModuleSpecifierEnding) {
104597                     case "minimal": return 0 /* Minimal */;
104598                     case "index": return 1 /* Index */;
104599                     case "js": return 2 /* JsExtension */;
104600                     default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
104601                         : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
104602                 }
104603             }
104604         }
104605         function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
104606             return {
104607                 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
104608                 ending: ts.hasJSFileExtension(oldImportSpecifier) ?
104609                     2 /* JsExtension */ :
104610                     ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
104611             };
104612         }
104613         function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) {
104614             var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
104615             if (res === oldImportSpecifier)
104616                 return undefined;
104617             return res;
104618         }
104619         moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
104620         // Note: importingSourceFile is just for usesJsExtensionOnImports
104621         function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences) {
104622             if (preferences === void 0) { preferences = {}; }
104623             return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(preferences, compilerOptions, importingSourceFile));
104624         }
104625         moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
104626         function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host) {
104627             var info = getInfo(importingSourceFileName, host);
104628             var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host);
104629             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions, /*packageNameOnly*/ true); });
104630         }
104631         moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName;
104632         function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences) {
104633             var info = getInfo(importingSourceFileName, host);
104634             var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host);
104635             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) ||
104636                 getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
104637         }
104638         /** Returns an import for each symlink and for the realpath. */
104639         function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, userPreferences) {
104640             var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
104641             if (ambient)
104642                 return [ambient];
104643             var info = getInfo(importingSourceFile.path, host);
104644             var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
104645             var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host);
104646             var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
104647             var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); });
104648             return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); });
104649         }
104650         moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
104651         // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
104652         function getInfo(importingSourceFileName, host) {
104653             var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
104654             var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
104655             return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
104656         }
104657         function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) {
104658             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104659             var ending = _b.ending, relativePreference = _b.relativePreference;
104660             var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
104661             var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
104662                 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
104663             if (!baseUrl || relativePreference === 0 /* Relative */) {
104664                 return relativePath;
104665             }
104666             var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
104667             if (!relativeToBaseUrl) {
104668                 return relativePath;
104669             }
104670             var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
104671             var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
104672             var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;
104673             if (relativePreference === 1 /* NonRelative */) {
104674                 return nonRelative;
104675             }
104676             if (relativePreference !== 2 /* Auto */)
104677                 ts.Debug.assertNever(relativePreference);
104678             // Prefer a relative import over a baseUrl import if it has fewer components.
104679             return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
104680         }
104681         function countPathComponents(path) {
104682             var count = 0;
104683             for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
104684                 if (path.charCodeAt(i) === 47 /* slash */)
104685                     count++;
104686             }
104687             return count;
104688         }
104689         moduleSpecifiers.countPathComponents = countPathComponents;
104690         function usesJsExtensionOnImports(_a) {
104691             var imports = _a.imports;
104692             return ts.firstDefined(imports, function (_a) {
104693                 var text = _a.text;
104694                 return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
104695             }) || false;
104696         }
104697         function numberOfDirectorySeparators(str) {
104698             var match = str.match(/\//g);
104699             return match ? match.length : 0;
104700         }
104701         function comparePathsByNumberOfDirectorySeparators(a, b) {
104702             return ts.compareValues(numberOfDirectorySeparators(a), numberOfDirectorySeparators(b));
104703         }
104704         function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
104705             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104706             var cwd = host.getCurrentDirectory();
104707             var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
104708             var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray;
104709             var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects);
104710             var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
104711             if (!preferSymlinks) {
104712                 var result_12 = ts.forEach(targets, cb);
104713                 if (result_12)
104714                     return result_12;
104715             }
104716             var links = host.getProbableSymlinks
104717                 ? host.getProbableSymlinks(host.getSourceFiles())
104718                 : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd);
104719             var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive;
104720             var result = ts.forEachEntry(links, function (resolved, path) {
104721                 if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) {
104722                     return undefined; // Don't want to a package to globally import from itself
104723                 }
104724                 var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; });
104725                 if (target === undefined)
104726                     return undefined;
104727                 var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName);
104728                 var option = ts.resolvePath(path, relative);
104729                 if (!host.fileExists || host.fileExists(option)) {
104730                     var result_13 = cb(option);
104731                     if (result_13)
104732                         return result_13;
104733                 }
104734             });
104735             return result ||
104736                 (preferSymlinks ? ts.forEach(targets, cb) : undefined);
104737         }
104738         moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
104739         /**
104740          * Looks for existing imports that use symlinks to this module.
104741          * Symlinks will be returned first so they are preferred over the real path.
104742          */
104743         function getAllModulePaths(importingFileName, importedFileName, host) {
104744             var cwd = host.getCurrentDirectory();
104745             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104746             var allFileNames = ts.createMap();
104747             var importedFileFromNodeModules = false;
104748             forEachFileNameOfModule(importingFileName, importedFileName, host, 
104749             /*preferSymlinks*/ true, function (path) {
104750                 // dont return value, so we collect everything
104751                 allFileNames.set(path, getCanonicalFileName(path));
104752                 importedFileFromNodeModules = importedFileFromNodeModules || ts.pathContainsNodeModules(path);
104753             });
104754             // Sort by paths closest to importing file Name directory
104755             var sortedPaths = [];
104756             var _loop_20 = function (directory) {
104757                 var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
104758                 var pathsInDirectory;
104759                 allFileNames.forEach(function (canonicalFileName, fileName) {
104760                     if (ts.startsWith(canonicalFileName, directoryStart)) {
104761                         // If the importedFile is from node modules, use only paths in node_modules folder as option
104762                         if (!importedFileFromNodeModules || ts.pathContainsNodeModules(fileName)) {
104763                             (pathsInDirectory || (pathsInDirectory = [])).push(fileName);
104764                         }
104765                         allFileNames.delete(fileName);
104766                     }
104767                 });
104768                 if (pathsInDirectory) {
104769                     if (pathsInDirectory.length > 1) {
104770                         pathsInDirectory.sort(comparePathsByNumberOfDirectorySeparators);
104771                     }
104772                     sortedPaths.push.apply(sortedPaths, pathsInDirectory);
104773                 }
104774                 var newDirectory = ts.getDirectoryPath(directory);
104775                 if (newDirectory === directory)
104776                     return out_directory_1 = directory, "break";
104777                 directory = newDirectory;
104778                 out_directory_1 = directory;
104779             };
104780             var out_directory_1;
104781             for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
104782                 var state_8 = _loop_20(directory);
104783                 directory = out_directory_1;
104784                 if (state_8 === "break")
104785                     break;
104786             }
104787             if (allFileNames.size) {
104788                 var remainingPaths = ts.arrayFrom(allFileNames.values());
104789                 if (remainingPaths.length > 1)
104790                     remainingPaths.sort(comparePathsByNumberOfDirectorySeparators);
104791                 sortedPaths.push.apply(sortedPaths, remainingPaths);
104792             }
104793             return sortedPaths;
104794         }
104795         function tryGetModuleNameFromAmbientModule(moduleSymbol) {
104796             var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
104797             if (decl) {
104798                 return decl.name.text;
104799             }
104800         }
104801         function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
104802             for (var key in paths) {
104803                 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
104804                     var patternText_1 = _a[_i];
104805                     var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
104806                     var indexOfStar = pattern.indexOf("*");
104807                     if (indexOfStar !== -1) {
104808                         var prefix = pattern.substr(0, indexOfStar);
104809                         var suffix = pattern.substr(indexOfStar + 1);
104810                         if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
104811                             ts.startsWith(relativeToBaseUrl, prefix) &&
104812                             ts.endsWith(relativeToBaseUrl, suffix) ||
104813                             !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
104814                             var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
104815                             return key.replace("*", matchedStar);
104816                         }
104817                     }
104818                     else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
104819                         return key;
104820                     }
104821                 }
104822             }
104823         }
104824         function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
104825             var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
104826             if (normalizedTargetPath === undefined) {
104827                 return undefined;
104828             }
104829             var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
104830             var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
104831             return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
104832                 ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
104833                 : ts.removeFileExtension(relativePath);
104834         }
104835         function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options, packageNameOnly) {
104836             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104837             if (!host.fileExists || !host.readFile) {
104838                 return undefined;
104839             }
104840             var parts = getNodeModulePathParts(moduleFileName);
104841             if (!parts) {
104842                 return undefined;
104843             }
104844             // Simplify the full file path to something that can be resolved by Node.
104845             var moduleSpecifier = moduleFileName;
104846             if (!packageNameOnly) {
104847                 var packageRootIndex = parts.packageRootIndex;
104848                 var moduleFileNameForExtensionless = void 0;
104849                 while (true) {
104850                     // If the module could be imported by a directory name, use that directory's name
104851                     var _b = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _b.moduleFileToTry, packageRootPath = _b.packageRootPath;
104852                     if (packageRootPath) {
104853                         moduleSpecifier = packageRootPath;
104854                         break;
104855                     }
104856                     if (!moduleFileNameForExtensionless)
104857                         moduleFileNameForExtensionless = moduleFileToTry;
104858                     // try with next level of directory
104859                     packageRootIndex = moduleFileName.indexOf(ts.directorySeparator, packageRootIndex + 1);
104860                     if (packageRootIndex === -1) {
104861                         moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless);
104862                         break;
104863                     }
104864                 }
104865             }
104866             var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
104867             // Get a path that's relative to node_modules or the importing file's path
104868             // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
104869             var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
104870             if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
104871                 return undefined;
104872             }
104873             // If the module was found in @types, get the actual Node package name
104874             var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
104875             var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
104876             // For classic resolution, only allow importing from node_modules/@types, not other node_modules
104877             return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
104878             function tryDirectoryWithPackageJson(packageRootIndex) {
104879                 var packageRootPath = moduleFileName.substring(0, packageRootIndex);
104880                 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
104881                 var moduleFileToTry = moduleFileName;
104882                 if (host.fileExists(packageJsonPath)) {
104883                     var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
104884                     var versionPaths = packageJsonContent.typesVersions
104885                         ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
104886                         : undefined;
104887                     if (versionPaths) {
104888                         var subModuleName = moduleFileName.slice(packageRootPath.length + 1);
104889                         var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
104890                         if (fromPaths !== undefined) {
104891                             moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
104892                         }
104893                     }
104894                     // If the file is the main module, it can be imported by the package name
104895                     var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
104896                     if (ts.isString(mainFileRelative)) {
104897                         var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
104898                         if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
104899                             return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry };
104900                         }
104901                     }
104902                 }
104903                 return { moduleFileToTry: moduleFileToTry };
104904             }
104905             function getExtensionlessFileName(path) {
104906                 // We still have a file name - remove the extension
104907                 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
104908                 // If the file is /index, it can be imported by its directory name
104909                 // IFF there is not _also_ a file by the same name
104910                 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
104911                     return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
104912                 }
104913                 return fullModulePathWithoutExtension;
104914             }
104915         }
104916         function tryGetAnyFileFromPath(host, path) {
104917             if (!host.fileExists)
104918                 return;
104919             // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
104920             var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
104921             for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
104922                 var e = extensions_3[_i];
104923                 var fullPath = path + e;
104924                 if (host.fileExists(fullPath)) {
104925                     return fullPath;
104926                 }
104927             }
104928         }
104929         function getNodeModulePathParts(fullPath) {
104930             // If fullPath can't be valid module file within node_modules, returns undefined.
104931             // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
104932             // Returns indices:                       ^            ^                                                      ^             ^
104933             var topLevelNodeModulesIndex = 0;
104934             var topLevelPackageNameIndex = 0;
104935             var packageRootIndex = 0;
104936             var fileNameIndex = 0;
104937             var States;
104938             (function (States) {
104939                 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
104940                 States[States["NodeModules"] = 1] = "NodeModules";
104941                 States[States["Scope"] = 2] = "Scope";
104942                 States[States["PackageContent"] = 3] = "PackageContent";
104943             })(States || (States = {}));
104944             var partStart = 0;
104945             var partEnd = 0;
104946             var state = 0 /* BeforeNodeModules */;
104947             while (partEnd >= 0) {
104948                 partStart = partEnd;
104949                 partEnd = fullPath.indexOf("/", partStart + 1);
104950                 switch (state) {
104951                     case 0 /* BeforeNodeModules */:
104952                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
104953                             topLevelNodeModulesIndex = partStart;
104954                             topLevelPackageNameIndex = partEnd;
104955                             state = 1 /* NodeModules */;
104956                         }
104957                         break;
104958                     case 1 /* NodeModules */:
104959                     case 2 /* Scope */:
104960                         if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
104961                             state = 2 /* Scope */;
104962                         }
104963                         else {
104964                             packageRootIndex = partEnd;
104965                             state = 3 /* PackageContent */;
104966                         }
104967                         break;
104968                     case 3 /* PackageContent */:
104969                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
104970                             state = 1 /* NodeModules */;
104971                         }
104972                         else {
104973                             state = 3 /* PackageContent */;
104974                         }
104975                         break;
104976                 }
104977             }
104978             fileNameIndex = partStart;
104979             return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
104980         }
104981         function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
104982             return ts.firstDefined(rootDirs, function (rootDir) {
104983                 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
104984                 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
104985             });
104986         }
104987         function removeExtensionAndIndexPostFix(fileName, ending, options) {
104988             if (ts.fileExtensionIs(fileName, ".json" /* Json */))
104989                 return fileName;
104990             var noExtension = ts.removeFileExtension(fileName);
104991             switch (ending) {
104992                 case 0 /* Minimal */:
104993                     return ts.removeSuffix(noExtension, "/index");
104994                 case 1 /* Index */:
104995                     return noExtension;
104996                 case 2 /* JsExtension */:
104997                     return noExtension + getJSExtensionForFile(fileName, options);
104998                 default:
104999                     return ts.Debug.assertNever(ending);
105000             }
105001         }
105002         function getJSExtensionForFile(fileName, options) {
105003             var ext = ts.extensionFromPath(fileName);
105004             switch (ext) {
105005                 case ".ts" /* Ts */:
105006                 case ".d.ts" /* Dts */:
105007                     return ".js" /* Js */;
105008                 case ".tsx" /* Tsx */:
105009                     return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
105010                 case ".js" /* Js */:
105011                 case ".jsx" /* Jsx */:
105012                 case ".json" /* Json */:
105013                     return ext;
105014                 case ".tsbuildinfo" /* TsBuildInfo */:
105015                     return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
105016                 default:
105017                     return ts.Debug.assertNever(ext);
105018             }
105019         }
105020         function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
105021             var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
105022             return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
105023         }
105024         function isPathRelativeToParent(path) {
105025             return ts.startsWith(path, "..");
105026         }
105027     })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
105028 })(ts || (ts = {}));
105029 /*@internal*/
105030 var ts;
105031 (function (ts) {
105032     var sysFormatDiagnosticsHost = ts.sys ? {
105033         getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
105034         getNewLine: function () { return ts.sys.newLine; },
105035         getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
105036     } : undefined; // TODO: GH#18217
105037     /**
105038      * Create a function that reports error by writing to the system and handles the formating of the diagnostic
105039      */
105040     function createDiagnosticReporter(system, pretty) {
105041         var host = system === ts.sys ? sysFormatDiagnosticsHost : {
105042             getCurrentDirectory: function () { return system.getCurrentDirectory(); },
105043             getNewLine: function () { return system.newLine; },
105044             getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
105045         };
105046         if (!pretty) {
105047             return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
105048         }
105049         var diagnostics = new Array(1);
105050         return function (diagnostic) {
105051             diagnostics[0] = diagnostic;
105052             system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
105053             diagnostics[0] = undefined; // TODO: GH#18217
105054         };
105055     }
105056     ts.createDiagnosticReporter = createDiagnosticReporter;
105057     /**
105058      * @returns Whether the screen was cleared.
105059      */
105060     function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
105061         if (system.clearScreen &&
105062             !options.preserveWatchOutput &&
105063             !options.extendedDiagnostics &&
105064             !options.diagnostics &&
105065             ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
105066             system.clearScreen();
105067             return true;
105068         }
105069         return false;
105070     }
105071     ts.screenStartingMessageCodes = [
105072         ts.Diagnostics.Starting_compilation_in_watch_mode.code,
105073         ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
105074     ];
105075     function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
105076         return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
105077             ? newLine + newLine
105078             : newLine;
105079     }
105080     /**
105081      * Get locale specific time based on whether we are in test mode
105082      */
105083     function getLocaleTimeString(system) {
105084         return !system.now ?
105085             new Date().toLocaleTimeString() :
105086             system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
105087     }
105088     ts.getLocaleTimeString = getLocaleTimeString;
105089     /**
105090      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
105091      */
105092     function createWatchStatusReporter(system, pretty) {
105093         return pretty ?
105094             function (diagnostic, newLine, options) {
105095                 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
105096                 var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] ";
105097                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
105098                 system.write(output);
105099             } :
105100             function (diagnostic, newLine, options) {
105101                 var output = "";
105102                 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
105103                     output += newLine;
105104                 }
105105                 output += getLocaleTimeString(system) + " - ";
105106                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
105107                 system.write(output);
105108             };
105109     }
105110     ts.createWatchStatusReporter = createWatchStatusReporter;
105111     /** Parses config file using System interface */
105112     function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) {
105113         var host = system;
105114         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
105115         var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
105116         host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
105117         return result;
105118     }
105119     ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
105120     function getErrorCountForSummary(diagnostics) {
105121         return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
105122     }
105123     ts.getErrorCountForSummary = getErrorCountForSummary;
105124     function getWatchErrorSummaryDiagnosticMessage(errorCount) {
105125         return errorCount === 1 ?
105126             ts.Diagnostics.Found_1_error_Watching_for_file_changes :
105127             ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
105128     }
105129     ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
105130     function getErrorSummaryText(errorCount, newLine) {
105131         if (errorCount === 0)
105132             return "";
105133         var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
105134         return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
105135     }
105136     ts.getErrorSummaryText = getErrorSummaryText;
105137     function listFiles(program, writeFileName) {
105138         if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
105139             ts.forEach(program.getSourceFiles(), function (file) {
105140                 writeFileName(file.fileName);
105141             });
105142         }
105143     }
105144     ts.listFiles = listFiles;
105145     /**
105146      * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
105147      */
105148     function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105149         var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
105150         // First get and report any syntactic errors.
105151         var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
105152         var configFileParsingDiagnosticsLength = allDiagnostics.length;
105153         ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105154         // If we didn't have any syntactic errors, then also try getting the global and
105155         // semantic errors.
105156         if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105157             ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
105158             if (!isListFilesOnly) {
105159                 ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
105160                 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105161                     ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105162                 }
105163             }
105164         }
105165         // Emit and report any errors we ran into.
105166         var emitResult = isListFilesOnly
105167             ? { emitSkipped: true, diagnostics: ts.emptyArray }
105168             : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
105169         var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
105170         ts.addRange(allDiagnostics, emitDiagnostics);
105171         var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
105172         diagnostics.forEach(reportDiagnostic);
105173         if (writeFileName) {
105174             var currentDir_1 = program.getCurrentDirectory();
105175             ts.forEach(emittedFiles, function (file) {
105176                 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
105177                 writeFileName("TSFILE: " + filepath);
105178             });
105179             listFiles(program, writeFileName);
105180         }
105181         if (reportSummary) {
105182             reportSummary(getErrorCountForSummary(diagnostics));
105183         }
105184         return {
105185             emitResult: emitResult,
105186             diagnostics: diagnostics,
105187         };
105188     }
105189     ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
105190     function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105191         var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
105192         if (emitResult.emitSkipped && diagnostics.length > 0) {
105193             // If the emitter didn't emit anything, then pass that value along.
105194             return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
105195         }
105196         else if (diagnostics.length > 0) {
105197             // The emitter emitted something, inform the caller if that happened in the presence
105198             // of diagnostics or not.
105199             return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
105200         }
105201         return ts.ExitStatus.Success;
105202     }
105203     ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
105204     ts.noopFileWatcher = { close: ts.noop };
105205     function createWatchHost(system, reportWatchStatus) {
105206         if (system === void 0) { system = ts.sys; }
105207         var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
105208         return {
105209             onWatchStatusChange: onWatchStatusChange,
105210             watchFile: ts.maybeBind(system, system.watchFile) || (function () { return ts.noopFileWatcher; }),
105211             watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return ts.noopFileWatcher; }),
105212             setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
105213             clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
105214         };
105215     }
105216     ts.createWatchHost = createWatchHost;
105217     ts.WatchType = {
105218         ConfigFile: "Config file",
105219         SourceFile: "Source file",
105220         MissingFile: "Missing file",
105221         WildcardDirectory: "Wild card directory",
105222         FailedLookupLocations: "Failed Lookup Locations",
105223         TypeRoots: "Type roots"
105224     };
105225     function createWatchFactory(host, options) {
105226         var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
105227         var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
105228         var result = ts.getWatchFactory(watchLogLevel, writeLog);
105229         result.writeLog = writeLog;
105230         return result;
105231     }
105232     ts.createWatchFactory = createWatchFactory;
105233     function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
105234         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
105235         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105236         var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
105237         return {
105238             getSourceFile: function (fileName, languageVersion, onError) {
105239                 var text;
105240                 try {
105241                     ts.performance.mark("beforeIORead");
105242                     text = host.readFile(fileName, getCompilerOptions().charset);
105243                     ts.performance.mark("afterIORead");
105244                     ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
105245                 }
105246                 catch (e) {
105247                     if (onError) {
105248                         onError(e.message);
105249                     }
105250                     text = "";
105251                 }
105252                 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
105253             },
105254             getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
105255             getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
105256             writeFile: writeFile,
105257             getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
105258             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
105259             getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
105260             getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
105261             fileExists: function (f) { return host.fileExists(f); },
105262             readFile: function (f) { return host.readFile(f); },
105263             trace: ts.maybeBind(host, host.trace),
105264             directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
105265             getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
105266             realpath: ts.maybeBind(host, host.realpath),
105267             getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
105268             createHash: ts.maybeBind(host, host.createHash),
105269             readDirectory: ts.maybeBind(host, host.readDirectory),
105270         };
105271         function writeFile(fileName, text, writeByteOrderMark, onError) {
105272             try {
105273                 ts.performance.mark("beforeIOWrite");
105274                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
105275                 // the host.writeFile will do its own directory creation and
105276                 // the ensureDirectoriesExist call will always be redundant.
105277                 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); });
105278                 ts.performance.mark("afterIOWrite");
105279                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
105280             }
105281             catch (e) {
105282                 if (onError) {
105283                     onError(e.message);
105284                 }
105285             }
105286         }
105287     }
105288     ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
105289     function setGetSourceFileAsHashVersioned(compilerHost, host) {
105290         var originalGetSourceFile = compilerHost.getSourceFile;
105291         var computeHash = host.createHash || ts.generateDjb2Hash;
105292         compilerHost.getSourceFile = function () {
105293             var args = [];
105294             for (var _i = 0; _i < arguments.length; _i++) {
105295                 args[_i] = arguments[_i];
105296             }
105297             var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
105298             if (result) {
105299                 result.version = computeHash.call(host, result.text);
105300             }
105301             return result;
105302         };
105303     }
105304     ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
105305     /**
105306      * Creates the watch compiler host that can be extended with config file or root file names and options host
105307      */
105308     function createProgramHost(system, createProgram) {
105309         var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
105310         return {
105311             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
105312             getNewLine: function () { return system.newLine; },
105313             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
105314             getDefaultLibLocation: getDefaultLibLocation,
105315             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
105316             fileExists: function (path) { return system.fileExists(path); },
105317             readFile: function (path, encoding) { return system.readFile(path, encoding); },
105318             directoryExists: function (path) { return system.directoryExists(path); },
105319             getDirectories: function (path) { return system.getDirectories(path); },
105320             readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
105321             realpath: ts.maybeBind(system, system.realpath),
105322             getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
105323             trace: function (s) { return system.write(s + system.newLine); },
105324             createDirectory: function (path) { return system.createDirectory(path); },
105325             writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
105326             createHash: ts.maybeBind(system, system.createHash),
105327             createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
105328         };
105329     }
105330     ts.createProgramHost = createProgramHost;
105331     /**
105332      * Creates the watch compiler host that can be extended with config file or root file names and options host
105333      */
105334     function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
105335         if (system === void 0) { system = ts.sys; }
105336         var writeFileName = function (s) { return system.write(s + system.newLine); };
105337         var result = createProgramHost(system, createProgram);
105338         ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
105339         result.afterProgramCreate = function (builderProgram) {
105340             var compilerOptions = builderProgram.getCompilerOptions();
105341             var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
105342             emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
105343         };
105344         return result;
105345     }
105346     /**
105347      * Report error and exit
105348      */
105349     function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
105350         reportDiagnostic(diagnostic);
105351         system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
105352     }
105353     /**
105354      * Creates the watch compiler host from system for config file in watch mode
105355      */
105356     function createWatchCompilerHostOfConfigFile(_a) {
105357         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;
105358         var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
105359         var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
105360         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
105361         host.configFileName = configFileName;
105362         host.optionsToExtend = optionsToExtend;
105363         host.watchOptionsToExtend = watchOptionsToExtend;
105364         host.extraFileExtensions = extraFileExtensions;
105365         return host;
105366     }
105367     ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
105368     /**
105369      * Creates the watch compiler host from system for compiling root files and options in watch mode
105370      */
105371     function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
105372         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;
105373         var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
105374         host.rootFiles = rootFiles;
105375         host.options = options;
105376         host.watchOptions = watchOptions;
105377         host.projectReferences = projectReferences;
105378         return host;
105379     }
105380     ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
105381     function performIncrementalCompilation(input) {
105382         var system = input.system || ts.sys;
105383         var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
105384         var builderProgram = ts.createIncrementalProgram(input);
105385         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);
105386         if (input.afterProgramEmitAndDiagnostics)
105387             input.afterProgramEmitAndDiagnostics(builderProgram);
105388         return exitStatus;
105389     }
105390     ts.performIncrementalCompilation = performIncrementalCompilation;
105391 })(ts || (ts = {}));
105392 var ts;
105393 (function (ts) {
105394     function readBuilderProgram(compilerOptions, host) {
105395         if (compilerOptions.out || compilerOptions.outFile)
105396             return undefined;
105397         var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
105398         if (!buildInfoPath)
105399             return undefined;
105400         var content = host.readFile(buildInfoPath);
105401         if (!content)
105402             return undefined;
105403         var buildInfo = ts.getBuildInfo(content);
105404         if (buildInfo.version !== ts.version)
105405             return undefined;
105406         if (!buildInfo.program)
105407             return undefined;
105408         return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
105409     }
105410     ts.readBuilderProgram = readBuilderProgram;
105411     function createIncrementalCompilerHost(options, system) {
105412         if (system === void 0) { system = ts.sys; }
105413         var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
105414         host.createHash = ts.maybeBind(system, system.createHash);
105415         ts.setGetSourceFileAsHashVersioned(host, system);
105416         ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
105417         return host;
105418     }
105419     ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
105420     function createIncrementalProgram(_a) {
105421         var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
105422         host = host || createIncrementalCompilerHost(options);
105423         createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
105424         var oldProgram = readBuilderProgram(options, host);
105425         return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
105426     }
105427     ts.createIncrementalProgram = createIncrementalProgram;
105428     function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
105429         if (ts.isArray(rootFilesOrConfigFileName)) {
105430             return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
105431                 rootFiles: rootFilesOrConfigFileName,
105432                 options: options,
105433                 watchOptions: watchOptionsOrExtraFileExtensions,
105434                 projectReferences: projectReferencesOrWatchOptionsToExtend,
105435                 system: system,
105436                 createProgram: createProgram,
105437                 reportDiagnostic: reportDiagnostic,
105438                 reportWatchStatus: reportWatchStatus,
105439             });
105440         }
105441         else {
105442             return ts.createWatchCompilerHostOfConfigFile({
105443                 configFileName: rootFilesOrConfigFileName,
105444                 optionsToExtend: options,
105445                 watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
105446                 extraFileExtensions: watchOptionsOrExtraFileExtensions,
105447                 system: system,
105448                 createProgram: createProgram,
105449                 reportDiagnostic: reportDiagnostic,
105450                 reportWatchStatus: reportWatchStatus,
105451             });
105452         }
105453     }
105454     ts.createWatchCompilerHost = createWatchCompilerHost;
105455     function createWatchProgram(host) {
105456         var builderProgram;
105457         var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
105458         var missingFilesMap; // Map of file watchers for the missing files
105459         var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
105460         var timerToUpdateProgram; // timer callback to recompile the program
105461         var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info
105462         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
105463         var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
105464         var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed
105465         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105466         var currentDirectory = host.getCurrentDirectory();
105467         var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
105468         var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
105469         var configFileSpecs;
105470         var configFileParsingDiagnostics;
105471         var canConfigFileJsonReportNoInputFiles = false;
105472         var hasChangedConfigFileParsingErrors = false;
105473         var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
105474         var directoryStructureHost = cachedDirectoryStructureHost || host;
105475         var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
105476         // From tsc we want to get already parsed result and hence check for rootFileNames
105477         var newLine = updateNewLine();
105478         if (configFileName && host.configFileParsingResult) {
105479             setConfigFileParsingResult(host.configFileParsingResult);
105480             newLine = updateNewLine();
105481         }
105482         reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
105483         if (configFileName && !host.configFileParsingResult) {
105484             newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105485             ts.Debug.assert(!rootFileNames);
105486             parseConfigFile();
105487             newLine = updateNewLine();
105488         }
105489         var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
105490         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
105491         writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
105492         var configFileWatcher;
105493         if (configFileName) {
105494             configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
105495         }
105496         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
105497         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
105498         // Members for CompilerHost
105499         var getNewSourceFile = compilerHost.getSourceFile;
105500         compilerHost.getSourceFile = function (fileName) {
105501             var args = [];
105502             for (var _i = 1; _i < arguments.length; _i++) {
105503                 args[_i - 1] = arguments[_i];
105504             }
105505             return getVersionedSourceFileByPath.apply(void 0, __spreadArrays([fileName, toPath(fileName)], args));
105506         };
105507         compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
105508         compilerHost.getNewLine = function () { return newLine; };
105509         compilerHost.fileExists = fileExists;
105510         compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
105511         // Members for ResolutionCacheHost
105512         compilerHost.toPath = toPath;
105513         compilerHost.getCompilationSettings = function () { return compilerOptions; };
105514         compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
105515         compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
105516         compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
105517         compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
105518         compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
105519         compilerHost.onChangedAutomaticTypeDirectiveNames = function () {
105520             hasChangedAutomaticTypeDirectiveNames = true;
105521             scheduleProgramUpdate();
105522         };
105523         compilerHost.fileIsOpen = ts.returnFalse;
105524         compilerHost.getCurrentProgram = getCurrentProgram;
105525         compilerHost.writeLog = writeLog;
105526         // Cache for the module resolution
105527         var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
105528             ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
105529             currentDirectory, 
105530         /*logChangesWhenResolvingModule*/ false);
105531         // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
105532         compilerHost.resolveModuleNames = host.resolveModuleNames ?
105533             (function () {
105534                 var args = [];
105535                 for (var _i = 0; _i < arguments.length; _i++) {
105536                     args[_i] = arguments[_i];
105537                 }
105538                 return host.resolveModuleNames.apply(host, args);
105539             }) :
105540             (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
105541         compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
105542             (function () {
105543                 var args = [];
105544                 for (var _i = 0; _i < arguments.length; _i++) {
105545                     args[_i] = arguments[_i];
105546                 }
105547                 return host.resolveTypeReferenceDirectives.apply(host, args);
105548             }) :
105549             (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
105550         var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
105551         builderProgram = readBuilderProgram(compilerOptions, compilerHost);
105552         synchronizeProgram();
105553         // Update the wild card directory watch
105554         watchConfigFileWildCardDirectories();
105555         return configFileName ?
105556             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
105557             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
105558         function close() {
105559             resolutionCache.clear();
105560             ts.clearMap(sourceFilesCache, function (value) {
105561                 if (value && value.fileWatcher) {
105562                     value.fileWatcher.close();
105563                     value.fileWatcher = undefined;
105564                 }
105565             });
105566             if (configFileWatcher) {
105567                 configFileWatcher.close();
105568                 configFileWatcher = undefined;
105569             }
105570             if (watchedWildcardDirectories) {
105571                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
105572                 watchedWildcardDirectories = undefined;
105573             }
105574             if (missingFilesMap) {
105575                 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
105576                 missingFilesMap = undefined;
105577             }
105578         }
105579         function getCurrentBuilderProgram() {
105580             return builderProgram;
105581         }
105582         function getCurrentProgram() {
105583             return builderProgram && builderProgram.getProgramOrUndefined();
105584         }
105585         function synchronizeProgram() {
105586             writeLog("Synchronizing program");
105587             var program = getCurrentBuilderProgram();
105588             if (hasChangedCompilerOptions) {
105589                 newLine = updateNewLine();
105590                 if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
105591                     resolutionCache.clear();
105592                 }
105593             }
105594             // All resolutions are invalid if user provided resolutions
105595             var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
105596             if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
105597                 if (hasChangedConfigFileParsingErrors) {
105598                     builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105599                     hasChangedConfigFileParsingErrors = false;
105600                 }
105601             }
105602             else {
105603                 createNewProgram(hasInvalidatedResolution);
105604             }
105605             if (host.afterProgramCreate && program !== builderProgram) {
105606                 host.afterProgramCreate(builderProgram);
105607             }
105608             return builderProgram;
105609         }
105610         function createNewProgram(hasInvalidatedResolution) {
105611             // Compile the program
105612             writeLog("CreatingProgramWith::");
105613             writeLog("  roots: " + JSON.stringify(rootFileNames));
105614             writeLog("  options: " + JSON.stringify(compilerOptions));
105615             var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
105616             hasChangedCompilerOptions = false;
105617             hasChangedConfigFileParsingErrors = false;
105618             resolutionCache.startCachingPerDirectoryResolution();
105619             compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
105620             compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
105621             hasChangedAutomaticTypeDirectiveNames = false;
105622             builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105623             resolutionCache.finishCachingPerDirectoryResolution();
105624             // Update watches
105625             ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath);
105626             if (needsUpdateInTypeRootWatch) {
105627                 resolutionCache.updateTypeRootsWatch();
105628             }
105629             if (missingFilePathsRequestedForRelease) {
105630                 // These are the paths that program creater told us as not in use any more but were missing on the disk.
105631                 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
105632                 // if there is already watcher for it (for missing files)
105633                 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
105634                 // so that at later time we have correct result of their presence
105635                 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
105636                     var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
105637                     if (!missingFilesMap.has(missingFilePath)) {
105638                         sourceFilesCache.delete(missingFilePath);
105639                     }
105640                 }
105641                 missingFilePathsRequestedForRelease = undefined;
105642             }
105643         }
105644         function updateRootFileNames(files) {
105645             ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
105646             rootFileNames = files;
105647             scheduleProgramUpdate();
105648         }
105649         function updateNewLine() {
105650             return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105651         }
105652         function toPath(fileName) {
105653             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
105654         }
105655         function isFileMissingOnHost(hostSourceFile) {
105656             return typeof hostSourceFile === "boolean";
105657         }
105658         function isFilePresenceUnknownOnHost(hostSourceFile) {
105659             return typeof hostSourceFile.version === "boolean";
105660         }
105661         function fileExists(fileName) {
105662             var path = toPath(fileName);
105663             // If file is missing on host from cache, we can definitely say file doesnt exist
105664             // otherwise we need to ensure from the disk
105665             if (isFileMissingOnHost(sourceFilesCache.get(path))) {
105666                 return false;
105667             }
105668             return directoryStructureHost.fileExists(fileName);
105669         }
105670         function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
105671             var hostSourceFile = sourceFilesCache.get(path);
105672             // No source file on the host
105673             if (isFileMissingOnHost(hostSourceFile)) {
105674                 return undefined;
105675             }
105676             // Create new source file if requested or the versions dont match
105677             if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
105678                 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
105679                 if (hostSourceFile) {
105680                     if (sourceFile) {
105681                         // Set the source file and create file watcher now that file was present on the disk
105682                         hostSourceFile.sourceFile = sourceFile;
105683                         hostSourceFile.version = sourceFile.version;
105684                         if (!hostSourceFile.fileWatcher) {
105685                             hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105686                         }
105687                     }
105688                     else {
105689                         // There is no source file on host any more, close the watch, missing file paths will track it
105690                         if (hostSourceFile.fileWatcher) {
105691                             hostSourceFile.fileWatcher.close();
105692                         }
105693                         sourceFilesCache.set(path, false);
105694                     }
105695                 }
105696                 else {
105697                     if (sourceFile) {
105698                         var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105699                         sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
105700                     }
105701                     else {
105702                         sourceFilesCache.set(path, false);
105703                     }
105704                 }
105705                 return sourceFile;
105706             }
105707             return hostSourceFile.sourceFile;
105708         }
105709         function nextSourceFileVersion(path) {
105710             var hostSourceFile = sourceFilesCache.get(path);
105711             if (hostSourceFile !== undefined) {
105712                 if (isFileMissingOnHost(hostSourceFile)) {
105713                     // The next version, lets set it as presence unknown file
105714                     sourceFilesCache.set(path, { version: false });
105715                 }
105716                 else {
105717                     hostSourceFile.version = false;
105718                 }
105719             }
105720         }
105721         function getSourceVersion(path) {
105722             var hostSourceFile = sourceFilesCache.get(path);
105723             return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
105724         }
105725         function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
105726             var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
105727             // If this is the source file thats in the cache and new program doesnt need it,
105728             // remove the cached entry.
105729             // Note we arent deleting entry if file became missing in new program or
105730             // there was version update and new source file was created.
105731             if (hostSourceFileInfo !== undefined) {
105732                 // record the missing file paths so they can be removed later if watchers arent tracking them
105733                 if (isFileMissingOnHost(hostSourceFileInfo)) {
105734                     (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
105735                 }
105736                 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
105737                     if (hostSourceFileInfo.fileWatcher) {
105738                         hostSourceFileInfo.fileWatcher.close();
105739                     }
105740                     sourceFilesCache.delete(oldSourceFile.resolvedPath);
105741                     if (!hasSourceFileByPath) {
105742                         resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
105743                     }
105744                 }
105745             }
105746         }
105747         function reportWatchDiagnostic(message) {
105748             if (host.onWatchStatusChange) {
105749                 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
105750             }
105751         }
105752         // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
105753         // operations (such as saving all modified files in an editor) a chance to complete before we kick
105754         // off a new compilation.
105755         function scheduleProgramUpdate() {
105756             if (!host.setTimeout || !host.clearTimeout) {
105757                 return;
105758             }
105759             if (timerToUpdateProgram) {
105760                 host.clearTimeout(timerToUpdateProgram);
105761             }
105762             writeLog("Scheduling update");
105763             timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250);
105764         }
105765         function scheduleProgramReload() {
105766             ts.Debug.assert(!!configFileName);
105767             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
105768             scheduleProgramUpdate();
105769         }
105770         function updateProgramWithWatchStatus() {
105771             timerToUpdateProgram = undefined;
105772             reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
105773             updateProgram();
105774         }
105775         function updateProgram() {
105776             switch (reloadLevel) {
105777                 case ts.ConfigFileProgramReloadLevel.Partial:
105778                     ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
105779                     reloadFileNamesFromConfigFile();
105780                     break;
105781                 case ts.ConfigFileProgramReloadLevel.Full:
105782                     ts.perfLogger.logStartUpdateProgram("FullConfigReload");
105783                     reloadConfigFile();
105784                     break;
105785                 default:
105786                     ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
105787                     synchronizeProgram();
105788                     break;
105789             }
105790             ts.perfLogger.logStopUpdateProgram("Done");
105791             return getCurrentBuilderProgram();
105792         }
105793         function reloadFileNamesFromConfigFile() {
105794             writeLog("Reloading new file names and options");
105795             var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost);
105796             if (ts.updateErrorForNoInputFiles(result, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
105797                 hasChangedConfigFileParsingErrors = true;
105798             }
105799             rootFileNames = result.fileNames;
105800             // Update the program
105801             synchronizeProgram();
105802         }
105803         function reloadConfigFile() {
105804             writeLog("Reloading config file: " + configFileName);
105805             reloadLevel = ts.ConfigFileProgramReloadLevel.None;
105806             if (cachedDirectoryStructureHost) {
105807                 cachedDirectoryStructureHost.clearCache();
105808             }
105809             parseConfigFile();
105810             hasChangedCompilerOptions = true;
105811             synchronizeProgram();
105812             // Update the wild card directory watch
105813             watchConfigFileWildCardDirectories();
105814         }
105815         function parseConfigFile() {
105816             setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
105817         }
105818         function setConfigFileParsingResult(configFileParseResult) {
105819             rootFileNames = configFileParseResult.fileNames;
105820             compilerOptions = configFileParseResult.options;
105821             watchOptions = configFileParseResult.watchOptions;
105822             configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
105823             projectReferences = configFileParseResult.projectReferences;
105824             configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
105825             canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw);
105826             hasChangedConfigFileParsingErrors = true;
105827         }
105828         function onSourceFileChange(fileName, eventKind, path) {
105829             updateCachedSystemWithFile(fileName, path, eventKind);
105830             // Update the source file cache
105831             if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
105832                 resolutionCache.invalidateResolutionOfFile(path);
105833             }
105834             resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
105835             nextSourceFileVersion(path);
105836             // Update the program
105837             scheduleProgramUpdate();
105838         }
105839         function updateCachedSystemWithFile(fileName, path, eventKind) {
105840             if (cachedDirectoryStructureHost) {
105841                 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
105842             }
105843         }
105844         function watchMissingFilePath(missingFilePath) {
105845             return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, missingFilePath, ts.WatchType.MissingFile);
105846         }
105847         function onMissingFileChange(fileName, eventKind, missingFilePath) {
105848             updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
105849             if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
105850                 missingFilesMap.get(missingFilePath).close();
105851                 missingFilesMap.delete(missingFilePath);
105852                 // Delete the entry in the source files cache so that new source file is created
105853                 nextSourceFileVersion(missingFilePath);
105854                 // When a missing file is created, we should update the graph.
105855                 scheduleProgramUpdate();
105856             }
105857         }
105858         function watchConfigFileWildCardDirectories() {
105859             if (configFileSpecs) {
105860                 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory);
105861             }
105862             else if (watchedWildcardDirectories) {
105863                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
105864             }
105865         }
105866         function watchWildcardDirectory(directory, flags) {
105867             return watchDirectory(host, directory, function (fileOrDirectory) {
105868                 ts.Debug.assert(!!configFileName);
105869                 var fileOrDirectoryPath = toPath(fileOrDirectory);
105870                 // Since the file existence changed, update the sourceFiles cache
105871                 if (cachedDirectoryStructureHost) {
105872                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
105873                 }
105874                 nextSourceFileVersion(fileOrDirectoryPath);
105875                 fileOrDirectoryPath = ts.removeIgnoredPath(fileOrDirectoryPath);
105876                 if (!fileOrDirectoryPath)
105877                     return;
105878                 // If the the added or created file or directory is not supported file name, ignore the file
105879                 // But when watched directory is added/removed, we need to reload the file list
105880                 if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) {
105881                     writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
105882                     return;
105883                 }
105884                 // Reload is pending, do the reload
105885                 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
105886                     reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
105887                     // Schedule Update the program
105888                     scheduleProgramUpdate();
105889                 }
105890             }, flags, watchOptions, ts.WatchType.WildcardDirectory);
105891         }
105892     }
105893     ts.createWatchProgram = createWatchProgram;
105894 })(ts || (ts = {}));
105895 /*@internal*/
105896 var ts;
105897 (function (ts) {
105898     var UpToDateStatusType;
105899     (function (UpToDateStatusType) {
105900         UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
105901         UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
105902         /**
105903          * The project appears out of date because its upstream inputs are newer than its outputs,
105904          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
105905          * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
105906          */
105907         UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
105908         /**
105909          * The project appears out of date because its upstream inputs are newer than its outputs,
105910          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
105911          * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
105912          */
105913         UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
105914         UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
105915         UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
105916         UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
105917         UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
105918         UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
105919         UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
105920         UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
105921         /**
105922          * Projects with no outputs (i.e. "solution" files)
105923          */
105924         UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
105925     })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
105926     function resolveConfigFileProjectName(project) {
105927         if (ts.fileExtensionIs(project, ".json" /* Json */)) {
105928             return project;
105929         }
105930         return ts.combinePaths(project, "tsconfig.json");
105931     }
105932     ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
105933 })(ts || (ts = {}));
105934 var ts;
105935 (function (ts) {
105936     var minimumDate = new Date(-8640000000000000);
105937     var maximumDate = new Date(8640000000000000);
105938     var BuildResultFlags;
105939     (function (BuildResultFlags) {
105940         BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
105941         /**
105942          * No errors of any kind occurred during build
105943          */
105944         BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
105945         /**
105946          * None of the .d.ts files emitted by this build were
105947          * different from the existing files on disk
105948          */
105949         BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
105950         BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
105951         BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
105952         BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
105953         BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
105954         BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
105955         BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
105956     })(BuildResultFlags || (BuildResultFlags = {}));
105957     function createConfigFileMap() {
105958         return ts.createMap();
105959     }
105960     function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
105961         var existingValue = configFileMap.get(resolved);
105962         var newValue;
105963         if (!existingValue) {
105964             newValue = createT();
105965             configFileMap.set(resolved, newValue);
105966         }
105967         return existingValue || newValue;
105968     }
105969     function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
105970         return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
105971     }
105972     function newer(date1, date2) {
105973         return date2 > date1 ? date2 : date1;
105974     }
105975     function isDeclarationFile(fileName) {
105976         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
105977     }
105978     /*@internal*/
105979     function isCircularBuildOrder(buildOrder) {
105980         return !!buildOrder && !!buildOrder.buildOrder;
105981     }
105982     ts.isCircularBuildOrder = isCircularBuildOrder;
105983     /*@internal*/
105984     function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
105985         return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
105986     }
105987     ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
105988     /**
105989      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
105990      */
105991     function createBuilderStatusReporter(system, pretty) {
105992         return function (diagnostic) {
105993             var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - ";
105994             output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
105995             system.write(output);
105996         };
105997     }
105998     ts.createBuilderStatusReporter = createBuilderStatusReporter;
105999     function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
106000         var host = ts.createProgramHost(system, createProgram);
106001         host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
106002         host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
106003         host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
106004         host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
106005         host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
106006         host.now = ts.maybeBind(system, system.now); // For testing
106007         return host;
106008     }
106009     function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
106010         if (system === void 0) { system = ts.sys; }
106011         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
106012         host.reportErrorSummary = reportErrorSummary;
106013         return host;
106014     }
106015     ts.createSolutionBuilderHost = createSolutionBuilderHost;
106016     function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
106017         if (system === void 0) { system = ts.sys; }
106018         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
106019         var watchHost = ts.createWatchHost(system, reportWatchStatus);
106020         ts.copyProperties(host, watchHost);
106021         return host;
106022     }
106023     ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
106024     function getCompilerOptionsOfBuildOptions(buildOptions) {
106025         var result = {};
106026         ts.commonOptionsWithBuild.forEach(function (option) {
106027             if (ts.hasProperty(buildOptions, option.name))
106028                 result[option.name] = buildOptions[option.name];
106029         });
106030         return result;
106031     }
106032     function createSolutionBuilder(host, rootNames, defaultOptions) {
106033         return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
106034     }
106035     ts.createSolutionBuilder = createSolutionBuilder;
106036     function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
106037         return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
106038     }
106039     ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
106040     function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
106041         var host = hostOrHostWithWatch;
106042         var hostWithWatch = hostOrHostWithWatch;
106043         var currentDirectory = host.getCurrentDirectory();
106044         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
106045         // State of the solution
106046         var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
106047         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
106048         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
106049         compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
106050         compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
106051         compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
106052         var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
106053         if (!compilerHost.resolveModuleNames) {
106054             var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; };
106055             compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) {
106056                 return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
106057             };
106058         }
106059         var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
106060         var state = {
106061             host: host,
106062             hostWithWatch: hostWithWatch,
106063             currentDirectory: currentDirectory,
106064             getCanonicalFileName: getCanonicalFileName,
106065             parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
106066             writeFileName: host.trace ? function (s) { return host.trace(s); } : undefined,
106067             // State of solution
106068             options: options,
106069             baseCompilerOptions: baseCompilerOptions,
106070             rootNames: rootNames,
106071             baseWatchOptions: baseWatchOptions,
106072             resolvedConfigFilePaths: ts.createMap(),
106073             configFileCache: createConfigFileMap(),
106074             projectStatus: createConfigFileMap(),
106075             buildInfoChecked: createConfigFileMap(),
106076             extendedConfigCache: ts.createMap(),
106077             builderPrograms: createConfigFileMap(),
106078             diagnostics: createConfigFileMap(),
106079             projectPendingBuild: createConfigFileMap(),
106080             projectErrorsReported: createConfigFileMap(),
106081             compilerHost: compilerHost,
106082             moduleResolutionCache: moduleResolutionCache,
106083             // Mutable state
106084             buildOrder: undefined,
106085             readFileWithCache: function (f) { return host.readFile(f); },
106086             projectCompilerOptions: baseCompilerOptions,
106087             cache: undefined,
106088             allProjectBuildPending: true,
106089             needsSummary: true,
106090             watchAllProjectsPending: watch,
106091             currentInvalidatedProject: undefined,
106092             // Watch state
106093             watch: watch,
106094             allWatchedWildcardDirectories: createConfigFileMap(),
106095             allWatchedInputFiles: createConfigFileMap(),
106096             allWatchedConfigFiles: createConfigFileMap(),
106097             timerToBuildInvalidatedProject: undefined,
106098             reportFileChangeDetected: false,
106099             watchFile: watchFile,
106100             watchFilePath: watchFilePath,
106101             watchDirectory: watchDirectory,
106102             writeLog: writeLog,
106103         };
106104         return state;
106105     }
106106     function toPath(state, fileName) {
106107         return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
106108     }
106109     function toResolvedConfigFilePath(state, fileName) {
106110         var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
106111         var path = resolvedConfigFilePaths.get(fileName);
106112         if (path !== undefined)
106113             return path;
106114         var resolvedPath = toPath(state, fileName);
106115         resolvedConfigFilePaths.set(fileName, resolvedPath);
106116         return resolvedPath;
106117     }
106118     function isParsedCommandLine(entry) {
106119         return !!entry.options;
106120     }
106121     function parseConfigFile(state, configFileName, configFilePath) {
106122         var configFileCache = state.configFileCache;
106123         var value = configFileCache.get(configFilePath);
106124         if (value) {
106125             return isParsedCommandLine(value) ? value : undefined;
106126         }
106127         var diagnostic;
106128         var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
106129         var parsed;
106130         if (host.getParsedCommandLine) {
106131             parsed = host.getParsedCommandLine(configFileName);
106132             if (!parsed)
106133                 diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
106134         }
106135         else {
106136             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
106137             parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
106138             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
106139         }
106140         configFileCache.set(configFilePath, parsed || diagnostic);
106141         return parsed;
106142     }
106143     function resolveProjectName(state, name) {
106144         return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
106145     }
106146     function createBuildOrder(state, roots) {
106147         var temporaryMarks = ts.createMap();
106148         var permanentMarks = ts.createMap();
106149         var circularityReportStack = [];
106150         var buildOrder;
106151         var circularDiagnostics;
106152         for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
106153             var root = roots_1[_i];
106154             visit(root);
106155         }
106156         return circularDiagnostics ?
106157             { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
106158             buildOrder || ts.emptyArray;
106159         function visit(configFileName, inCircularContext) {
106160             var projPath = toResolvedConfigFilePath(state, configFileName);
106161             // Already visited
106162             if (permanentMarks.has(projPath))
106163                 return;
106164             // Circular
106165             if (temporaryMarks.has(projPath)) {
106166                 if (!inCircularContext) {
106167                     (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
106168                 }
106169                 return;
106170             }
106171             temporaryMarks.set(projPath, true);
106172             circularityReportStack.push(configFileName);
106173             var parsed = parseConfigFile(state, configFileName, projPath);
106174             if (parsed && parsed.projectReferences) {
106175                 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
106176                     var ref = _a[_i];
106177                     var resolvedRefPath = resolveProjectName(state, ref.path);
106178                     visit(resolvedRefPath, inCircularContext || ref.circular);
106179                 }
106180             }
106181             circularityReportStack.pop();
106182             permanentMarks.set(projPath, true);
106183             (buildOrder || (buildOrder = [])).push(configFileName);
106184         }
106185     }
106186     function getBuildOrder(state) {
106187         return state.buildOrder || createStateBuildOrder(state);
106188     }
106189     function createStateBuildOrder(state) {
106190         var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
106191         // Clear all to ResolvedConfigFilePaths cache to start fresh
106192         state.resolvedConfigFilePaths.clear();
106193         var currentProjects = ts.arrayToSet(getBuildOrderFromAnyBuildOrder(buildOrder), function (resolved) { return toResolvedConfigFilePath(state, resolved); });
106194         var noopOnDelete = { onDeleteValue: ts.noop };
106195         // Config file cache
106196         ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
106197         ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
106198         ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
106199         ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
106200         ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
106201         ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
106202         ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
106203         // Remove watches for the program no longer in the solution
106204         if (state.watch) {
106205             ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
106206             ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
106207             ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
106208         }
106209         return state.buildOrder = buildOrder;
106210     }
106211     function getBuildOrderFor(state, project, onlyReferences) {
106212         var resolvedProject = project && resolveProjectName(state, project);
106213         var buildOrderFromState = getBuildOrder(state);
106214         if (isCircularBuildOrder(buildOrderFromState))
106215             return buildOrderFromState;
106216         if (resolvedProject) {
106217             var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
106218             var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
106219             if (projectIndex === -1)
106220                 return undefined;
106221         }
106222         var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
106223         ts.Debug.assert(!isCircularBuildOrder(buildOrder));
106224         ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
106225         ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
106226         return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
106227     }
106228     function enableCache(state) {
106229         if (state.cache) {
106230             disableCache(state);
106231         }
106232         var compilerHost = state.compilerHost, host = state.host;
106233         var originalReadFileWithCache = state.readFileWithCache;
106234         var originalGetSourceFile = compilerHost.getSourceFile;
106235         var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
106236             var args = [];
106237             for (var _i = 0; _i < arguments.length; _i++) {
106238                 args[_i] = arguments[_i];
106239             }
106240             return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
106241         }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
106242         state.readFileWithCache = readFileWithCache;
106243         compilerHost.getSourceFile = getSourceFileWithCache;
106244         state.cache = {
106245             originalReadFile: originalReadFile,
106246             originalFileExists: originalFileExists,
106247             originalDirectoryExists: originalDirectoryExists,
106248             originalCreateDirectory: originalCreateDirectory,
106249             originalWriteFile: originalWriteFile,
106250             originalReadFileWithCache: originalReadFileWithCache,
106251             originalGetSourceFile: originalGetSourceFile,
106252         };
106253     }
106254     function disableCache(state) {
106255         if (!state.cache)
106256             return;
106257         var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache;
106258         host.readFile = cache.originalReadFile;
106259         host.fileExists = cache.originalFileExists;
106260         host.directoryExists = cache.originalDirectoryExists;
106261         host.createDirectory = cache.originalCreateDirectory;
106262         host.writeFile = cache.originalWriteFile;
106263         compilerHost.getSourceFile = cache.originalGetSourceFile;
106264         state.readFileWithCache = cache.originalReadFileWithCache;
106265         extendedConfigCache.clear();
106266         if (moduleResolutionCache) {
106267             moduleResolutionCache.directoryToModuleNameMap.clear();
106268             moduleResolutionCache.moduleNameToDirectoryMap.clear();
106269         }
106270         state.cache = undefined;
106271     }
106272     function clearProjectStatus(state, resolved) {
106273         state.projectStatus.delete(resolved);
106274         state.diagnostics.delete(resolved);
106275     }
106276     function addProjToQueue(_a, proj, reloadLevel) {
106277         var projectPendingBuild = _a.projectPendingBuild;
106278         var value = projectPendingBuild.get(proj);
106279         if (value === undefined) {
106280             projectPendingBuild.set(proj, reloadLevel);
106281         }
106282         else if (value < reloadLevel) {
106283             projectPendingBuild.set(proj, reloadLevel);
106284         }
106285     }
106286     function setupInitialBuild(state, cancellationToken) {
106287         // Set initial build if not already built
106288         if (!state.allProjectBuildPending)
106289             return;
106290         state.allProjectBuildPending = false;
106291         if (state.options.watch) {
106292             reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
106293         }
106294         enableCache(state);
106295         var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
106296         buildOrder.forEach(function (configFileName) {
106297             return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
106298         });
106299         if (cancellationToken) {
106300             cancellationToken.throwIfCancellationRequested();
106301         }
106302     }
106303     var InvalidatedProjectKind;
106304     (function (InvalidatedProjectKind) {
106305         InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
106306         InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
106307         InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
106308     })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
106309     function doneInvalidatedProject(state, projectPath) {
106310         state.projectPendingBuild.delete(projectPath);
106311         state.currentInvalidatedProject = undefined;
106312         return state.diagnostics.has(projectPath) ?
106313             ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
106314             ts.ExitStatus.Success;
106315     }
106316     function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
106317         var updateOutputFileStampsPending = true;
106318         return {
106319             kind: InvalidatedProjectKind.UpdateOutputFileStamps,
106320             project: project,
106321             projectPath: projectPath,
106322             buildOrder: buildOrder,
106323             getCompilerOptions: function () { return config.options; },
106324             getCurrentDirectory: function () { return state.currentDirectory; },
106325             updateOutputFileStatmps: function () {
106326                 updateOutputTimestamps(state, config, projectPath);
106327                 updateOutputFileStampsPending = false;
106328             },
106329             done: function () {
106330                 if (updateOutputFileStampsPending) {
106331                     updateOutputTimestamps(state, config, projectPath);
106332                 }
106333                 return doneInvalidatedProject(state, projectPath);
106334             }
106335         };
106336     }
106337     function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
106338         var Step;
106339         (function (Step) {
106340             Step[Step["CreateProgram"] = 0] = "CreateProgram";
106341             Step[Step["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
106342             Step[Step["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
106343             Step[Step["Emit"] = 3] = "Emit";
106344             Step[Step["EmitBundle"] = 4] = "EmitBundle";
106345             Step[Step["BuildInvalidatedProjectOfBundle"] = 5] = "BuildInvalidatedProjectOfBundle";
106346             Step[Step["QueueReferencingProjects"] = 6] = "QueueReferencingProjects";
106347             Step[Step["Done"] = 7] = "Done";
106348         })(Step || (Step = {}));
106349         var step = kind === InvalidatedProjectKind.Build ? Step.CreateProgram : Step.EmitBundle;
106350         var program;
106351         var buildResult;
106352         var invalidatedProjectOfBundle;
106353         return kind === InvalidatedProjectKind.Build ?
106354             {
106355                 kind: kind,
106356                 project: project,
106357                 projectPath: projectPath,
106358                 buildOrder: buildOrder,
106359                 getCompilerOptions: function () { return config.options; },
106360                 getCurrentDirectory: function () { return state.currentDirectory; },
106361                 getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
106362                 getProgram: function () {
106363                     return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
106364                 },
106365                 getSourceFile: function (fileName) {
106366                     return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
106367                 },
106368                 getSourceFiles: function () {
106369                     return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
106370                 },
106371                 getOptionsDiagnostics: function (cancellationToken) {
106372                     return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
106373                 },
106374                 getGlobalDiagnostics: function (cancellationToken) {
106375                     return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
106376                 },
106377                 getConfigFileParsingDiagnostics: function () {
106378                     return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
106379                 },
106380                 getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
106381                     return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
106382                 },
106383                 getAllDependencies: function (sourceFile) {
106384                     return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
106385                 },
106386                 getSemanticDiagnostics: function (sourceFile, cancellationToken) {
106387                     return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
106388                 },
106389                 getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
106390                     return withProgramOrUndefined(function (program) {
106391                         return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
106392                             program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
106393                     });
106394                 },
106395                 emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
106396                     if (targetSourceFile || emitOnlyDtsFiles) {
106397                         return withProgramOrUndefined(function (program) { return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); });
106398                     }
106399                     executeSteps(Step.SemanticDiagnostics, cancellationToken);
106400                     if (step !== Step.Emit)
106401                         return undefined;
106402                     return emit(writeFile, cancellationToken, customTransformers);
106403                 },
106404                 done: done
106405             } :
106406             {
106407                 kind: kind,
106408                 project: project,
106409                 projectPath: projectPath,
106410                 buildOrder: buildOrder,
106411                 getCompilerOptions: function () { return config.options; },
106412                 getCurrentDirectory: function () { return state.currentDirectory; },
106413                 emit: function (writeFile, customTransformers) {
106414                     if (step !== Step.EmitBundle)
106415                         return invalidatedProjectOfBundle;
106416                     return emitBundle(writeFile, customTransformers);
106417                 },
106418                 done: done,
106419             };
106420         function done(cancellationToken, writeFile, customTransformers) {
106421             executeSteps(Step.Done, cancellationToken, writeFile, customTransformers);
106422             return doneInvalidatedProject(state, projectPath);
106423         }
106424         function withProgramOrUndefined(action) {
106425             executeSteps(Step.CreateProgram);
106426             return program && action(program);
106427         }
106428         function withProgramOrEmptyArray(action) {
106429             return withProgramOrUndefined(action) || ts.emptyArray;
106430         }
106431         function createProgram() {
106432             ts.Debug.assert(program === undefined);
106433             if (state.options.dry) {
106434                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
106435                 buildResult = BuildResultFlags.Success;
106436                 step = Step.QueueReferencingProjects;
106437                 return;
106438             }
106439             if (state.options.verbose)
106440                 reportStatus(state, ts.Diagnostics.Building_project_0, project);
106441             if (config.fileNames.length === 0) {
106442                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106443                 // Nothing to build - must be a solution file, basically
106444                 buildResult = BuildResultFlags.None;
106445                 step = Step.QueueReferencingProjects;
106446                 return;
106447             }
106448             var host = state.host, compilerHost = state.compilerHost;
106449             state.projectCompilerOptions = config.options;
106450             // Update module resolution cache if needed
106451             updateModuleResolutionCache(state, project, config);
106452             // Create program
106453             program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
106454             step++;
106455         }
106456         function handleDiagnostics(diagnostics, errorFlags, errorType) {
106457             if (diagnostics.length) {
106458                 buildResult = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType);
106459                 step = Step.QueueReferencingProjects;
106460             }
106461             else {
106462                 step++;
106463             }
106464         }
106465         function getSyntaxDiagnostics(cancellationToken) {
106466             ts.Debug.assertIsDefined(program);
106467             handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
106468         }
106469         function getSemanticDiagnostics(cancellationToken) {
106470             handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
106471         }
106472         function emit(writeFileCallback, cancellationToken, customTransformers) {
106473             ts.Debug.assertIsDefined(program);
106474             ts.Debug.assert(step === Step.Emit);
106475             // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
106476             program.backupState();
106477             var declDiagnostics;
106478             var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
106479             var outputFiles = [];
106480             var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, 
106481             /*writeFileName*/ undefined, 
106482             /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, 
106483             /*emitOnlyDts*/ false, customTransformers).emitResult;
106484             // Don't emit .d.ts if there are decl file errors
106485             if (declDiagnostics) {
106486                 program.restoreState();
106487                 buildResult = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
106488                 step = Step.QueueReferencingProjects;
106489                 return {
106490                     emitSkipped: true,
106491                     diagnostics: emitResult.diagnostics
106492                 };
106493             }
106494             // Actual Emit
106495             var host = state.host, compilerHost = state.compilerHost;
106496             var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
106497             var newestDeclarationFileContentChangedTime = minimumDate;
106498             var anyDtsChanged = false;
106499             var emitterDiagnostics = ts.createDiagnosticCollection();
106500             var emittedOutputs = ts.createMap();
106501             outputFiles.forEach(function (_a) {
106502                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106503                 var priorChangeTime;
106504                 if (!anyDtsChanged && isDeclarationFile(name)) {
106505                     // Check for unchanged .d.ts files
106506                     if (host.fileExists(name) && state.readFileWithCache(name) === text) {
106507                         priorChangeTime = host.getModifiedTime(name);
106508                     }
106509                     else {
106510                         resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
106511                         anyDtsChanged = true;
106512                     }
106513                 }
106514                 emittedOutputs.set(toPath(state, name), name);
106515                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106516                 if (priorChangeTime !== undefined) {
106517                     newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
106518                 }
106519             });
106520             finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, 
106521             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
106522             return emitResult;
106523         }
106524         function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
106525             var emitDiagnostics = emitterDiagnostics.getDiagnostics();
106526             if (emitDiagnostics.length) {
106527                 buildResult = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
106528                 step = Step.QueueReferencingProjects;
106529                 return emitDiagnostics;
106530             }
106531             if (state.writeFileName) {
106532                 emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
106533                 if (program)
106534                     ts.listFiles(program, state.writeFileName);
106535             }
106536             // Update time stamps for rest of the outputs
106537             var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
106538             state.diagnostics.delete(projectPath);
106539             state.projectStatus.set(projectPath, {
106540                 type: ts.UpToDateStatusType.UpToDate,
106541                 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
106542                     maximumDate :
106543                     newestDeclarationFileContentChangedTime,
106544                 oldestOutputFileName: oldestOutputFileName
106545             });
106546             afterProgramDone(state, projectPath, program, config);
106547             state.projectCompilerOptions = state.baseCompilerOptions;
106548             step = Step.QueueReferencingProjects;
106549             buildResult = resultFlags;
106550             return emitDiagnostics;
106551         }
106552         function emitBundle(writeFileCallback, customTransformers) {
106553             ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
106554             if (state.options.dry) {
106555                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
106556                 buildResult = BuildResultFlags.Success;
106557                 step = Step.QueueReferencingProjects;
106558                 return undefined;
106559             }
106560             if (state.options.verbose)
106561                 reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
106562             // Update js, and source map
106563             var compilerHost = state.compilerHost;
106564             state.projectCompilerOptions = config.options;
106565             var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
106566                 var refName = resolveProjectName(state, ref.path);
106567                 return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
106568             }, customTransformers);
106569             if (ts.isString(outputFiles)) {
106570                 reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
106571                 step = Step.BuildInvalidatedProjectOfBundle;
106572                 return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
106573             }
106574             // Actual Emit
106575             ts.Debug.assert(!!outputFiles.length);
106576             var emitterDiagnostics = ts.createDiagnosticCollection();
106577             var emittedOutputs = ts.createMap();
106578             outputFiles.forEach(function (_a) {
106579                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106580                 emittedOutputs.set(toPath(state, name), name);
106581                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106582             });
106583             var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, 
106584             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
106585             return { emitSkipped: false, diagnostics: emitDiagnostics };
106586         }
106587         function executeSteps(till, cancellationToken, writeFile, customTransformers) {
106588             while (step <= till && step < Step.Done) {
106589                 var currentStep = step;
106590                 switch (step) {
106591                     case Step.CreateProgram:
106592                         createProgram();
106593                         break;
106594                     case Step.SyntaxDiagnostics:
106595                         getSyntaxDiagnostics(cancellationToken);
106596                         break;
106597                     case Step.SemanticDiagnostics:
106598                         getSemanticDiagnostics(cancellationToken);
106599                         break;
106600                     case Step.Emit:
106601                         emit(writeFile, cancellationToken, customTransformers);
106602                         break;
106603                     case Step.EmitBundle:
106604                         emitBundle(writeFile, customTransformers);
106605                         break;
106606                     case Step.BuildInvalidatedProjectOfBundle:
106607                         ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
106608                         step = Step.Done;
106609                         break;
106610                     case Step.QueueReferencingProjects:
106611                         queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult));
106612                         step++;
106613                         break;
106614                     // Should never be done
106615                     case Step.Done:
106616                     default:
106617                         ts.assertType(step);
106618                 }
106619                 ts.Debug.assert(step > currentStep);
106620             }
106621         }
106622     }
106623     function needsBuild(_a, status, config) {
106624         var options = _a.options;
106625         if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
106626             return true;
106627         return config.fileNames.length === 0 ||
106628             !!ts.getConfigFileParsingDiagnostics(config).length ||
106629             !ts.isIncrementalCompilation(config.options);
106630     }
106631     function getNextInvalidatedProject(state, buildOrder, reportQueue) {
106632         if (!state.projectPendingBuild.size)
106633             return undefined;
106634         if (isCircularBuildOrder(buildOrder))
106635             return undefined;
106636         if (state.currentInvalidatedProject) {
106637             // Only if same buildOrder the currentInvalidated project can be sent again
106638             return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
106639                 state.currentInvalidatedProject :
106640                 undefined;
106641         }
106642         var options = state.options, projectPendingBuild = state.projectPendingBuild;
106643         for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
106644             var project = buildOrder[projectIndex];
106645             var projectPath = toResolvedConfigFilePath(state, project);
106646             var reloadLevel = state.projectPendingBuild.get(projectPath);
106647             if (reloadLevel === undefined)
106648                 continue;
106649             if (reportQueue) {
106650                 reportQueue = false;
106651                 reportBuildQueue(state, buildOrder);
106652             }
106653             var config = parseConfigFile(state, project, projectPath);
106654             if (!config) {
106655                 reportParseConfigFileDiagnostic(state, projectPath);
106656                 projectPendingBuild.delete(projectPath);
106657                 continue;
106658             }
106659             if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
106660                 watchConfigFile(state, project, projectPath, config);
106661                 watchWildCardDirectories(state, project, projectPath, config);
106662                 watchInputFiles(state, project, projectPath, config);
106663             }
106664             else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
106665                 // Update file names
106666                 var result = ts.getFileNamesFromConfigSpecs(config.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
106667                 ts.updateErrorForNoInputFiles(result, project, config.configFileSpecs, config.errors, ts.canJsonReportNoInutFiles(config.raw));
106668                 config.fileNames = result.fileNames;
106669                 watchInputFiles(state, project, projectPath, config);
106670             }
106671             var status = getUpToDateStatus(state, config, projectPath);
106672             verboseReportProjectStatus(state, project, status);
106673             if (!options.force) {
106674                 if (status.type === ts.UpToDateStatusType.UpToDate) {
106675                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106676                     projectPendingBuild.delete(projectPath);
106677                     // Up to date, skip
106678                     if (options.dry) {
106679                         // In a dry build, inform the user of this fact
106680                         reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
106681                     }
106682                     continue;
106683                 }
106684                 if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
106685                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106686                     return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
106687                 }
106688             }
106689             if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
106690                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106691                 projectPendingBuild.delete(projectPath);
106692                 if (options.verbose) {
106693                     reportStatus(state, status.upstreamProjectBlocked ?
106694                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
106695                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
106696                 }
106697                 continue;
106698             }
106699             if (status.type === ts.UpToDateStatusType.ContainerOnly) {
106700                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106701                 projectPendingBuild.delete(projectPath);
106702                 // Do nothing
106703                 continue;
106704             }
106705             return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
106706                 InvalidatedProjectKind.Build :
106707                 InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
106708         }
106709         return undefined;
106710     }
106711     function listEmittedFile(_a, proj, file) {
106712         var writeFileName = _a.writeFileName;
106713         if (writeFileName && proj.options.listEmittedFiles) {
106714             writeFileName("TSFILE: " + file);
106715         }
106716     }
106717     function getOldProgram(_a, proj, parsed) {
106718         var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
106719         if (options.force)
106720             return undefined;
106721         var value = builderPrograms.get(proj);
106722         if (value)
106723             return value;
106724         return ts.readBuilderProgram(parsed.options, compilerHost);
106725     }
106726     function afterProgramDone(_a, proj, program, config) {
106727         var host = _a.host, watch = _a.watch, builderPrograms = _a.builderPrograms;
106728         if (program) {
106729             if (host.afterProgramEmitAndDiagnostics) {
106730                 host.afterProgramEmitAndDiagnostics(program);
106731             }
106732             if (watch) {
106733                 program.releaseProgram();
106734                 builderPrograms.set(proj, program);
106735             }
106736         }
106737         else if (host.afterEmitBundle) {
106738             host.afterEmitBundle(config);
106739         }
106740     }
106741     function buildErrors(state, resolvedPath, program, config, diagnostics, errorFlags, errorType) {
106742         reportAndStoreErrors(state, resolvedPath, diagnostics);
106743         // List files if any other build error using program (emit errors already report files)
106744         if (program && state.writeFileName)
106745             ts.listFiles(program, state.writeFileName);
106746         state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
106747         afterProgramDone(state, resolvedPath, program, config);
106748         state.projectCompilerOptions = state.baseCompilerOptions;
106749         return errorFlags;
106750     }
106751     function updateModuleResolutionCache(state, proj, config) {
106752         if (!state.moduleResolutionCache)
106753             return;
106754         // Update module resolution cache if needed
106755         var moduleResolutionCache = state.moduleResolutionCache;
106756         var projPath = toPath(state, proj);
106757         if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) {
106758             // The own map will be for projectCompilerOptions
106759             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0);
106760             moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap);
106761             moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap);
106762         }
106763         else {
106764             // Set correct own map
106765             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0);
106766             var ref = {
106767                 sourceFile: config.options.configFile,
106768                 commandLine: config
106769             };
106770             moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
106771             moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
106772         }
106773         moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options);
106774         moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options);
106775     }
106776     function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
106777         // Check tsconfig time
106778         var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
106779         if (oldestOutputFileTime < tsconfigTime) {
106780             return {
106781                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
106782                 outOfDateOutputFileName: oldestOutputFileName,
106783                 newerInputFileName: configFile
106784             };
106785         }
106786     }
106787     function getUpToDateStatusWorker(state, project, resolvedPath) {
106788         var newestInputFileName = undefined;
106789         var newestInputFileTime = minimumDate;
106790         var host = state.host;
106791         // Get timestamps of input files
106792         for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
106793             var inputFile = _a[_i];
106794             if (!host.fileExists(inputFile)) {
106795                 return {
106796                     type: ts.UpToDateStatusType.Unbuildable,
106797                     reason: inputFile + " does not exist"
106798                 };
106799             }
106800             var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
106801             if (inputTime > newestInputFileTime) {
106802                 newestInputFileName = inputFile;
106803                 newestInputFileTime = inputTime;
106804             }
106805         }
106806         // Container if no files are specified in the project
106807         if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
106808             return {
106809                 type: ts.UpToDateStatusType.ContainerOnly
106810             };
106811         }
106812         // Collect the expected outputs of this project
106813         var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
106814         // Now see if all outputs are newer than the newest input
106815         var oldestOutputFileName = "(none)";
106816         var oldestOutputFileTime = maximumDate;
106817         var newestOutputFileName = "(none)";
106818         var newestOutputFileTime = minimumDate;
106819         var missingOutputFileName;
106820         var newestDeclarationFileContentChangedTime = minimumDate;
106821         var isOutOfDateWithInputs = false;
106822         for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
106823             var output = outputs_1[_b];
106824             // Output is missing; can stop checking
106825             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106826             if (!host.fileExists(output)) {
106827                 missingOutputFileName = output;
106828                 break;
106829             }
106830             var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
106831             if (outputTime < oldestOutputFileTime) {
106832                 oldestOutputFileTime = outputTime;
106833                 oldestOutputFileName = output;
106834             }
106835             // If an output is older than the newest input, we can stop checking
106836             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106837             if (outputTime < newestInputFileTime) {
106838                 isOutOfDateWithInputs = true;
106839                 break;
106840             }
106841             if (outputTime > newestOutputFileTime) {
106842                 newestOutputFileTime = outputTime;
106843                 newestOutputFileName = output;
106844             }
106845             // Keep track of when the most recent time a .d.ts file was changed.
106846             // In addition to file timestamps, we also keep track of when a .d.ts file
106847             // had its file touched but not had its contents changed - this allows us
106848             // to skip a downstream typecheck
106849             if (isDeclarationFile(output)) {
106850                 var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
106851                 newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
106852             }
106853         }
106854         var pseudoUpToDate = false;
106855         var usesPrepend = false;
106856         var upstreamChangedProject;
106857         if (project.projectReferences) {
106858             state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
106859             for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
106860                 var ref = _d[_c];
106861                 usesPrepend = usesPrepend || !!(ref.prepend);
106862                 var resolvedRef = ts.resolveProjectReferencePath(ref);
106863                 var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
106864                 var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
106865                 // Its a circular reference ignore the status of this project
106866                 if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
106867                     refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
106868                     continue;
106869                 }
106870                 // An upstream project is blocked
106871                 if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
106872                     refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
106873                     return {
106874                         type: ts.UpToDateStatusType.UpstreamBlocked,
106875                         upstreamProjectName: ref.path,
106876                         upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
106877                     };
106878                 }
106879                 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
106880                 if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
106881                     return {
106882                         type: ts.UpToDateStatusType.UpstreamOutOfDate,
106883                         upstreamProjectName: ref.path
106884                     };
106885                 }
106886                 // Check oldest output file name only if there is no missing output file name
106887                 if (!missingOutputFileName) {
106888                     // If the upstream project's newest file is older than our oldest output, we
106889                     // can't be out of date because of it
106890                     if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
106891                         continue;
106892                     }
106893                     // If the upstream project has only change .d.ts files, and we've built
106894                     // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
106895                     if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
106896                         pseudoUpToDate = true;
106897                         upstreamChangedProject = ref.path;
106898                         continue;
106899                     }
106900                     // We have an output older than an upstream output - we are out of date
106901                     ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
106902                     return {
106903                         type: ts.UpToDateStatusType.OutOfDateWithUpstream,
106904                         outOfDateOutputFileName: oldestOutputFileName,
106905                         newerProjectName: ref.path
106906                     };
106907                 }
106908             }
106909         }
106910         if (missingOutputFileName !== undefined) {
106911             return {
106912                 type: ts.UpToDateStatusType.OutputMissing,
106913                 missingOutputFileName: missingOutputFileName
106914             };
106915         }
106916         if (isOutOfDateWithInputs) {
106917             return {
106918                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
106919                 outOfDateOutputFileName: oldestOutputFileName,
106920                 newerInputFileName: newestInputFileName
106921             };
106922         }
106923         else {
106924             // Check tsconfig time
106925             var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
106926             if (configStatus)
106927                 return configStatus;
106928             // Check extended config time
106929             var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
106930             if (extendedConfigStatus)
106931                 return extendedConfigStatus;
106932         }
106933         if (!state.buildInfoChecked.has(resolvedPath)) {
106934             state.buildInfoChecked.set(resolvedPath, true);
106935             var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
106936             if (buildInfoPath) {
106937                 var value = state.readFileWithCache(buildInfoPath);
106938                 var buildInfo = value && ts.getBuildInfo(value);
106939                 if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
106940                     return {
106941                         type: ts.UpToDateStatusType.TsVersionOutputOfDate,
106942                         version: buildInfo.version
106943                     };
106944                 }
106945             }
106946         }
106947         if (usesPrepend && pseudoUpToDate) {
106948             return {
106949                 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
106950                 outOfDateOutputFileName: oldestOutputFileName,
106951                 newerProjectName: upstreamChangedProject
106952             };
106953         }
106954         // Up to date
106955         return {
106956             type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
106957             newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
106958             newestInputFileTime: newestInputFileTime,
106959             newestOutputFileTime: newestOutputFileTime,
106960             newestInputFileName: newestInputFileName,
106961             newestOutputFileName: newestOutputFileName,
106962             oldestOutputFileName: oldestOutputFileName
106963         };
106964     }
106965     function getUpToDateStatus(state, project, resolvedPath) {
106966         if (project === undefined) {
106967             return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
106968         }
106969         var prior = state.projectStatus.get(resolvedPath);
106970         if (prior !== undefined) {
106971             return prior;
106972         }
106973         var actual = getUpToDateStatusWorker(state, project, resolvedPath);
106974         state.projectStatus.set(resolvedPath, actual);
106975         return actual;
106976     }
106977     function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
106978         var host = state.host;
106979         var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
106980         if (!skipOutputs || outputs.length !== skipOutputs.size) {
106981             var reportVerbose = !!state.options.verbose;
106982             var now = host.now ? host.now() : new Date();
106983             for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
106984                 var file = outputs_2[_i];
106985                 if (skipOutputs && skipOutputs.has(toPath(state, file))) {
106986                     continue;
106987                 }
106988                 if (reportVerbose) {
106989                     reportVerbose = false;
106990                     reportStatus(state, verboseMessage, proj.options.configFilePath);
106991                 }
106992                 if (isDeclarationFile(file)) {
106993                     priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
106994                 }
106995                 host.setModifiedTime(file, now);
106996             }
106997         }
106998         return priorNewestUpdateTime;
106999     }
107000     function updateOutputTimestamps(state, proj, resolvedPath) {
107001         if (state.options.dry) {
107002             return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
107003         }
107004         var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
107005         state.projectStatus.set(resolvedPath, {
107006             type: ts.UpToDateStatusType.UpToDate,
107007             newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
107008             oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
107009         });
107010     }
107011     function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
107012         // Queue only if there are no errors
107013         if (buildResult & BuildResultFlags.AnyErrors)
107014             return;
107015         // Only composite projects can be referenced by other projects
107016         if (!config.options.composite)
107017             return;
107018         // Always use build order to queue projects
107019         for (var index = projectIndex + 1; index < buildOrder.length; index++) {
107020             var nextProject = buildOrder[index];
107021             var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
107022             if (state.projectPendingBuild.has(nextProjectPath))
107023                 continue;
107024             var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
107025             if (!nextProjectConfig || !nextProjectConfig.projectReferences)
107026                 continue;
107027             for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
107028                 var ref = _a[_i];
107029                 var resolvedRefPath = resolveProjectName(state, ref.path);
107030                 if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
107031                     continue;
107032                 // If the project is referenced with prepend, always build downstream projects,
107033                 // If declaration output is changed, build the project
107034                 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
107035                 var status = state.projectStatus.get(nextProjectPath);
107036                 if (status) {
107037                     switch (status.type) {
107038                         case ts.UpToDateStatusType.UpToDate:
107039                             if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
107040                                 if (ref.prepend) {
107041                                     state.projectStatus.set(nextProjectPath, {
107042                                         type: ts.UpToDateStatusType.OutOfDateWithPrepend,
107043                                         outOfDateOutputFileName: status.oldestOutputFileName,
107044                                         newerProjectName: project
107045                                     });
107046                                 }
107047                                 else {
107048                                     status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
107049                                 }
107050                                 break;
107051                             }
107052                         // falls through
107053                         case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107054                         case ts.UpToDateStatusType.OutOfDateWithPrepend:
107055                             if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
107056                                 state.projectStatus.set(nextProjectPath, {
107057                                     type: ts.UpToDateStatusType.OutOfDateWithUpstream,
107058                                     outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
107059                                     newerProjectName: project
107060                                 });
107061                             }
107062                             break;
107063                         case ts.UpToDateStatusType.UpstreamBlocked:
107064                             if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
107065                                 clearProjectStatus(state, nextProjectPath);
107066                             }
107067                             break;
107068                     }
107069                 }
107070                 addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
107071                 break;
107072             }
107073         }
107074     }
107075     function build(state, project, cancellationToken, onlyReferences) {
107076         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107077         if (!buildOrder)
107078             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107079         setupInitialBuild(state, cancellationToken);
107080         var reportQueue = true;
107081         var successfulProjects = 0;
107082         while (true) {
107083             var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
107084             if (!invalidatedProject)
107085                 break;
107086             reportQueue = false;
107087             invalidatedProject.done(cancellationToken);
107088             if (!state.diagnostics.has(invalidatedProject.projectPath))
107089                 successfulProjects++;
107090         }
107091         disableCache(state);
107092         reportErrorSummary(state, buildOrder);
107093         startWatching(state, buildOrder);
107094         return isCircularBuildOrder(buildOrder)
107095             ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
107096             : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
107097                 ? ts.ExitStatus.Success
107098                 : successfulProjects
107099                     ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
107100                     : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
107101     }
107102     function clean(state, project, onlyReferences) {
107103         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107104         if (!buildOrder)
107105             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107106         if (isCircularBuildOrder(buildOrder)) {
107107             reportErrors(state, buildOrder.circularDiagnostics);
107108             return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
107109         }
107110         var options = state.options, host = state.host;
107111         var filesToDelete = options.dry ? [] : undefined;
107112         for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
107113             var proj = buildOrder_1[_i];
107114             var resolvedPath = toResolvedConfigFilePath(state, proj);
107115             var parsed = parseConfigFile(state, proj, resolvedPath);
107116             if (parsed === undefined) {
107117                 // File has gone missing; fine to ignore here
107118                 reportParseConfigFileDiagnostic(state, resolvedPath);
107119                 continue;
107120             }
107121             var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
107122             for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
107123                 var output = outputs_3[_a];
107124                 if (host.fileExists(output)) {
107125                     if (filesToDelete) {
107126                         filesToDelete.push(output);
107127                     }
107128                     else {
107129                         host.deleteFile(output);
107130                         invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
107131                     }
107132                 }
107133             }
107134         }
107135         if (filesToDelete) {
107136             reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
107137         }
107138         return ts.ExitStatus.Success;
107139     }
107140     function invalidateProject(state, resolved, reloadLevel) {
107141         // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
107142         if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
107143             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
107144         }
107145         if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
107146             state.configFileCache.delete(resolved);
107147             state.buildOrder = undefined;
107148         }
107149         state.needsSummary = true;
107150         clearProjectStatus(state, resolved);
107151         addProjToQueue(state, resolved, reloadLevel);
107152         enableCache(state);
107153     }
107154     function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
107155         state.reportFileChangeDetected = true;
107156         invalidateProject(state, resolvedPath, reloadLevel);
107157         scheduleBuildInvalidatedProject(state);
107158     }
107159     function scheduleBuildInvalidatedProject(state) {
107160         var hostWithWatch = state.hostWithWatch;
107161         if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
107162             return;
107163         }
107164         if (state.timerToBuildInvalidatedProject) {
107165             hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
107166         }
107167         state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
107168     }
107169     function buildNextInvalidatedProject(state) {
107170         state.timerToBuildInvalidatedProject = undefined;
107171         if (state.reportFileChangeDetected) {
107172             state.reportFileChangeDetected = false;
107173             state.projectErrorsReported.clear();
107174             reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
107175         }
107176         var buildOrder = getBuildOrder(state);
107177         var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
107178         if (invalidatedProject) {
107179             invalidatedProject.done();
107180             if (state.projectPendingBuild.size) {
107181                 // Schedule next project for build
107182                 if (state.watch && !state.timerToBuildInvalidatedProject) {
107183                     scheduleBuildInvalidatedProject(state);
107184                 }
107185                 return;
107186             }
107187         }
107188         disableCache(state);
107189         reportErrorSummary(state, buildOrder);
107190     }
107191     function watchConfigFile(state, resolved, resolvedPath, parsed) {
107192         if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
107193             return;
107194         state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(state.hostWithWatch, resolved, function () {
107195             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
107196         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
107197     }
107198     function isSameFile(state, file1, file2) {
107199         return ts.comparePaths(file1, file2, state.currentDirectory, !state.host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
107200     }
107201     function isOutputFile(state, fileName, configFile) {
107202         if (configFile.options.noEmit)
107203             return false;
107204         // ts or tsx files are not output
107205         if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) &&
107206             (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) {
107207             return false;
107208         }
107209         // If options have --outFile or --out, check if its that
107210         var out = configFile.options.outFile || configFile.options.out;
107211         if (out && (isSameFile(state, fileName, out) || isSameFile(state, fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) {
107212             return true;
107213         }
107214         // If declarationDir is specified, return if its a file in that directory
107215         if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107216             return true;
107217         }
107218         // If --outDir, check if file is in that directory
107219         if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107220             return true;
107221         }
107222         return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(state, fileName, inputFile); });
107223     }
107224     function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
107225         if (!state.watch)
107226             return;
107227         ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { return state.watchDirectory(state.hostWithWatch, dir, function (fileOrDirectory) {
107228             var fileOrDirectoryPath = toPath(state, fileOrDirectory);
107229             if (fileOrDirectoryPath !== toPath(state, dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) {
107230                 state.writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory);
107231                 return;
107232             }
107233             if (isOutputFile(state, fileOrDirectory, parsed)) {
107234                 state.writeLog(fileOrDirectory + " is output file");
107235                 return;
107236             }
107237             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
107238         }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
107239     }
107240     function watchInputFiles(state, resolved, resolvedPath, parsed) {
107241         if (!state.watch)
107242             return;
107243         ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
107244             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); },
107245             onDeleteValue: ts.closeFileWatcher,
107246         });
107247     }
107248     function startWatching(state, buildOrder) {
107249         if (!state.watchAllProjectsPending)
107250             return;
107251         state.watchAllProjectsPending = false;
107252         for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
107253             var resolved = _a[_i];
107254             var resolvedPath = toResolvedConfigFilePath(state, resolved);
107255             var cfg = parseConfigFile(state, resolved, resolvedPath);
107256             // Watch this file
107257             watchConfigFile(state, resolved, resolvedPath, cfg);
107258             if (cfg) {
107259                 // Update watchers for wildcard directories
107260                 watchWildCardDirectories(state, resolved, resolvedPath, cfg);
107261                 // Watch input files
107262                 watchInputFiles(state, resolved, resolvedPath, cfg);
107263             }
107264         }
107265     }
107266     function stopWatching(state) {
107267         ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
107268         ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
107269         ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
107270     }
107271     function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
107272         var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
107273         return {
107274             build: function (project, cancellationToken) { return build(state, project, cancellationToken); },
107275             clean: function (project) { return clean(state, project); },
107276             buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); },
107277             cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
107278             getNextInvalidatedProject: function (cancellationToken) {
107279                 setupInitialBuild(state, cancellationToken);
107280                 return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
107281             },
107282             getBuildOrder: function () { return getBuildOrder(state); },
107283             getUpToDateStatusOfProject: function (project) {
107284                 var configFileName = resolveProjectName(state, project);
107285                 var configFilePath = toResolvedConfigFilePath(state, configFileName);
107286                 return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
107287             },
107288             invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
107289             buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
107290             getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
107291             close: function () { return stopWatching(state); },
107292         };
107293     }
107294     function relName(state, path) {
107295         return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
107296     }
107297     function reportStatus(state, message) {
107298         var args = [];
107299         for (var _i = 2; _i < arguments.length; _i++) {
107300             args[_i - 2] = arguments[_i];
107301         }
107302         state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
107303     }
107304     function reportWatchStatus(state, message) {
107305         var args = [];
107306         for (var _i = 2; _i < arguments.length; _i++) {
107307             args[_i - 2] = arguments[_i];
107308         }
107309         if (state.hostWithWatch.onWatchStatusChange) {
107310             state.hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
107311         }
107312     }
107313     function reportErrors(_a, errors) {
107314         var host = _a.host;
107315         errors.forEach(function (err) { return host.reportDiagnostic(err); });
107316     }
107317     function reportAndStoreErrors(state, proj, errors) {
107318         reportErrors(state, errors);
107319         state.projectErrorsReported.set(proj, true);
107320         if (errors.length) {
107321             state.diagnostics.set(proj, errors);
107322         }
107323     }
107324     function reportParseConfigFileDiagnostic(state, proj) {
107325         reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
107326     }
107327     function reportErrorSummary(state, buildOrder) {
107328         if (!state.needsSummary)
107329             return;
107330         state.needsSummary = false;
107331         var canReportSummary = state.watch || !!state.host.reportErrorSummary;
107332         var diagnostics = state.diagnostics;
107333         var totalErrors = 0;
107334         if (isCircularBuildOrder(buildOrder)) {
107335             reportBuildQueue(state, buildOrder.buildOrder);
107336             reportErrors(state, buildOrder.circularDiagnostics);
107337             if (canReportSummary)
107338                 totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
107339         }
107340         else {
107341             // Report errors from the other projects
107342             buildOrder.forEach(function (project) {
107343                 var projectPath = toResolvedConfigFilePath(state, project);
107344                 if (!state.projectErrorsReported.has(projectPath)) {
107345                     reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
107346                 }
107347             });
107348             if (canReportSummary)
107349                 diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
107350         }
107351         if (state.watch) {
107352             reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
107353         }
107354         else if (state.host.reportErrorSummary) {
107355             state.host.reportErrorSummary(totalErrors);
107356         }
107357     }
107358     /**
107359      * Report the build ordering inferred from the current project graph if we're in verbose mode
107360      */
107361     function reportBuildQueue(state, buildQueue) {
107362         if (state.options.verbose) {
107363             reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n    * " + relName(state, s); }).join(""));
107364         }
107365     }
107366     function reportUpToDateStatus(state, configFileName, status) {
107367         switch (status.type) {
107368             case ts.UpToDateStatusType.OutOfDateWithSelf:
107369                 return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName));
107370             case ts.UpToDateStatusType.OutOfDateWithUpstream:
107371                 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));
107372             case ts.UpToDateStatusType.OutputMissing:
107373                 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));
107374             case ts.UpToDateStatusType.UpToDate:
107375                 if (status.newestInputFileTime !== undefined) {
107376                     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 || ""));
107377                 }
107378                 // Don't report anything for "up to date because it was already built" -- too verbose
107379                 break;
107380             case ts.UpToDateStatusType.OutOfDateWithPrepend:
107381                 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));
107382             case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107383                 return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
107384             case ts.UpToDateStatusType.UpstreamOutOfDate:
107385                 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));
107386             case ts.UpToDateStatusType.UpstreamBlocked:
107387                 return reportStatus(state, status.upstreamProjectBlocked ?
107388                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
107389                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
107390             case ts.UpToDateStatusType.Unbuildable:
107391                 return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
107392             case ts.UpToDateStatusType.TsVersionOutputOfDate:
107393                 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);
107394             case ts.UpToDateStatusType.ContainerOnly:
107395             // Don't report status on "solution" projects
107396             // falls through
107397             case ts.UpToDateStatusType.ComputingUpstream:
107398                 // Should never leak from getUptoDateStatusWorker
107399                 break;
107400             default:
107401                 ts.assertType(status);
107402         }
107403     }
107404     /**
107405      * Report the up-to-date status of a project if we're in verbose mode
107406      */
107407     function verboseReportProjectStatus(state, configFileName, status) {
107408         if (state.options.verbose) {
107409             reportUpToDateStatus(state, configFileName, status);
107410         }
107411     }
107412 })(ts || (ts = {}));
107413 var ts;
107414 (function (ts) {
107415     var server;
107416     (function (server) {
107417         /* @internal */
107418         server.ActionSet = "action::set";
107419         /* @internal */
107420         server.ActionInvalidate = "action::invalidate";
107421         /* @internal */
107422         server.ActionPackageInstalled = "action::packageInstalled";
107423         /* @internal */
107424         server.EventTypesRegistry = "event::typesRegistry";
107425         /* @internal */
107426         server.EventBeginInstallTypes = "event::beginInstallTypes";
107427         /* @internal */
107428         server.EventEndInstallTypes = "event::endInstallTypes";
107429         /* @internal */
107430         server.EventInitializationFailed = "event::initializationFailed";
107431         /* @internal */
107432         var Arguments;
107433         (function (Arguments) {
107434             Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
107435             Arguments.LogFile = "--logFile";
107436             Arguments.EnableTelemetry = "--enableTelemetry";
107437             Arguments.TypingSafeListLocation = "--typingSafeListLocation";
107438             Arguments.TypesMapLocation = "--typesMapLocation";
107439             /**
107440              * This argument specifies the location of the NPM executable.
107441              * typingsInstaller will run the command with `${npmLocation} install ...`.
107442              */
107443             Arguments.NpmLocation = "--npmLocation";
107444             /**
107445              * Flag indicating that the typings installer should try to validate the default npm location.
107446              * If the default npm is not found when this flag is enabled, fallback to `npm install`
107447              */
107448             Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
107449         })(Arguments = server.Arguments || (server.Arguments = {}));
107450         /* @internal */
107451         function hasArgument(argumentName) {
107452             return ts.sys.args.indexOf(argumentName) >= 0;
107453         }
107454         server.hasArgument = hasArgument;
107455         /* @internal */
107456         function findArgument(argumentName) {
107457             var index = ts.sys.args.indexOf(argumentName);
107458             return index >= 0 && index < ts.sys.args.length - 1
107459                 ? ts.sys.args[index + 1]
107460                 : undefined;
107461         }
107462         server.findArgument = findArgument;
107463         /* @internal */
107464         function nowString() {
107465             // E.g. "12:34:56.789"
107466             var d = new Date();
107467             return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
107468         }
107469         server.nowString = nowString;
107470     })(server = ts.server || (ts.server = {}));
107471 })(ts || (ts = {}));
107472 /* @internal */
107473 var ts;
107474 (function (ts) {
107475     var JsTyping;
107476     (function (JsTyping) {
107477         function isTypingUpToDate(cachedTyping, availableTypingVersions) {
107478             var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
107479             return availableVersion.compareTo(cachedTyping.version) <= 0;
107480         }
107481         JsTyping.isTypingUpToDate = isTypingUpToDate;
107482         JsTyping.nodeCoreModuleList = [
107483             "assert",
107484             "async_hooks",
107485             "buffer",
107486             "child_process",
107487             "cluster",
107488             "console",
107489             "constants",
107490             "crypto",
107491             "dgram",
107492             "dns",
107493             "domain",
107494             "events",
107495             "fs",
107496             "http",
107497             "https",
107498             "http2",
107499             "inspector",
107500             "net",
107501             "os",
107502             "path",
107503             "perf_hooks",
107504             "process",
107505             "punycode",
107506             "querystring",
107507             "readline",
107508             "repl",
107509             "stream",
107510             "string_decoder",
107511             "timers",
107512             "tls",
107513             "tty",
107514             "url",
107515             "util",
107516             "v8",
107517             "vm",
107518             "zlib"
107519         ];
107520         JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
107521         function nonRelativeModuleNameForTypingCache(moduleName) {
107522             return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
107523         }
107524         JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
107525         function loadSafeList(host, safeListPath) {
107526             var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
107527             return ts.createMapFromTemplate(result.config);
107528         }
107529         JsTyping.loadSafeList = loadSafeList;
107530         function loadTypesMap(host, typesMapPath) {
107531             var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
107532             if (result.config) {
107533                 return ts.createMapFromTemplate(result.config.simpleMap);
107534             }
107535             return undefined;
107536         }
107537         JsTyping.loadTypesMap = loadTypesMap;
107538         /**
107539          * @param host is the object providing I/O related operations.
107540          * @param fileNames are the file names that belong to the same project
107541          * @param projectRootPath is the path to the project root directory
107542          * @param safeListPath is the path used to retrieve the safe list
107543          * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
107544          * @param typeAcquisition is used to customize the typing acquisition process
107545          * @param compilerOptions are used as a source for typing inference
107546          */
107547         function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
107548             if (!typeAcquisition || !typeAcquisition.enable) {
107549                 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
107550             }
107551             // A typing name to typing file path mapping
107552             var inferredTypings = ts.createMap();
107553             // Only infer typings for .js and .jsx files
107554             fileNames = ts.mapDefined(fileNames, function (fileName) {
107555                 var path = ts.normalizePath(fileName);
107556                 if (ts.hasJSFileExtension(path)) {
107557                     return path;
107558                 }
107559             });
107560             var filesToWatch = [];
107561             if (typeAcquisition.include)
107562                 addInferredTypings(typeAcquisition.include, "Explicitly included types");
107563             var exclude = typeAcquisition.exclude || [];
107564             // Directories to search for package.json, bower.json and other typing information
107565             var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath);
107566             possibleSearchDirs.set(projectRootPath, true);
107567             possibleSearchDirs.forEach(function (_true, searchDir) {
107568                 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
107569                 getTypingNamesFromJson(packageJsonPath, filesToWatch);
107570                 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
107571                 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
107572                 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
107573                 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
107574                 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
107575                 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
107576             });
107577             getTypingNamesFromSourceFileNames(fileNames);
107578             // add typings for unresolved imports
107579             if (unresolvedImports) {
107580                 var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
107581                 addInferredTypings(module_1, "Inferred typings from unresolved imports");
107582             }
107583             // Add the cached typing locations for inferred typings that are already installed
107584             packageNameToTypingLocation.forEach(function (typing, name) {
107585                 var registryEntry = typesRegistry.get(name);
107586                 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
107587                     inferredTypings.set(name, typing.typingLocation);
107588                 }
107589             });
107590             // Remove typings that the user has added to the exclude list
107591             for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
107592                 var excludeTypingName = exclude_1[_i];
107593                 var didDelete = inferredTypings.delete(excludeTypingName);
107594                 if (didDelete && log)
107595                     log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
107596             }
107597             var newTypingNames = [];
107598             var cachedTypingPaths = [];
107599             inferredTypings.forEach(function (inferred, typing) {
107600                 if (inferred !== undefined) {
107601                     cachedTypingPaths.push(inferred);
107602                 }
107603                 else {
107604                     newTypingNames.push(typing);
107605                 }
107606             });
107607             var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
107608             if (log)
107609                 log("Result: " + JSON.stringify(result));
107610             return result;
107611             function addInferredTyping(typingName) {
107612                 if (!inferredTypings.has(typingName)) {
107613                     inferredTypings.set(typingName, undefined); // TODO: GH#18217
107614                 }
107615             }
107616             function addInferredTypings(typingNames, message) {
107617                 if (log)
107618                     log(message + ": " + JSON.stringify(typingNames));
107619                 ts.forEach(typingNames, addInferredTyping);
107620             }
107621             /**
107622              * Get the typing info from common package manager json files like package.json or bower.json
107623              */
107624             function getTypingNamesFromJson(jsonPath, filesToWatch) {
107625                 if (!host.fileExists(jsonPath)) {
107626                     return;
107627                 }
107628                 filesToWatch.push(jsonPath);
107629                 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
107630                 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
107631                 addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
107632             }
107633             /**
107634              * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
107635              * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
107636              * to the 'angular-route' typing name.
107637              * @param fileNames are the names for source files in the project
107638              */
107639             function getTypingNamesFromSourceFileNames(fileNames) {
107640                 var fromFileNames = ts.mapDefined(fileNames, function (j) {
107641                     if (!ts.hasJSFileExtension(j))
107642                         return undefined;
107643                     var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
107644                     var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
107645                     return safeList.get(cleanedTypingName);
107646                 });
107647                 if (fromFileNames.length) {
107648                     addInferredTypings(fromFileNames, "Inferred typings from file names");
107649                 }
107650                 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
107651                 if (hasJsxFile) {
107652                     if (log)
107653                         log("Inferred 'react' typings due to presence of '.jsx' extension");
107654                     addInferredTyping("react");
107655                 }
107656             }
107657             /**
107658              * Infer typing names from packages folder (ex: node_module, bower_components)
107659              * @param packagesFolderPath is the path to the packages folder
107660              */
107661             function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
107662                 filesToWatch.push(packagesFolderPath);
107663                 // Todo: add support for ModuleResolutionHost too
107664                 if (!host.directoryExists(packagesFolderPath)) {
107665                     return;
107666                 }
107667                 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
107668                 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
107669                 if (log)
107670                     log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
107671                 var packageNames = [];
107672                 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
107673                     var fileName = fileNames_1[_i];
107674                     var normalizedFileName = ts.normalizePath(fileName);
107675                     var baseFileName = ts.getBaseFileName(normalizedFileName);
107676                     if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
107677                         continue;
107678                     }
107679                     var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
107680                     var packageJson = result_1.config;
107681                     // npm 3's package.json contains a "_requiredBy" field
107682                     // we should include all the top level module names for npm 2, and only module names whose
107683                     // "_requiredBy" field starts with "#" or equals "/" for npm 3.
107684                     if (baseFileName === "package.json" && packageJson._requiredBy &&
107685                         ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
107686                         continue;
107687                     }
107688                     // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
107689                     // to download d.ts files from DefinitelyTyped
107690                     if (!packageJson.name) {
107691                         continue;
107692                     }
107693                     var ownTypes = packageJson.types || packageJson.typings;
107694                     if (ownTypes) {
107695                         var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
107696                         if (log)
107697                             log("    Package '" + packageJson.name + "' provides its own types.");
107698                         inferredTypings.set(packageJson.name, absolutePath);
107699                     }
107700                     else {
107701                         packageNames.push(packageJson.name);
107702                     }
107703                 }
107704                 addInferredTypings(packageNames, "    Found package names");
107705             }
107706         }
107707         JsTyping.discoverTypings = discoverTypings;
107708         var NameValidationResult;
107709         (function (NameValidationResult) {
107710             NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
107711             NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
107712             NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
107713             NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
107714             NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
107715             NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
107716         })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
107717         var maxPackageNameLength = 214;
107718         /**
107719          * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
107720          */
107721         function validatePackageName(packageName) {
107722             return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
107723         }
107724         JsTyping.validatePackageName = validatePackageName;
107725         function validatePackageNameWorker(packageName, supportScopedPackage) {
107726             if (!packageName) {
107727                 return 1 /* EmptyName */;
107728             }
107729             if (packageName.length > maxPackageNameLength) {
107730                 return 2 /* NameTooLong */;
107731             }
107732             if (packageName.charCodeAt(0) === 46 /* dot */) {
107733                 return 3 /* NameStartsWithDot */;
107734             }
107735             if (packageName.charCodeAt(0) === 95 /* _ */) {
107736                 return 4 /* NameStartsWithUnderscore */;
107737             }
107738             // check if name is scope package like: starts with @ and has one '/' in the middle
107739             // scoped packages are not currently supported
107740             if (supportScopedPackage) {
107741                 var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
107742                 if (matches) {
107743                     var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
107744                     if (scopeResult !== 0 /* Ok */) {
107745                         return { name: matches[1], isScopeName: true, result: scopeResult };
107746                     }
107747                     var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
107748                     if (packageResult !== 0 /* Ok */) {
107749                         return { name: matches[2], isScopeName: false, result: packageResult };
107750                     }
107751                     return 0 /* Ok */;
107752                 }
107753             }
107754             if (encodeURIComponent(packageName) !== packageName) {
107755                 return 5 /* NameContainsNonURISafeCharacters */;
107756             }
107757             return 0 /* Ok */;
107758         }
107759         function renderPackageNameValidationFailure(result, typing) {
107760             return typeof result === "object" ?
107761                 renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
107762                 renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
107763         }
107764         JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
107765         function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
107766             var kind = isScopeName ? "Scope" : "Package";
107767             switch (result) {
107768                 case 1 /* EmptyName */:
107769                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty";
107770                 case 2 /* NameTooLong */:
107771                     return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters";
107772                 case 3 /* NameStartsWithDot */:
107773                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'";
107774                 case 4 /* NameStartsWithUnderscore */:
107775                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'";
107776                 case 5 /* NameContainsNonURISafeCharacters */:
107777                     return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters";
107778                 case 0 /* Ok */:
107779                     return ts.Debug.fail(); // Shouldn't have called this.
107780                 default:
107781                     throw ts.Debug.assertNever(result);
107782             }
107783         }
107784     })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
107785 })(ts || (ts = {}));
107786 var ts;
107787 (function (ts) {
107788     var server;
107789     (function (server) {
107790         var typingsInstaller;
107791         (function (typingsInstaller) {
107792             var nullLog = {
107793                 isEnabled: function () { return false; },
107794                 writeLine: ts.noop
107795             };
107796             function typingToFileName(cachePath, packageName, installTypingHost, log) {
107797                 try {
107798                     var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
107799                     return result.resolvedModule && result.resolvedModule.resolvedFileName;
107800                 }
107801                 catch (e) {
107802                     if (log.isEnabled()) {
107803                         log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message);
107804                     }
107805                     return undefined;
107806                 }
107807             }
107808             /*@internal*/
107809             function installNpmPackages(npmPath, tsVersion, packageNames, install) {
107810                 var hasError = false;
107811                 for (var remaining = packageNames.length; remaining > 0;) {
107812                     var result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
107813                     remaining = result.remaining;
107814                     hasError = install(result.command) || hasError;
107815                 }
107816                 return hasError;
107817             }
107818             typingsInstaller.installNpmPackages = installNpmPackages;
107819             /*@internal*/
107820             function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
107821                 var sliceStart = packageNames.length - remaining;
107822                 var command, toSlice = remaining;
107823                 while (true) {
107824                     command = npmPath + " install --ignore-scripts " + (toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ") + " --save-dev --user-agent=\"typesInstaller/" + tsVersion + "\"";
107825                     if (command.length < 8000) {
107826                         break;
107827                     }
107828                     toSlice = toSlice - Math.floor(toSlice / 2);
107829                 }
107830                 return { command: command, remaining: remaining - toSlice };
107831             }
107832             typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation;
107833             function endsWith(str, suffix, caseSensitive) {
107834                 var expectedPos = str.length - suffix.length;
107835                 return expectedPos >= 0 &&
107836                     (str.indexOf(suffix, expectedPos) === expectedPos ||
107837                         (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */));
107838             }
107839             function isPackageOrBowerJson(fileName, caseSensitive) {
107840                 return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive);
107841             }
107842             function sameFiles(a, b, caseSensitive) {
107843                 return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */);
107844             }
107845             var ProjectWatcherType;
107846             (function (ProjectWatcherType) {
107847                 ProjectWatcherType["FileWatcher"] = "FileWatcher";
107848                 ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher";
107849             })(ProjectWatcherType || (ProjectWatcherType = {}));
107850             var TypingsInstaller = /** @class */ (function () {
107851                 function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) {
107852                     if (log === void 0) { log = nullLog; }
107853                     this.installTypingHost = installTypingHost;
107854                     this.globalCachePath = globalCachePath;
107855                     this.safeListPath = safeListPath;
107856                     this.typesMapLocation = typesMapLocation;
107857                     this.throttleLimit = throttleLimit;
107858                     this.log = log;
107859                     this.packageNameToTypingLocation = ts.createMap();
107860                     this.missingTypingsSet = ts.createMap();
107861                     this.knownCachesSet = ts.createMap();
107862                     this.projectWatchers = ts.createMap();
107863                     this.pendingRunRequests = [];
107864                     this.installRunCount = 1;
107865                     this.inFlightRequestCount = 0;
107866                     this.latestDistTag = "latest";
107867                     this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames);
107868                     this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json");
107869                     if (this.log.isEnabled()) {
107870                         this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation);
107871                     }
107872                     this.processCacheLocation(this.globalCachePath);
107873                 }
107874                 TypingsInstaller.prototype.closeProject = function (req) {
107875                     this.closeWatchers(req.projectName);
107876                 };
107877                 TypingsInstaller.prototype.closeWatchers = function (projectName) {
107878                     if (this.log.isEnabled()) {
107879                         this.log.writeLine("Closing file watchers for project '" + projectName + "'");
107880                     }
107881                     var watchers = this.projectWatchers.get(projectName);
107882                     if (!watchers) {
107883                         if (this.log.isEnabled()) {
107884                             this.log.writeLine("No watchers are registered for project '" + projectName + "'");
107885                         }
107886                         return;
107887                     }
107888                     ts.clearMap(watchers, ts.closeFileWatcher);
107889                     this.projectWatchers.delete(projectName);
107890                     if (this.log.isEnabled()) {
107891                         this.log.writeLine("Closing file watchers for project '" + projectName + "' - done.");
107892                     }
107893                 };
107894                 TypingsInstaller.prototype.install = function (req) {
107895                     var _this = this;
107896                     if (this.log.isEnabled()) {
107897                         this.log.writeLine("Got install request " + JSON.stringify(req));
107898                     }
107899                     // load existing typing information from the cache
107900                     if (req.cachePath) {
107901                         if (this.log.isEnabled()) {
107902                             this.log.writeLine("Request specifies cache path '" + req.cachePath + "', loading cached information...");
107903                         }
107904                         this.processCacheLocation(req.cachePath);
107905                     }
107906                     if (this.safeList === undefined) {
107907                         this.initializeSafeList();
107908                     }
107909                     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);
107910                     if (this.log.isEnabled()) {
107911                         this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult));
107912                     }
107913                     // start watching files
107914                     this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions);
107915                     // install typings
107916                     if (discoverTypingsResult.newTypingNames.length) {
107917                         this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
107918                     }
107919                     else {
107920                         this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
107921                         if (this.log.isEnabled()) {
107922                             this.log.writeLine("No new typings were requested as a result of typings discovery");
107923                         }
107924                     }
107925                 };
107926                 TypingsInstaller.prototype.initializeSafeList = function () {
107927                     // Prefer the safe list from the types map if it exists
107928                     if (this.typesMapLocation) {
107929                         var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation);
107930                         if (safeListFromMap) {
107931                             this.log.writeLine("Loaded safelist from types map file '" + this.typesMapLocation + "'");
107932                             this.safeList = safeListFromMap;
107933                             return;
107934                         }
107935                         this.log.writeLine("Failed to load safelist from types map file '" + this.typesMapLocation + "'");
107936                     }
107937                     this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath);
107938                 };
107939                 TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) {
107940                     if (this.log.isEnabled()) {
107941                         this.log.writeLine("Processing cache location '" + cacheLocation + "'");
107942                     }
107943                     if (this.knownCachesSet.has(cacheLocation)) {
107944                         if (this.log.isEnabled()) {
107945                             this.log.writeLine("Cache location was already processed...");
107946                         }
107947                         return;
107948                     }
107949                     var packageJson = ts.combinePaths(cacheLocation, "package.json");
107950                     var packageLockJson = ts.combinePaths(cacheLocation, "package-lock.json");
107951                     if (this.log.isEnabled()) {
107952                         this.log.writeLine("Trying to find '" + packageJson + "'...");
107953                     }
107954                     if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
107955                         var npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); // TODO: GH#18217
107956                         var npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); // TODO: GH#18217
107957                         if (this.log.isEnabled()) {
107958                             this.log.writeLine("Loaded content of '" + packageJson + "': " + JSON.stringify(npmConfig));
107959                             this.log.writeLine("Loaded content of '" + packageLockJson + "'");
107960                         }
107961                         if (npmConfig.devDependencies && npmLock.dependencies) {
107962                             for (var key in npmConfig.devDependencies) {
107963                                 if (!ts.hasProperty(npmLock.dependencies, key)) {
107964                                     // if package in package.json but not package-lock.json, skip adding to cache so it is reinstalled on next use
107965                                     continue;
107966                                 }
107967                                 // key is @types/<package name>
107968                                 var packageName = ts.getBaseFileName(key);
107969                                 if (!packageName) {
107970                                     continue;
107971                                 }
107972                                 var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
107973                                 if (!typingFile) {
107974                                     this.missingTypingsSet.set(packageName, true);
107975                                     continue;
107976                                 }
107977                                 var existingTypingFile = this.packageNameToTypingLocation.get(packageName);
107978                                 if (existingTypingFile) {
107979                                     if (existingTypingFile.typingLocation === typingFile) {
107980                                         continue;
107981                                     }
107982                                     if (this.log.isEnabled()) {
107983                                         this.log.writeLine("New typing for package " + packageName + " from '" + typingFile + "' conflicts with existing typing file '" + existingTypingFile + "'");
107984                                     }
107985                                 }
107986                                 if (this.log.isEnabled()) {
107987                                     this.log.writeLine("Adding entry into typings cache: '" + packageName + "' => '" + typingFile + "'");
107988                                 }
107989                                 var info = ts.getProperty(npmLock.dependencies, key);
107990                                 var version_1 = info && info.version;
107991                                 if (!version_1) {
107992                                     continue;
107993                                 }
107994                                 var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) };
107995                                 this.packageNameToTypingLocation.set(packageName, newTyping);
107996                             }
107997                         }
107998                     }
107999                     if (this.log.isEnabled()) {
108000                         this.log.writeLine("Finished processing cache location '" + cacheLocation + "'");
108001                     }
108002                     this.knownCachesSet.set(cacheLocation, true);
108003                 };
108004                 TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
108005                     var _this = this;
108006                     return ts.mapDefined(typingsToInstall, function (typing) {
108007                         var typingKey = ts.mangleScopedPackageName(typing);
108008                         if (_this.missingTypingsSet.get(typingKey)) {
108009                             if (_this.log.isEnabled())
108010                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' is in missingTypingsSet - skipping...");
108011                             return undefined;
108012                         }
108013                         var validationResult = ts.JsTyping.validatePackageName(typing);
108014                         if (validationResult !== 0 /* Ok */) {
108015                             // add typing name to missing set so we won't process it again
108016                             _this.missingTypingsSet.set(typingKey, true);
108017                             if (_this.log.isEnabled())
108018                                 _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing));
108019                             return undefined;
108020                         }
108021                         if (!_this.typesRegistry.has(typingKey)) {
108022                             if (_this.log.isEnabled())
108023                                 _this.log.writeLine("'" + typing + "':: Entry for package '" + typingKey + "' does not exist in local types registry - skipping...");
108024                             return undefined;
108025                         }
108026                         if (_this.packageNameToTypingLocation.get(typingKey) && ts.JsTyping.isTypingUpToDate(_this.packageNameToTypingLocation.get(typingKey), _this.typesRegistry.get(typingKey))) {
108027                             if (_this.log.isEnabled())
108028                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' already has an up-to-date typing - skipping...");
108029                             return undefined;
108030                         }
108031                         return typingKey;
108032                     });
108033                 };
108034                 TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) {
108035                     var npmConfigPath = ts.combinePaths(directory, "package.json");
108036                     if (this.log.isEnabled()) {
108037                         this.log.writeLine("Npm config file: " + npmConfigPath);
108038                     }
108039                     if (!this.installTypingHost.fileExists(npmConfigPath)) {
108040                         if (this.log.isEnabled()) {
108041                             this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one...");
108042                         }
108043                         this.ensureDirectoryExists(directory, this.installTypingHost);
108044                         this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
108045                     }
108046                 };
108047                 TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
108048                     var _this = this;
108049                     if (this.log.isEnabled()) {
108050                         this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall));
108051                     }
108052                     var filteredTypings = this.filterTypings(typingsToInstall);
108053                     if (filteredTypings.length === 0) {
108054                         if (this.log.isEnabled()) {
108055                             this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings");
108056                         }
108057                         this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
108058                         return;
108059                     }
108060                     this.ensurePackageDirectoryExists(cachePath);
108061                     var requestId = this.installRunCount;
108062                     this.installRunCount++;
108063                     // send progress event
108064                     this.sendResponse({
108065                         kind: server.EventBeginInstallTypes,
108066                         eventId: requestId,
108067                         // qualified explicitly to prevent occasional shadowing
108068                         // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
108069                         typingsInstallerVersion: ts.version,
108070                         projectName: req.projectName
108071                     });
108072                     var scopedTypings = filteredTypings.map(typingsName);
108073                     this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) {
108074                         try {
108075                             if (!ok) {
108076                                 if (_this.log.isEnabled()) {
108077                                     _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: " + JSON.stringify(filteredTypings));
108078                                 }
108079                                 for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) {
108080                                     var typing = filteredTypings_1[_i];
108081                                     _this.missingTypingsSet.set(typing, true);
108082                                 }
108083                                 return;
108084                             }
108085                             // TODO: watch project directory
108086                             if (_this.log.isEnabled()) {
108087                                 _this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings));
108088                             }
108089                             var installedTypingFiles = [];
108090                             for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) {
108091                                 var packageName = filteredTypings_2[_a];
108092                                 var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log);
108093                                 if (!typingFile) {
108094                                     _this.missingTypingsSet.set(packageName, true);
108095                                     continue;
108096                                 }
108097                                 // packageName is guaranteed to exist in typesRegistry by filterTypings
108098                                 var distTags = _this.typesRegistry.get(packageName);
108099                                 var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]);
108100                                 var newTyping = { typingLocation: typingFile, version: newVersion };
108101                                 _this.packageNameToTypingLocation.set(packageName, newTyping);
108102                                 installedTypingFiles.push(typingFile);
108103                             }
108104                             if (_this.log.isEnabled()) {
108105                                 _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles));
108106                             }
108107                             _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
108108                         }
108109                         finally {
108110                             var response = {
108111                                 kind: server.EventEndInstallTypes,
108112                                 eventId: requestId,
108113                                 projectName: req.projectName,
108114                                 packagesToInstall: scopedTypings,
108115                                 installSuccess: ok,
108116                                 // qualified explicitly to prevent occasional shadowing
108117                                 // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
108118                                 typingsInstallerVersion: ts.version
108119                             };
108120                             _this.sendResponse(response);
108121                         }
108122                     });
108123                 };
108124                 TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) {
108125                     var directoryName = ts.getDirectoryPath(directory);
108126                     if (!host.directoryExists(directoryName)) {
108127                         this.ensureDirectoryExists(directoryName, host);
108128                     }
108129                     if (!host.directoryExists(directory)) {
108130                         host.createDirectory(directory);
108131                     }
108132                 };
108133                 TypingsInstaller.prototype.watchFiles = function (projectName, files, projectRootPath, options) {
108134                     var _this = this;
108135                     if (!files.length) {
108136                         // shut down existing watchers
108137                         this.closeWatchers(projectName);
108138                         return;
108139                     }
108140                     var watchers = this.projectWatchers.get(projectName);
108141                     var toRemove = ts.createMap();
108142                     if (!watchers) {
108143                         watchers = ts.createMap();
108144                         this.projectWatchers.set(projectName, watchers);
108145                     }
108146                     else {
108147                         ts.copyEntries(watchers, toRemove);
108148                     }
108149                     // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings
108150                     watchers.isInvoked = false;
108151                     var isLoggingEnabled = this.log.isEnabled();
108152                     var createProjectWatcher = function (path, projectWatcherType) {
108153                         var canonicalPath = _this.toCanonicalFileName(path);
108154                         toRemove.delete(canonicalPath);
108155                         if (watchers.has(canonicalPath)) {
108156                             return;
108157                         }
108158                         if (isLoggingEnabled) {
108159                             _this.log.writeLine(projectWatcherType + ":: Added:: WatchInfo: " + path);
108160                         }
108161                         var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ?
108162                             _this.installTypingHost.watchFile(path, function (f, eventKind) {
108163                                 if (isLoggingEnabled) {
108164                                     _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + path + ":: handler is already invoked '" + watchers.isInvoked + "'");
108165                                 }
108166                                 if (!watchers.isInvoked) {
108167                                     watchers.isInvoked = true;
108168                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
108169                                 }
108170                             }, /*pollingInterval*/ 2000, options) :
108171                             _this.installTypingHost.watchDirectory(path, function (f) {
108172                                 if (isLoggingEnabled) {
108173                                     _this.log.writeLine("DirectoryWatcher:: Triggered with " + f + " :: WatchInfo: " + path + " recursive :: handler is already invoked '" + watchers.isInvoked + "'");
108174                                 }
108175                                 if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) {
108176                                     return;
108177                                 }
108178                                 if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) &&
108179                                     !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) {
108180                                     watchers.isInvoked = true;
108181                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
108182                                 }
108183                             }, /*recursive*/ true, options);
108184                         watchers.set(canonicalPath, isLoggingEnabled ? {
108185                             close: function () {
108186                                 _this.log.writeLine(projectWatcherType + ":: Closed:: WatchInfo: " + path);
108187                                 watcher.close();
108188                             }
108189                         } : watcher);
108190                     };
108191                     // Create watches from list of files
108192                     for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
108193                         var file = files_1[_i];
108194                         if (file.endsWith("/package.json") || file.endsWith("/bower.json")) {
108195                             // package.json or bower.json exists, watch the file to detect changes and update typings
108196                             createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
108197                             continue;
108198                         }
108199                         // path in projectRoot, watch project root
108200                         if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
108201                             var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1);
108202                             if (subDirectory !== -1) {
108203                                 // Watch subDirectory
108204                                 createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
108205                             }
108206                             else {
108207                                 // Watch the directory itself
108208                                 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
108209                             }
108210                             continue;
108211                         }
108212                         // path in global cache, watch global cache
108213                         if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
108214                             createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */);
108215                             continue;
108216                         }
108217                         // watch node_modules or bower_components
108218                         createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
108219                     }
108220                     // Remove unused watches
108221                     toRemove.forEach(function (watch, path) {
108222                         watch.close();
108223                         watchers.delete(path);
108224                     });
108225                 };
108226                 TypingsInstaller.prototype.createSetTypings = function (request, typings) {
108227                     return {
108228                         projectName: request.projectName,
108229                         typeAcquisition: request.typeAcquisition,
108230                         compilerOptions: request.compilerOptions,
108231                         typings: typings,
108232                         unresolvedImports: request.unresolvedImports,
108233                         kind: server.ActionSet
108234                     };
108235                 };
108236                 TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) {
108237                     this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted });
108238                     this.executeWithThrottling();
108239                 };
108240                 TypingsInstaller.prototype.executeWithThrottling = function () {
108241                     var _this = this;
108242                     var _loop_1 = function () {
108243                         this_1.inFlightRequestCount++;
108244                         var request = this_1.pendingRunRequests.pop();
108245                         this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) {
108246                             _this.inFlightRequestCount--;
108247                             request.onRequestCompleted(ok);
108248                             _this.executeWithThrottling();
108249                         });
108250                     };
108251                     var this_1 = this;
108252                     while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
108253                         _loop_1();
108254                     }
108255                 };
108256                 return TypingsInstaller;
108257             }());
108258             typingsInstaller.TypingsInstaller = TypingsInstaller;
108259             /* @internal */
108260             function typingsName(packageName) {
108261                 return "@types/" + packageName + "@ts" + ts.versionMajorMinor;
108262             }
108263             typingsInstaller.typingsName = typingsName;
108264         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
108265     })(server = ts.server || (ts.server = {}));
108266 })(ts || (ts = {}));
108267 var ts;
108268 (function (ts) {
108269     var server;
108270     (function (server) {
108271         var typingsInstaller;
108272         (function (typingsInstaller) {
108273             var fs = require("fs");
108274             var path = require("path");
108275             var FileLog = (function () {
108276                 function FileLog(logFile) {
108277                     var _this = this;
108278                     this.logFile = logFile;
108279                     this.isEnabled = function () {
108280                         return typeof _this.logFile === "string";
108281                     };
108282                     this.writeLine = function (text) {
108283                         if (typeof _this.logFile !== "string")
108284                             return;
108285                         try {
108286                             fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine);
108287                         }
108288                         catch (e) {
108289                             _this.logFile = undefined;
108290                         }
108291                     };
108292                 }
108293                 return FileLog;
108294             }());
108295             function getDefaultNPMLocation(processName, validateDefaultNpmLocation, host) {
108296                 if (path.basename(processName).indexOf("node") === 0) {
108297                     var npmPath = path.join(path.dirname(process.argv[0]), "npm");
108298                     if (!validateDefaultNpmLocation) {
108299                         return npmPath;
108300                     }
108301                     if (host.fileExists(npmPath)) {
108302                         return "\"" + npmPath + "\"";
108303                     }
108304                 }
108305                 return "npm";
108306             }
108307             function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
108308                 if (!host.fileExists(typesRegistryFilePath)) {
108309                     if (log.isEnabled()) {
108310                         log.writeLine("Types registry file '" + typesRegistryFilePath + "' does not exist");
108311                     }
108312                     return ts.createMap();
108313                 }
108314                 try {
108315                     var content = JSON.parse(host.readFile(typesRegistryFilePath));
108316                     return ts.createMapFromTemplate(content.entries);
108317                 }
108318                 catch (e) {
108319                     if (log.isEnabled()) {
108320                         log.writeLine("Error when loading types registry file '" + typesRegistryFilePath + "': " + e.message + ", " + e.stack);
108321                     }
108322                     return ts.createMap();
108323                 }
108324             }
108325             var typesRegistryPackageName = "types-registry";
108326             function getTypesRegistryFileLocation(globalTypingsCacheLocation) {
108327                 return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + typesRegistryPackageName + "/index.json");
108328             }
108329             var NodeTypingsInstaller = (function (_super) {
108330                 __extends(NodeTypingsInstaller, _super);
108331                 function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, throttleLimit, log) {
108332                     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;
108333                     _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, _this.installTypingHost);
108334                     if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") {
108335                         _this.npmPath = "\"" + _this.npmPath + "\"";
108336                     }
108337                     if (_this.log.isEnabled()) {
108338                         _this.log.writeLine("Process id: " + process.pid);
108339                         _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)");
108340                         _this.log.writeLine("validateDefaultNpmLocation: " + validateDefaultNpmLocation);
108341                     }
108342                     (_this.nodeExecSync = require("child_process").execSync);
108343                     _this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
108344                     try {
108345                         if (_this.log.isEnabled()) {
108346                             _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package...");
108347                         }
108348                         _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName + "@" + _this.latestDistTag, { cwd: globalTypingsCacheLocation });
108349                         if (_this.log.isEnabled()) {
108350                             _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package");
108351                         }
108352                     }
108353                     catch (e) {
108354                         if (_this.log.isEnabled()) {
108355                             _this.log.writeLine("Error updating " + typesRegistryPackageName + " package: " + e.message);
108356                         }
108357                         _this.delayedInitializationError = {
108358                             kind: "event::initializationFailed",
108359                             message: e.message
108360                         };
108361                     }
108362                     _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log);
108363                     return _this;
108364                 }
108365                 NodeTypingsInstaller.prototype.listen = function () {
108366                     var _this = this;
108367                     process.on("message", function (req) {
108368                         if (_this.delayedInitializationError) {
108369                             _this.sendResponse(_this.delayedInitializationError);
108370                             _this.delayedInitializationError = undefined;
108371                         }
108372                         switch (req.kind) {
108373                             case "discover":
108374                                 _this.install(req);
108375                                 break;
108376                             case "closeProject":
108377                                 _this.closeProject(req);
108378                                 break;
108379                             case "typesRegistry": {
108380                                 var typesRegistry_1 = {};
108381                                 _this.typesRegistry.forEach(function (value, key) {
108382                                     typesRegistry_1[key] = value;
108383                                 });
108384                                 var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 };
108385                                 _this.sendResponse(response);
108386                                 break;
108387                             }
108388                             case "installPackage": {
108389                                 var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath;
108390                                 var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath;
108391                                 if (cwd) {
108392                                     _this.installWorker(-1, [packageName_1], cwd, function (success) {
108393                                         var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + ".";
108394                                         var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message };
108395                                         _this.sendResponse(response);
108396                                     });
108397                                 }
108398                                 else {
108399                                     var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." };
108400                                     _this.sendResponse(response);
108401                                 }
108402                                 break;
108403                             }
108404                             default:
108405                                 ts.Debug.assertNever(req);
108406                         }
108407                     });
108408                 };
108409                 NodeTypingsInstaller.prototype.sendResponse = function (response) {
108410                     if (this.log.isEnabled()) {
108411                         this.log.writeLine("Sending response:\n    " + JSON.stringify(response));
108412                     }
108413                     process.send(response);
108414                     if (this.log.isEnabled()) {
108415                         this.log.writeLine("Response has been sent.");
108416                     }
108417                 };
108418                 NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) {
108419                     var _this = this;
108420                     if (this.log.isEnabled()) {
108421                         this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'.");
108422                     }
108423                     var start = Date.now();
108424                     var hasError = typingsInstaller.installNpmPackages(this.npmPath, ts.version, packageNames, function (command) { return _this.execSyncAndLog(command, { cwd: cwd }); });
108425                     if (this.log.isEnabled()) {
108426                         this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms");
108427                     }
108428                     onRequestCompleted(!hasError);
108429                 };
108430                 NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) {
108431                     if (this.log.isEnabled()) {
108432                         this.log.writeLine("Exec: " + command);
108433                     }
108434                     try {
108435                         var stdout = this.nodeExecSync(command, __assign(__assign({}, options), { encoding: "utf-8" }));
108436                         if (this.log.isEnabled()) {
108437                             this.log.writeLine("    Succeeded. stdout:" + indent(ts.sys.newLine, stdout));
108438                         }
108439                         return false;
108440                     }
108441                     catch (error) {
108442                         var stdout = error.stdout, stderr = error.stderr;
108443                         this.log.writeLine("    Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + "    stderr:" + indent(ts.sys.newLine, stderr));
108444                         return true;
108445                     }
108446                 };
108447                 return NodeTypingsInstaller;
108448             }(typingsInstaller.TypingsInstaller));
108449             typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller;
108450             function getDirectoryOfPackageJson(fileName, host) {
108451                 return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) {
108452                     if (host.fileExists(ts.combinePaths(directory, "package.json"))) {
108453                         return directory;
108454                     }
108455                 });
108456             }
108457             var logFilePath = server.findArgument(server.Arguments.LogFile);
108458             var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation);
108459             var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
108460             var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation);
108461             var npmLocation = server.findArgument(server.Arguments.NpmLocation);
108462             var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
108463             var log = new FileLog(logFilePath);
108464             if (log.isEnabled()) {
108465                 process.on("uncaughtException", function (e) {
108466                     log.writeLine("Unhandled exception: " + e + " at " + e.stack);
108467                 });
108468             }
108469             process.on("disconnect", function () {
108470                 if (log.isEnabled()) {
108471                     log.writeLine("Parent process has exited, shutting down...");
108472                 }
108473                 process.exit(0);
108474             });
108475             var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log);
108476             installer.listen();
108477             function indent(newline, str) {
108478                 return newline + "    " + str.replace(/\r?\n/, newline + "    ");
108479             }
108480         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
108481     })(server = ts.server || (ts.server = {}));
108482 })(ts || (ts = {}));
108483 //# sourceMappingURL=typingsInstaller.js.map