***************************************************************************** */
"use strict";
-var __spreadArrays = (this && this.__spreadArrays) || function () {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
- r[k] = a[j];
- return r;
+var __spreadArray = (this && this.__spreadArray) || function (to, from) {
+ for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
+ to[j] = from[i];
+ return to;
};
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
return extendStatics(d, b);
};
return function (d, b) {
+ if (typeof b !== "function" && b !== null)
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
(function (ts) {
// WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
// If changing the text in this section, be sure to test `configurePrerelease` too.
- ts.versionMajorMinor = "4.1";
+ ts.versionMajorMinor = "4.2";
+ // The following is baselined as a literal template type without intervention
/** The version of the TypeScript compiler release */
- ts.version = "4.1.3";
+ // eslint-disable-next-line @typescript-eslint/no-inferrable-types
+ ts.version = "4.2.3";
/* @internal */
var Comparison;
(function (Comparison) {
return array1;
if (!some(array1))
return array2;
- return __spreadArrays(array1, array2);
+ return __spreadArray(__spreadArray([], array1), array2);
}
ts.concatenate = concatenate;
function selectIndex(_, i) {
// | 1. | i | 105 | Ascii i |
// | 2. | I | 73 | Ascii I |
// |-------- Special characters ------------------------------------------------------------------------|
- // | 3. | \u0130 | 304 | Uppper case I with dot above |
+ // | 3. | \u0130 | 304 | Upper case I with dot above |
// | 4. | i,\u0307 | 105,775 | i, followed by 775: Lower case of (3rd item) |
// | 5. | I,\u0307 | 73,775 | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
// | 6. | \u0131 | 305 | Lower case i without dot, upper case is I (2nd item) |
ts.compareBooleans = compareBooleans;
/**
* 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.
- * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
+ * Names less than length 3 only check for case-insensitive equality.
*
- * If there is a candidate that's the same except for case, return that.
- * If there is a candidate that's within one edit of the name, return that.
- * Otherwise, return the candidate with the smallest Levenshtein distance,
+ * find the candidate with the smallest Levenshtein distance,
* except for candidates:
* * With no name
* * Whose length differs from the target name by more than 0.34 of the length of the name.
*/
function getSpellingSuggestion(name, candidates, getName) {
var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
- var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
+ var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result is worse than this, don't bother.
var bestCandidate;
- var justCheckExactMatches = false;
- var nameLowerCase = name.toLowerCase();
for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
var candidate = candidates_1[_i];
var candidateName = getName(candidate);
- if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
- var candidateNameLowerCase = candidateName.toLowerCase();
- if (candidateNameLowerCase === nameLowerCase) {
- if (candidateName === name) {
- continue;
- }
- return candidate;
- }
- if (justCheckExactMatches) {
+ if (candidateName !== undefined && Math.abs(candidateName.length - name.length) <= maximumLengthDifference) {
+ if (candidateName === name) {
continue;
}
- if (candidateName.length < 3) {
- // Don't bother, user would have noticed a 2-character name having an extra character
+ // Only consider candidates less than 3 characters long when they differ by case.
+ // Otherwise, don't bother, since a user would usually notice differences of a 2-character name.
+ if (candidateName.length < 3 && candidateName.toLowerCase() !== name.toLowerCase()) {
continue;
}
- // Only care about a result better than the best so far.
- var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
+ var distance = levenshteinWithMax(name, candidateName, bestDistance - 0.1);
if (distance === undefined) {
continue;
}
- if (distance < 3) {
- justCheckExactMatches = true;
- bestCandidate = candidate;
- }
- else {
- ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
- bestDistance = distance;
- bestCandidate = candidate;
- }
+ ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
+ bestDistance = distance;
+ bestCandidate = candidate;
}
}
return bestCandidate;
var previous = new Array(s2.length + 1);
var current = new Array(s2.length + 1);
/** Represents any value > max. We don't care about the particular value. */
- var big = max + 1;
+ var big = max + 0.01;
for (var i = 0; i <= s2.length; i++) {
previous[i] = i;
}
for (var i = 1; i <= s1.length; i++) {
var c1 = s1.charCodeAt(i - 1);
- var minJ = i > max ? i - max : 1;
- var maxJ = s2.length > max + i ? max + i : s2.length;
+ var minJ = Math.ceil(i > max ? i - max : 1);
+ var maxJ = Math.floor(s2.length > max + i ? max + i : s2.length);
current[0] = i;
/** Smallest value of the matrix in the ith column. */
var colMin = i;
current[j] = big;
}
for (var j = minJ; j <= maxJ; j++) {
+ // case difference should be significantly cheaper than other differences
+ var substitutionDistance = s1[i - 1].toLowerCase() === s2[j - 1].toLowerCase()
+ ? (previous[j - 1] + 0.1)
+ : (previous[j - 1] + 2);
var dist = c1 === s2.charCodeAt(j - 1)
? previous[j - 1]
- : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
+ : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ substitutionDistance);
current[j] = dist;
colMin = Math.min(colMin, dist);
}
return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
}
Debug.formatTypeFlags = formatTypeFlags;
+ function formatSignatureFlags(flags) {
+ return formatEnum(flags, ts.SignatureFlags, /*isFlags*/ true);
+ }
+ Debug.formatSignatureFlags = formatSignatureFlags;
function formatObjectFlags(flags) {
return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
}
}
},
});
+ Object.defineProperties(ts.objectAllocator.getSignatureConstructor().prototype, {
+ __debugFlags: { get: function () { return formatSignatureFlags(this.flags); } },
+ __debugSignatureToString: { value: function () { var _a; return (_a = this.checker) === null || _a === void 0 ? void 0 : _a.signatureToString(this); } }
+ });
var nodeConstructors = [
ts.objectAllocator.getNodeConstructor(),
ts.objectAllocator.getIdentifierConstructor(),
typeof PerformanceObserver === "function" &&
hasRequiredAPI(performance, PerformanceObserver)) {
return {
+ // For now we always write native performance events when running in the browser. We may
+ // make this conditional in the future if we find that native web performance hooks
+ // in the browser also slow down compilation.
+ shouldWriteNativeEvents: true,
performance: performance,
PerformanceObserver: PerformanceObserver
};
}
}
function tryGetNodePerformanceHooks() {
- if (typeof module === "object" && typeof require === "function") {
+ if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") {
try {
- var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver;
- if (hasRequiredAPI(performance_1, PerformanceObserver_1)) {
+ var performance_1;
+ var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver;
+ if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) {
+ performance_1 = nodePerformance_1;
// There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not
// match the Web Performance API specification. Node's implementation did not allow
// optional `start` and `end` arguments for `performance.measure`.
var version_1 = new ts.Version(process.versions.node);
var range = new ts.VersionRange("<12.16.3 || 13 <13.13");
if (range.test(version_1)) {
- return {
- performance: {
- get timeOrigin() { return performance_1.timeOrigin; },
- now: function () { return performance_1.now(); },
- mark: function (name) { return performance_1.mark(name); },
- measure: function (name, start, end) {
- if (start === void 0) { start = "nodeStart"; }
- if (end === undefined) {
- end = "__performance.measure-fix__";
- performance_1.mark(end);
- }
- performance_1.measure(name, start, end);
- if (end === "__performance.measure-fix__") {
- performance_1.clearMarks("__performance.measure-fix__");
- }
+ performance_1 = {
+ get timeOrigin() { return nodePerformance_1.timeOrigin; },
+ now: function () { return nodePerformance_1.now(); },
+ mark: function (name) { return nodePerformance_1.mark(name); },
+ measure: function (name, start, end) {
+ if (start === void 0) { start = "nodeStart"; }
+ if (end === undefined) {
+ end = "__performance.measure-fix__";
+ nodePerformance_1.mark(end);
+ }
+ nodePerformance_1.measure(name, start, end);
+ if (end === "__performance.measure-fix__") {
+ nodePerformance_1.clearMarks("__performance.measure-fix__");
}
- },
- PerformanceObserver: PerformanceObserver_1
+ }
};
}
return {
+ // By default, only write native events when generating a cpu profile or using the v8 profiler.
+ shouldWriteNativeEvents: false,
performance: performance_1,
PerformanceObserver: PerformanceObserver_1
};
var performance;
(function (performance) {
var perfHooks;
- var perfObserver;
// when set, indicates the implementation of `Performance` to use for user timing.
// when unset, indicates user timing is unavailable or disabled.
var performanceImpl;
}
performance.createTimer = createTimer;
performance.nullTimer = { enter: ts.noop, exit: ts.noop };
+ var enabled = false;
+ var timeorigin = ts.timestamp();
+ var marks = new ts.Map();
var counts = new ts.Map();
var durations = new ts.Map();
/**
* @param markName The name of the mark.
*/
function mark(markName) {
- performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName);
+ var _a;
+ if (enabled) {
+ var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0;
+ counts.set(markName, count + 1);
+ marks.set(markName, ts.timestamp());
+ performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName);
+ }
}
performance.mark = mark;
/**
* used.
*/
function measure(measureName, startMarkName, endMarkName) {
- performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName);
+ var _a, _b;
+ if (enabled) {
+ var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp();
+ var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin;
+ var previousDuration = durations.get(measureName) || 0;
+ durations.set(measureName, previousDuration + (end - start));
+ performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName);
+ }
}
performance.measure = measure;
/**
* Indicates whether the performance API is enabled.
*/
function isEnabled() {
- return !!performanceImpl;
+ return enabled;
}
performance.isEnabled = isEnabled;
/** Enables (and resets) performance measurements for the compiler. */
- function enable() {
- if (!performanceImpl) {
+ function enable(system) {
+ var _a;
+ if (system === void 0) { system = ts.sys; }
+ if (!enabled) {
+ enabled = true;
perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks());
- if (!perfHooks)
- return false;
- perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList));
- perfObserver.observe({ entryTypes: ["mark", "measure"] });
- performanceImpl = perfHooks.performance;
+ if (perfHooks) {
+ timeorigin = perfHooks.performance.timeOrigin;
+ // NodeJS's Web Performance API is currently slower than expected, but we'd still like
+ // to be able to leverage native trace events when node is run with either `--cpu-prof`
+ // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when
+ // running in debug mode (since its possible to generate a cpu profile while debugging).
+ if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) {
+ performanceImpl = perfHooks.performance;
+ }
+ }
}
return true;
}
performance.enable = enable;
/** Disables performance measurements for the compiler. */
function disable() {
- perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect();
- performanceImpl = undefined;
- counts.clear();
- durations.clear();
- }
- performance.disable = disable;
- function updateStatisticsFromList(list) {
- for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) {
- var mark_1 = _a[_i];
- counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1);
- }
- for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) {
- var measure_1 = _c[_b];
- durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration);
+ if (enabled) {
+ marks.clear();
+ counts.clear();
+ durations.clear();
+ performanceImpl = undefined;
+ enabled = false;
}
}
+ performance.disable = disable;
})(performance = ts.performance || (ts.performance = {}));
})(ts || (ts = {}));
/* @internal */
/** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
})(ts || (ts = {}));
+/* Tracing events for the compiler. */
/*@internal*/
-/** Tracing events for the compiler. */
var ts;
(function (ts) {
- var tracing;
- (function (tracing) {
+ // enable the above using startTracing()
+})(ts || (ts = {}));
+// `tracingEnabled` should never be used directly, only through the above
+/* @internal */
+(function (ts) {
+ var tracingEnabled;
+ (function (tracingEnabled) {
+ var Mode;
+ (function (Mode) {
+ Mode[Mode["Project"] = 0] = "Project";
+ Mode[Mode["Build"] = 1] = "Build";
+ Mode[Mode["Server"] = 2] = "Server";
+ })(Mode = tracingEnabled.Mode || (tracingEnabled.Mode = {}));
var fs;
var traceCount = 0;
- var traceFd;
+ var traceFd = 0;
+ var mode;
var legendPath;
var legend = [];
- /** Starts tracing for the given project (unless the `fs` module is unavailable). */
- function startTracing(configFilePath, traceDir, isBuildMode) {
- ts.Debug.assert(!traceFd, "Tracing already started");
+ ;
+ /** Starts tracing for the given project. */
+ function startTracing(tracingMode, traceDir, configFilePath) {
+ ts.Debug.assert(!ts.tracing, "Tracing already started");
if (fs === undefined) {
try {
fs = require("fs");
}
- catch (_a) {
- fs = false;
+ catch (e) {
+ throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")");
}
}
- if (!fs) {
- return;
- }
+ mode = tracingMode;
if (legendPath === undefined) {
legendPath = ts.combinePaths(traceDir, "legend.json");
}
if (!fs.existsSync(traceDir)) {
fs.mkdirSync(traceDir, { recursive: true });
}
- var countPart = isBuildMode ? "." + ++traceCount : "";
+ var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount
+ : mode === 2 /* Server */ ? "." + process.pid
+ : "";
var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json");
var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json");
legend.push({
typesPath: typesPath,
});
traceFd = fs.openSync(tracePath, "w");
+ ts.tracing = tracingEnabled; // only when traceFd is properly set
// Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import)
var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 };
fs.writeSync(traceFd, "[\n"
+ [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })]
.map(function (v) { return JSON.stringify(v); }).join(",\n"));
}
- tracing.startTracing = startTracing;
- /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */
+ tracingEnabled.startTracing = startTracing;
+ /** Stops tracing for the in-progress project and dumps the type catalog. */
function stopTracing(typeCatalog) {
- if (!traceFd) {
- ts.Debug.assert(!fs, "Tracing is not in progress");
- return;
- }
- ts.Debug.assert(fs);
+ ts.Debug.assert(ts.tracing, "Tracing is not in progress");
+ ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode
fs.writeSync(traceFd, "\n]\n");
fs.closeSync(traceFd);
- traceFd = undefined;
+ ts.tracing = undefined;
if (typeCatalog) {
dumpTypes(typeCatalog);
}
legend[legend.length - 1].typesPath = undefined;
}
}
- tracing.stopTracing = stopTracing;
- function isTracing() {
- return !!traceFd;
- }
- tracing.isTracing = isTracing;
+ tracingEnabled.stopTracing = stopTracing;
var Phase;
(function (Phase) {
Phase["Parse"] = "parse";
Phase["Program"] = "program";
Phase["Bind"] = "bind";
Phase["Check"] = "check";
+ Phase["CheckTypes"] = "checkTypes";
Phase["Emit"] = "emit";
- })(Phase = tracing.Phase || (tracing.Phase = {}));
- /** Note: `push`/`pop` should be used by default.
- * `begin`/`end` are for special cases where we need the data point even if the event never
- * terminates (typically for reducing a scenario too big to trace to one that can be completed).
- * In the future we might implement an exit handler to dump unfinished events which would
- * deprecate these operations.
- */
- function begin(phase, name, args) {
- if (!traceFd)
- return;
- writeEvent("B", phase, name, args);
- }
- tracing.begin = begin;
- function end(phase, name, args) {
- if (!traceFd)
- return;
- writeEvent("E", phase, name, args);
- }
- tracing.end = end;
+ Phase["Session"] = "session";
+ })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {}));
function instant(phase, name, args) {
- if (!traceFd)
- return;
writeEvent("I", phase, name, args, "\"s\":\"g\"");
}
- tracing.instant = instant;
- // Used for "Complete" (ph:"X") events
- var completeEvents = [];
- function push(phase, name, args) {
- if (!traceFd)
- return;
- completeEvents.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp() });
+ tracingEnabled.instant = instant;
+ var eventStack = [];
+ /**
+ * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event
+ * never terminates (typically for reducing a scenario too big to trace to one that can be completed).
+ * In the future we might implement an exit handler to dump unfinished events which would deprecate
+ * these operations.
+ */
+ function push(phase, name, args, separateBeginAndEnd) {
+ if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; }
+ if (separateBeginAndEnd) {
+ writeEvent("B", phase, name, args);
+ }
+ eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd });
}
- tracing.push = push;
+ tracingEnabled.push = push;
function pop() {
- if (!traceFd)
- return;
- ts.Debug.assert(completeEvents.length > 0);
- var _a = completeEvents.pop(), phase = _a.phase, name = _a.name, args = _a.args, time = _a.time;
- var dur = 1000 * ts.timestamp() - time;
- writeEvent("X", phase, name, args, "\"dur\":" + dur, time);
+ ts.Debug.assert(eventStack.length > 0);
+ writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp());
+ eventStack.length--;
+ }
+ tracingEnabled.pop = pop;
+ function popAll() {
+ var endTime = 1000 * ts.timestamp();
+ for (var i = eventStack.length - 1; i >= 0; i--) {
+ writeStackEvent(i, endTime);
+ }
+ eventStack.length = 0;
+ }
+ tracingEnabled.popAll = popAll;
+ // sample every 10ms
+ var sampleInterval = 1000 * 10;
+ function writeStackEvent(index, endTime) {
+ var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd;
+ if (separateBeginAndEnd) {
+ writeEvent("E", phase, name, args, /*extras*/ undefined, endTime);
+ }
+ // test if [time,endTime) straddles a sampling point
+ else if (sampleInterval - (time % sampleInterval) <= endTime - time) {
+ writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time);
+ }
}
- tracing.pop = pop;
function writeEvent(eventType, phase, name, args, extras, time) {
if (time === void 0) { time = 1000 * ts.timestamp(); }
- ts.Debug.assert(traceFd);
- ts.Debug.assert(fs);
+ // In server mode, there's no easy way to dump type information, so we drop events that would require it.
+ if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */)
+ return;
ts.performance.mark("beginTracing");
fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"" + eventType + "\",\"cat\":\"" + phase + "\",\"ts\":" + time + ",\"name\":\"" + name + "\"");
if (extras)
}
function dumpTypes(types) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
- ts.Debug.assert(fs);
ts.performance.mark("beginDumpTypes");
var typesPath = legend[legend.length - 1].typesPath;
var typesFd = fs.openSync(typesPath, "w");
if (!legendPath) {
return;
}
- ts.Debug.assert(fs);
fs.writeFileSync(legendPath, JSON.stringify(legend));
}
- tracing.dumpLegend = dumpLegend;
- })(tracing = ts.tracing || (ts.tracing = {}));
+ tracingEnabled.dumpLegend = dumpLegend;
+ })(tracingEnabled = ts.tracingEnabled || (ts.tracingEnabled = {}));
+})(ts || (ts = {}));
+/*@internal*/
+(function (ts) {
+ // define after tracingEnabled is initialized
+ ts.startTracing = ts.tracingEnabled.startTracing;
})(ts || (ts = {}));
var ts;
(function (ts) {
}());
ts.OperationCanceledException = OperationCanceledException;
/*@internal*/
- var RefFileKind;
- (function (RefFileKind) {
- RefFileKind[RefFileKind["Import"] = 0] = "Import";
- RefFileKind[RefFileKind["ReferenceFile"] = 1] = "ReferenceFile";
- RefFileKind[RefFileKind["TypeReferenceDirective"] = 2] = "TypeReferenceDirective";
- })(RefFileKind = ts.RefFileKind || (ts.RefFileKind = {}));
+ var FileIncludeKind;
+ (function (FileIncludeKind) {
+ FileIncludeKind[FileIncludeKind["RootFile"] = 0] = "RootFile";
+ FileIncludeKind[FileIncludeKind["SourceFromProjectReference"] = 1] = "SourceFromProjectReference";
+ FileIncludeKind[FileIncludeKind["OutputFromProjectReference"] = 2] = "OutputFromProjectReference";
+ FileIncludeKind[FileIncludeKind["Import"] = 3] = "Import";
+ FileIncludeKind[FileIncludeKind["ReferenceFile"] = 4] = "ReferenceFile";
+ FileIncludeKind[FileIncludeKind["TypeReferenceDirective"] = 5] = "TypeReferenceDirective";
+ FileIncludeKind[FileIncludeKind["LibFile"] = 6] = "LibFile";
+ FileIncludeKind[FileIncludeKind["LibReferenceDirective"] = 7] = "LibReferenceDirective";
+ FileIncludeKind[FileIncludeKind["AutomaticTypeDirectiveFile"] = 8] = "AutomaticTypeDirectiveFile";
+ })(FileIncludeKind = ts.FileIncludeKind || (ts.FileIncludeKind = {}));
+ /*@internal*/
+ var FilePreprocessingDiagnosticsKind;
+ (function (FilePreprocessingDiagnosticsKind) {
+ FilePreprocessingDiagnosticsKind[FilePreprocessingDiagnosticsKind["FilePreprocessingReferencedDiagnostic"] = 0] = "FilePreprocessingReferencedDiagnostic";
+ FilePreprocessingDiagnosticsKind[FilePreprocessingDiagnosticsKind["FilePreprocessingFileExplainingDiagnostic"] = 1] = "FilePreprocessingFileExplainingDiagnostic";
+ })(FilePreprocessingDiagnosticsKind = ts.FilePreprocessingDiagnosticsKind || (ts.FilePreprocessingDiagnosticsKind = {}));
/* @internal */
var StructureIsReused;
(function (StructureIsReused) {
// This *should* be every type other than null, undefined, void, and never
TypeFlags[TypeFlags["Narrowable"] = 536624127] = "Narrowable";
/* @internal */
- TypeFlags[TypeFlags["NotPrimitiveUnion"] = 469647395] = "NotPrimitiveUnion";
+ TypeFlags[TypeFlags["NotPrimitiveUnion"] = 468598819] = "NotPrimitiveUnion";
// The following flags are aggregated during union and intersection type construction
/* @internal */
TypeFlags[TypeFlags["IncludesMask"] = 205258751] = "IncludesMask";
ElementFlags[ElementFlags["Optional"] = 2] = "Optional";
ElementFlags[ElementFlags["Rest"] = 4] = "Rest";
ElementFlags[ElementFlags["Variadic"] = 8] = "Variadic";
+ ElementFlags[ElementFlags["Fixed"] = 3] = "Fixed";
ElementFlags[ElementFlags["Variable"] = 12] = "Variable";
+ ElementFlags[ElementFlags["NonRequired"] = 14] = "NonRequired";
+ ElementFlags[ElementFlags["NonRest"] = 11] = "NonRest";
})(ElementFlags = ts.ElementFlags || (ts.ElementFlags = {}));
/* @internal */
var JsxReferenceKind;
var SignatureFlags;
(function (SignatureFlags) {
SignatureFlags[SignatureFlags["None"] = 0] = "None";
+ // Propagating flags
SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
- SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain";
- SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain";
- SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 16] = "IsUntypedSignatureInJSFile";
- // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us
+ SignatureFlags[SignatureFlags["Abstract"] = 4] = "Abstract";
+ // Non-propagating flags
+ SignatureFlags[SignatureFlags["IsInnerCallChain"] = 8] = "IsInnerCallChain";
+ SignatureFlags[SignatureFlags["IsOuterCallChain"] = 16] = "IsOuterCallChain";
+ SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 32] = "IsUntypedSignatureInJSFile";
+ // We do not propagate `IsInnerCallChain` or `IsOuterCallChain` to instantiated signatures, as that would result in us
// attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
// instantiating the return type.
- SignatureFlags[SignatureFlags["PropagatingFlags"] = 19] = "PropagatingFlags";
- SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags";
+ SignatureFlags[SignatureFlags["PropagatingFlags"] = 39] = "PropagatingFlags";
+ SignatureFlags[SignatureFlags["CallChainFlags"] = 24] = "CallChainFlags";
})(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
var IndexKind;
(function (IndexKind) {
ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
- ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
- ExternalEmitHelpers[ExternalEmitHelpers["SpreadArrays"] = 2048] = "SpreadArrays";
- ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 4096] = "Await";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 8192] = "AsyncGenerator";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 16384] = "AsyncDelegator";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 32768] = "AsyncValues";
- ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 65536] = "ExportStar";
- ExternalEmitHelpers[ExternalEmitHelpers["ImportStar"] = 131072] = "ImportStar";
- ExternalEmitHelpers[ExternalEmitHelpers["ImportDefault"] = 262144] = "ImportDefault";
- ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 524288] = "MakeTemplateObject";
- ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 1048576] = "ClassPrivateFieldGet";
- ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 2097152] = "ClassPrivateFieldSet";
- ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 4194304] = "CreateBinding";
+ ExternalEmitHelpers[ExternalEmitHelpers["SpreadArray"] = 1024] = "SpreadArray";
+ ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues";
+ ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar";
+ ExternalEmitHelpers[ExternalEmitHelpers["ImportStar"] = 65536] = "ImportStar";
+ ExternalEmitHelpers[ExternalEmitHelpers["ImportDefault"] = 131072] = "ImportDefault";
+ ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 262144] = "MakeTemplateObject";
+ ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 524288] = "ClassPrivateFieldGet";
+ ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 1048576] = "ClassPrivateFieldSet";
+ ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 2097152] = "CreateBinding";
ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
- ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 4194304] = "LastEmitHelper";
+ ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 2097152] = "LastEmitHelper";
// Helpers included by ES2015 for..of
ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
// Helpers included by ES2017 for..await..of
- ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 32768] = "ForAwaitOfIncludes";
+ ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes";
// Helpers included by ES2017 async generators
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 12288] = "AsyncGeneratorIncludes";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes";
// Helpers included by yield* in ES2017 async generators
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 53248] = "AsyncDelegatorIncludes";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes";
// Helpers included by ES2015 spread
ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
})(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
* we expect the host to correctly handle paths in our specified format.
*/
ts.directorySeparator = "/";
- var altDirectorySeparator = "\\";
+ ts.altDirectorySeparator = "\\";
var urlSchemeSeparator = "://";
var backslashRegExp = /\\/g;
//// Path Tests
if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
if (path.charCodeAt(1) !== ch0)
return 1; // POSIX: "/" (or non-normalized "\")
- var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
+ var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : ts.altDirectorySeparator, 2);
if (p1 < 0)
return path.length; // UNC: "//server" or "\\server"
return p1 + 1; // UNC: "//server/" or "\\server\"
var rest = path.substring(rootLength).split(ts.directorySeparator);
if (rest.length && !ts.lastOrUndefined(rest))
rest.pop();
- return __spreadArrays([root], rest);
+ return __spreadArray([root], rest);
}
/**
* Parse a path into an array containing a root component (at index 0) and zero or more path
for (var _i = 1; _i < arguments.length; _i++) {
paths[_i - 1] = arguments[_i];
}
- return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path));
+ return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArray([path], paths)) : normalizeSlashes(path));
}
ts.resolvePath = resolvePath;
/**
* Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
* Comparison is case-sensitive between the canonical paths.
*
- * @deprecated Use `containsPath` if possible.
+ * Use `containsPath` if file names are not already reduced and absolute.
*/
function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
var canonicalFileName = getCanonicalFileName(fileName);
for (; start < fromComponents.length; start++) {
relative.push("..");
}
- return __spreadArrays([""], relative, components);
+ return __spreadArray(__spreadArray([""], relative), components);
}
ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
* (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
*/
/*@internal*/
- function createDirectoryWatcherSupportingRecursive(host) {
+ function createDirectoryWatcherSupportingRecursive(_a) {
+ var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, directoryExists = _a.directoryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout;
var cache = new ts.Map();
var callbackCache = ts.createMultiMap();
var cacheToUpdateChildWatches = new ts.Map();
var timerToUpdateChildWatches;
- var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
- var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
+ var filePathComparer = ts.getStringComparer(!useCaseSensitiveFileNames);
+ var toCanonicalFilePath = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
return function (dirName, callback, recursive, options) { return recursive ?
createDirectoryWatcher(dirName, options, callback) :
- host.watchDirectory(dirName, callback, recursive, options); };
+ watchDirectory(dirName, callback, recursive, options); };
/**
* Create the directory watcher for the dirPath.
*/
}
else {
directoryWatcher = {
- watcher: host.watchDirectory(dirName, function (fileName) {
- if (isIgnoredPath(fileName))
+ watcher: watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName, options))
return;
if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
// Call the actual callback
function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
// Iterate through existing children and update the watches if needed
var parentWatcher = cache.get(dirPath);
- if (parentWatcher && host.directoryExists(dirName)) {
+ if (parentWatcher && directoryExists(dirName)) {
// Schedule the update and postpone invoke for callbacks
scheduleUpdateChildWatches(dirName, dirPath, fileName, options);
return;
cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options, fileNames: [fileName] });
}
if (timerToUpdateChildWatches) {
- host.clearTimeout(timerToUpdateChildWatches);
+ clearTimeout(timerToUpdateChildWatches);
timerToUpdateChildWatches = undefined;
}
- timerToUpdateChildWatches = host.setTimeout(onTimerToUpdateChildWatches, 1000);
+ timerToUpdateChildWatches = setTimeout(onTimerToUpdateChildWatches, 1000);
}
function onTimerToUpdateChildWatches() {
timerToUpdateChildWatches = undefined;
var start = ts.timestamp();
var invokeMap = new ts.Map();
while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
- var _a = cacheToUpdateChildWatches.entries().next(), _b = _a.value, dirPath = _b[0], _c = _b[1], dirName = _c.dirName, options = _c.options, fileNames = _c.fileNames, done = _a.done;
- ts.Debug.assert(!done);
+ var result = cacheToUpdateChildWatches.entries().next();
+ ts.Debug.assert(!result.done);
+ var _a = result.value, dirPath = _a[0], _b = _a[1], dirName = _b.dirName, options = _b.options, fileNames = _b.fileNames;
cacheToUpdateChildWatches.delete(dirPath);
// Because the child refresh is fresh, we would need to invalidate whole root directory being watched
// to ensure that all the changes are reflected at this time
var hasChanges = updateChildWatches(dirName, dirPath, options);
invokeCallbacks(dirPath, invokeMap, hasChanges ? undefined : fileNames);
}
- ts.sysLog("sysLog:: invokingWatchers:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
+ ts.sysLog("sysLog:: invokingWatchers:: Elapsed:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
callbackCache.forEach(function (callbacks, rootDirName) {
var existing = invokeMap.get(rootDirName);
if (existing) {
}
});
var elapsed = ts.timestamp() - start;
- ts.sysLog("sysLog:: Elapsed " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
+ ts.sysLog("sysLog:: Elapsed:: " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
}
function removeChildWatches(parentWatcher) {
if (!parentWatcher)
if (!parentWatcher)
return false;
var newChildWatches;
- var hasChanges = ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
+ var hasChanges = ts.enumerateInsertsAndDeletes(directoryExists(parentDir) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) {
var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
// Filter our the symbolic link directories since those arent included in recursive watch
// which is same behaviour when recursive: true is passed to fs.watch
- return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName, options) && filePathComparer(childFullName, ts.normalizePath(realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
}) : ts.emptyArray, parentWatcher.childWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
parentWatcher.childWatches = newChildWatches || ts.emptyArray;
return hasChanges;
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
- function isIgnoredPath(path) {
- return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ function isIgnoredPath(path, options) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); }) ||
+ isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames, getCurrentDirectory);
}
function isInPath(path, searchPath) {
if (ts.stringContains(path, searchPath))
return true;
- if (host.useCaseSensitiveFileNames)
+ if (useCaseSensitiveFileNames)
return false;
return ts.stringContains(toCanonicalFilePath(path), searchPath);
}
}
};
}
- function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
+ function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames, getCurrentDirectory) {
+ return ((options === null || options === void 0 ? void 0 : options.excludeDirectories) || (options === null || options === void 0 ? void 0 : options.excludeFiles)) && (ts.matchesExclude(pathToCheck, options === null || options === void 0 ? void 0 : options.excludeFiles, useCaseSensitiveFileNames, getCurrentDirectory()) ||
+ ts.matchesExclude(pathToCheck, options === null || options === void 0 ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames, getCurrentDirectory()));
+ }
+ function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory) {
return function (eventName, relativeFileName) {
// In watchDirectory we only care about adding and removing files (when event name is
// "rename"); changes made within files are handled by corresponding fileWatchers (when
// event name is "change")
if (eventName === "rename") {
// When deleting a file, the passed baseFileName is null
- callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
+ var fileName = !relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName));
+ if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames, getCurrentDirectory)) {
+ callback(fileName);
+ }
}
};
}
/*@internal*/
function createSystemWatchFunctions(_a) {
- 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;
+ var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory;
var dynamicPollingWatchFile;
var nonPollingWatchFile;
var hostRecursiveDirectoryWatcher;
}
function watchDirectory(directoryName, callback, recursive, options) {
if (fsSupportsRecursiveFsWatch) {
- return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
+ return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
}
if (!hostRecursiveDirectoryWatcher) {
hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
+ getCurrentDirectory: getCurrentDirectory,
directoryExists: directoryExists,
getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
watchDirectory: nonRecursiveWatchDirectory,
}
function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
ts.Debug.assert(!recursive);
- options = updateOptionsForWatchDirectory(options);
- var watchDirectoryKind = ts.Debug.checkDefined(options.watchDirectory);
+ var watchDirectoryOptions = updateOptionsForWatchDirectory(options);
+ var watchDirectoryKind = ts.Debug.checkDefined(watchDirectoryOptions.watchDirectory);
switch (watchDirectoryKind) {
case ts.WatchDirectoryKind.FixedPollingInterval:
return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium,
return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium,
/*options*/ undefined);
case ts.WatchDirectoryKind.UseFsEvents:
- return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
+ return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(watchDirectoryOptions));
default:
ts.Debug.assertNever(watchDirectoryKind);
}
// not actually work.
var byteOrderMarkIndicator = "\uFEFF";
function getNodeSystem() {
+ var _a;
var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
var _fs = require("fs");
var _path = require("path");
try {
_crypto = require("crypto");
}
- catch (_a) {
+ catch (_b) {
_crypto = undefined;
}
var activeSession;
var profilePath = "./profile.cpuprofile";
+ var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync;
var Buffer = require("buffer").Buffer;
var nodeVersion = getNodeMajorVersion();
var isNode4OrLater = nodeVersion >= 4;
var platform = _os.platform();
var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
- var _b = createSystemWatchFunctions({
+ var getCurrentDirectory = ts.memoize(function () { return process.cwd(); });
+ var _c = createSystemWatchFunctions({
pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
getModifiedTime: getModifiedTime,
setTimeout: setTimeout,
clearTimeout: clearTimeout,
fsWatch: fsWatch,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
+ getCurrentDirectory: getCurrentDirectory,
fileExists: fileExists,
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
tscWatchFile: process.env.TSC_WATCHFILE,
useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
- }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory;
+ }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory;
var nodeSystem = {
args: process.argv.slice(2),
newLine: _os.EOL,
getExecutingFilePath: function () {
return __filename;
},
- getCurrentDirectory: function () {
- return process.cwd();
- },
+ getCurrentDirectory: getCurrentDirectory,
getDirectories: getDirectories,
getEnvironmentVariable: function (name) {
return process.env[name] || "";
},
getFileSize: function (path) {
try {
- var stat = _fs.statSync(path);
- if (stat.isFile()) {
+ var stat = statSync(path);
+ if (stat === null || stat === void 0 ? void 0 : stat.isFile()) {
return stat.size;
}
}
},
enableCPUProfiler: enableCPUProfiler,
disableCPUProfiler: disableCPUProfiler,
+ cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); },
realpath: realpath,
debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
tryEnableSourceMapsForHost: function () {
}
};
return nodeSystem;
+ /**
+ * `throwIfNoEntry` was added so recently that it's not in the node types.
+ * This helper encapsulates the mitigating usage of `any`.
+ * See https://github.com/nodejs/node/pull/33716
+ */
+ function statSync(path) {
+ // throwIfNoEntry will be ignored by older versions of node
+ return _fs.statSync(path, { throwIfNoEntry: false });
+ }
/**
* Uses the builtin inspector APIs to capture a CPU profile
* See https://nodejs.org/api/inspector.html#inspector_example_usage for details
if (activeSession && activeSession !== "stopping") {
var s_1 = activeSession;
activeSession.post("Profiler.stop", function (err, _a) {
+ var _b;
var profile = _a.profile;
if (!err) {
try {
- if (_fs.statSync(profilePath).isDirectory()) {
+ if ((_b = statSync(profilePath)) === null || _b === void 0 ? void 0 : _b.isDirectory()) {
profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile");
}
}
- catch (_b) {
+ catch (_c) {
// do nothing and ignore fallible fs operation
}
try {
_fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
}
- catch (_c) {
+ catch (_d) {
// do nothing and ignore fallible fs operation
}
_fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
return event === "rename" &&
(!relativeName ||
relativeName === lastDirectoryPart ||
- relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) &&
+ (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) &&
!fileSystemEntryExists(fileOrDirectory, entryKind) ?
invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
callback(event, relativeName);
if (typeof dirent === "string" || dirent.isSymbolicLink()) {
var name = ts.combinePaths(path, entry);
try {
- stat = _fs.statSync(name);
+ stat = statSync(name);
+ if (!stat) {
+ continue;
+ }
}
catch (e) {
continue;
var originalStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
try {
- var stat = _fs.statSync(path);
+ var stat = statSync(path);
+ if (!stat) {
+ return false;
+ }
switch (entryKind) {
case 0 /* File */: return stat.isFile();
case 1 /* Directory */: return stat.isDirectory();
}
function realpath(path) {
try {
- return _fs.realpathSync(path);
+ return realpathSync(path);
}
catch (_a) {
return path;
}
}
function getModifiedTime(path) {
+ var _a;
try {
- return _fs.statSync(path).mtime;
+ return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime;
}
catch (e) {
return undefined;
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."),
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."),
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."),
- 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."),
+ for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."),
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."),
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."),
Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
_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."),
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."),
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."),
- 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."),
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."),
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"),
Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module: diag(1262, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262", "Identifier expected. '{0}' is a reserved word at the top-level of a module."),
Declarations_with_initializers_cannot_also_have_definite_assignment_assertions: diag(1263, ts.DiagnosticCategory.Error, "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263", "Declarations with initializers cannot also have definite assignment assertions."),
Declarations_with_definite_assignment_assertions_must_also_have_type_annotations: diag(1264, ts.DiagnosticCategory.Error, "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264", "Declarations with definite assignment assertions must also have type annotations."),
+ A_rest_element_cannot_follow_another_rest_element: diag(1265, ts.DiagnosticCategory.Error, "A_rest_element_cannot_follow_another_rest_element_1265", "A rest element cannot follow another rest element."),
+ An_optional_element_cannot_follow_a_rest_element: diag(1266, ts.DiagnosticCategory.Error, "An_optional_element_cannot_follow_a_rest_element_1266", "An optional element cannot follow a rest element."),
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."),
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."),
Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern: diag(1312, ts.DiagnosticCategory.Error, "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312", "Did you mean to use a ':'? An '=' can only follow a property name when the containing object literal is part of a destructuring pattern."),
Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
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"),
Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
- 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'."),
- 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'."),
+ This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error: diag(1371, ts.DiagnosticCategory.Error, "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371", "This import is never used as a value and must use 'import type' because 'importsNotUsedAsValues' is set to 'error'."),
Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
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"),
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."),
Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1387, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387", "Function type notation must be parenthesized when used in an intersection type."),
Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."),
_0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."),
+ Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."),
+ The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."),
+ An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"),
+ Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"),
+ Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"),
+ Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions: diag(1395, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions_1395", "Imported via {0} from file '{1}' to import 'importHelpers' as specified in compilerOptions"),
+ Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions: diag(1396, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions_1396", "Imported via {0} from file '{1}' with packageId '{2}' to import 'importHelpers' as specified in compilerOptions"),
+ Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions: diag(1397, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions_1397", "Imported via {0} from file '{1}' to import 'jsx' and 'jsxs' factory functions"),
+ Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions: diag(1398, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions_1398", "Imported via {0} from file '{1}' with packageId '{2}' to import 'jsx' and 'jsxs' factory functions"),
+ File_is_included_via_import_here: diag(1399, ts.DiagnosticCategory.Message, "File_is_included_via_import_here_1399", "File is included via import here."),
+ Referenced_via_0_from_file_1: diag(1400, ts.DiagnosticCategory.Message, "Referenced_via_0_from_file_1_1400", "Referenced via '{0}' from file '{1}'"),
+ File_is_included_via_reference_here: diag(1401, ts.DiagnosticCategory.Message, "File_is_included_via_reference_here_1401", "File is included via reference here."),
+ Type_library_referenced_via_0_from_file_1: diag(1402, ts.DiagnosticCategory.Message, "Type_library_referenced_via_0_from_file_1_1402", "Type library referenced via '{0}' from file '{1}'"),
+ Type_library_referenced_via_0_from_file_1_with_packageId_2: diag(1403, ts.DiagnosticCategory.Message, "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403", "Type library referenced via '{0}' from file '{1}' with packageId '{2}'"),
+ File_is_included_via_type_library_reference_here: diag(1404, ts.DiagnosticCategory.Message, "File_is_included_via_type_library_reference_here_1404", "File is included via type library reference here."),
+ Library_referenced_via_0_from_file_1: diag(1405, ts.DiagnosticCategory.Message, "Library_referenced_via_0_from_file_1_1405", "Library referenced via '{0}' from file '{1}'"),
+ File_is_included_via_library_reference_here: diag(1406, ts.DiagnosticCategory.Message, "File_is_included_via_library_reference_here_1406", "File is included via library reference here."),
+ Matched_by_include_pattern_0_in_1: diag(1407, ts.DiagnosticCategory.Message, "Matched_by_include_pattern_0_in_1_1407", "Matched by include pattern '{0}' in '{1}'"),
+ File_is_matched_by_include_pattern_specified_here: diag(1408, ts.DiagnosticCategory.Message, "File_is_matched_by_include_pattern_specified_here_1408", "File is matched by include pattern specified here."),
+ Part_of_files_list_in_tsconfig_json: diag(1409, ts.DiagnosticCategory.Message, "Part_of_files_list_in_tsconfig_json_1409", "Part of 'files' list in tsconfig.json"),
+ File_is_matched_by_files_list_specified_here: diag(1410, ts.DiagnosticCategory.Message, "File_is_matched_by_files_list_specified_here_1410", "File is matched by 'files' list specified here."),
+ Output_from_referenced_project_0_included_because_1_specified: diag(1411, ts.DiagnosticCategory.Message, "Output_from_referenced_project_0_included_because_1_specified_1411", "Output from referenced project '{0}' included because '{1}' specified"),
+ Output_from_referenced_project_0_included_because_module_is_specified_as_none: diag(1412, ts.DiagnosticCategory.Message, "Output_from_referenced_project_0_included_because_module_is_specified_as_none_1412", "Output from referenced project '{0}' included because '--module' is specified as 'none'"),
+ File_is_output_from_referenced_project_specified_here: diag(1413, ts.DiagnosticCategory.Message, "File_is_output_from_referenced_project_specified_here_1413", "File is output from referenced project specified here."),
+ Source_from_referenced_project_0_included_because_1_specified: diag(1414, ts.DiagnosticCategory.Message, "Source_from_referenced_project_0_included_because_1_specified_1414", "Source from referenced project '{0}' included because '{1}' specified"),
+ Source_from_referenced_project_0_included_because_module_is_specified_as_none: diag(1415, ts.DiagnosticCategory.Message, "Source_from_referenced_project_0_included_because_module_is_specified_as_none_1415", "Source from referenced project '{0}' included because '--module' is specified as 'none'"),
+ File_is_source_from_referenced_project_specified_here: diag(1416, ts.DiagnosticCategory.Message, "File_is_source_from_referenced_project_specified_here_1416", "File is source from referenced project specified here."),
+ Entry_point_of_type_library_0_specified_in_compilerOptions: diag(1417, ts.DiagnosticCategory.Message, "Entry_point_of_type_library_0_specified_in_compilerOptions_1417", "Entry point of type library '{0}' specified in compilerOptions"),
+ Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1: diag(1418, ts.DiagnosticCategory.Message, "Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1_1418", "Entry point of type library '{0}' specified in compilerOptions with packageId '{1}'"),
+ File_is_entry_point_of_type_library_specified_here: diag(1419, ts.DiagnosticCategory.Message, "File_is_entry_point_of_type_library_specified_here_1419", "File is entry point of type library specified here."),
+ Entry_point_for_implicit_type_library_0: diag(1420, ts.DiagnosticCategory.Message, "Entry_point_for_implicit_type_library_0_1420", "Entry point for implicit type library '{0}'"),
+ Entry_point_for_implicit_type_library_0_with_packageId_1: diag(1421, ts.DiagnosticCategory.Message, "Entry_point_for_implicit_type_library_0_with_packageId_1_1421", "Entry point for implicit type library '{0}' with packageId '{1}'"),
+ Library_0_specified_in_compilerOptions: diag(1422, ts.DiagnosticCategory.Message, "Library_0_specified_in_compilerOptions_1422", "Library '{0}' specified in compilerOptions"),
+ File_is_library_specified_here: diag(1423, ts.DiagnosticCategory.Message, "File_is_library_specified_here_1423", "File is library specified here."),
+ Default_library: diag(1424, ts.DiagnosticCategory.Message, "Default_library_1424", "Default library"),
+ Default_library_for_target_0: diag(1425, ts.DiagnosticCategory.Message, "Default_library_for_target_0_1425", "Default library for target '{0}'"),
+ File_is_default_library_for_target_specified_here: diag(1426, ts.DiagnosticCategory.Message, "File_is_default_library_for_target_specified_here_1426", "File is default library for target specified here."),
+ Root_file_specified_for_compilation: diag(1427, ts.DiagnosticCategory.Message, "Root_file_specified_for_compilation_1427", "Root file specified for compilation"),
+ File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"),
+ File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"),
+ The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"),
+ for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."),
+ Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."),
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."),
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."),
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),
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."),
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."),
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'."),
- 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."),
+ The_right_hand_side_of_an_in_expression_must_not_be_a_primitive: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361", "The right-hand side of an 'in' expression must not be a primitive."),
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."),
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."),
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."),
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."),
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."),
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."),
- 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}'."),
+ Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead: diag(2576, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576", "Property '{0}' does not exist on type '{1}'. Did you mean to access the static member '{2}' instead?"),
Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."),
Source_has_0_element_s_but_target_allows_only_1: diag(2619, ts.DiagnosticCategory.Error, "Source_has_0_element_s_but_target_allows_only_1_2619", "Source has {0} element(s) but target allows only {1}."),
Target_requires_0_element_s_but_source_may_have_fewer: diag(2620, ts.DiagnosticCategory.Error, "Target_requires_0_element_s_but_source_may_have_fewer_2620", "Target requires {0} element(s) but source may have fewer."),
Target_allows_only_0_element_s_but_source_may_have_more: diag(2621, ts.DiagnosticCategory.Error, "Target_allows_only_0_element_s_but_source_may_have_more_2621", "Target allows only {0} element(s) but source may have more."),
- Element_at_index_0_is_variadic_in_one_type_but_not_in_the_other: diag(2622, ts.DiagnosticCategory.Error, "Element_at_index_0_is_variadic_in_one_type_but_not_in_the_other_2622", "Element at index {0} is variadic in one type but not in the other."),
+ Source_provides_no_match_for_required_element_at_position_0_in_target: diag(2623, ts.DiagnosticCategory.Error, "Source_provides_no_match_for_required_element_at_position_0_in_target_2623", "Source provides no match for required element at position {0} in target."),
+ Source_provides_no_match_for_variadic_element_at_position_0_in_target: diag(2624, ts.DiagnosticCategory.Error, "Source_provides_no_match_for_variadic_element_at_position_0_in_target_2624", "Source provides no match for variadic element at position {0} in target."),
+ Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target: diag(2625, ts.DiagnosticCategory.Error, "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625", "Variadic element at position {0} in source does not match element at position {1} in target."),
+ Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target: diag(2626, ts.DiagnosticCategory.Error, "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626", "Type at position {0} in source is not compatible with type at position {1} in target."),
+ Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target: diag(2627, ts.DiagnosticCategory.Error, "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627", "Type at positions {0} through {1} in source is not compatible with type at position {2} in target."),
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."),
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."),
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."),
Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise: diag(2794, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794", "Expected {0} arguments, but got {1}. Did you forget to include 'void' in your type argument to 'Promise'?"),
The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."),
It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."),
+ A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."),
+ The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."),
+ Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."),
+ Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."),
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}'."),
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}'."),
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}'."),
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}'."),
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}'."),
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}'."),
+ Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."),
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."),
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}'."),
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}'."),
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."),
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."),
Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
+ Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0: diag(4111, ts.DiagnosticCategory.Error, "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111", "Property '{0}' comes from an index signature, so it must be accessed with ['{0}']."),
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."),
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."),
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}'."),
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."),
Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."),
Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"),
+ Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."),
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."),
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."),
Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
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."),
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."),
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."),
- 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'."),
+ Specify_JSX_code_generation_Colon_preserve_react_native_react_react_jsx_or_react_jsxdev: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_react_react_jsx_or_react_jsxdev_6080", "Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'."),
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."),
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}."),
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."),
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"),
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"),
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."),
- _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true),
+ _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true),
Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."),
+ The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true),
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}'"),
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."),
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."),
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."),
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?"),
+ Print_names_of_files_and_the_reason_they_are_part_of_the_compilation: diag(6505, ts.DiagnosticCategory.Message, "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505", "Print names of files and the reason they are part of the compilation."),
+ Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6803, ts.DiagnosticCategory.Error, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803", "Require undeclared properties from index signatures to use element accesses."),
Include_undefined_in_index_signature_results: diag(6800, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6800", "Include 'undefined' in index signature results"),
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."),
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."),
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}'."),
_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."),
The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed: diag(7056, ts.DiagnosticCategory.Error, "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056", "The inferred type of this node exceeds the maximum length the compiler will serialize. An explicit type annotation is needed."),
+ yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation: diag(7057, ts.DiagnosticCategory.Error, "yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057", "'yield' expression implicitly results in an 'any' type because its containing generator lacks a return-type annotation."),
You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
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."),
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."),
Can_only_convert_logical_AND_access_chains: diag(95142, ts.DiagnosticCategory.Message, "Can_only_convert_logical_AND_access_chains_95142", "Can only convert logical AND access chains"),
Add_void_to_Promise_resolved_without_a_value: diag(95143, ts.DiagnosticCategory.Message, "Add_void_to_Promise_resolved_without_a_value_95143", "Add 'void' to Promise resolved without a value"),
Add_void_to_all_Promises_resolved_without_a_value: diag(95144, ts.DiagnosticCategory.Message, "Add_void_to_all_Promises_resolved_without_a_value_95144", "Add 'void' to all Promises resolved without a value"),
+ Use_element_access_for_0: diag(95145, ts.DiagnosticCategory.Message, "Use_element_access_for_0_95145", "Use element access for '{0}'"),
+ Use_element_access_for_all_undeclared_properties: diag(95146, ts.DiagnosticCategory.Message, "Use_element_access_for_all_undeclared_properties_95146", "Use element access for all undeclared properties."),
+ Delete_all_unused_imports: diag(95147, ts.DiagnosticCategory.Message, "Delete_all_unused_imports_95147", "Delete all unused imports"),
+ Infer_function_return_type: diag(95148, ts.DiagnosticCategory.Message, "Infer_function_return_type_95148", "Infer function return type"),
+ Return_type_must_be_inferred_from_a_function: diag(95149, ts.DiagnosticCategory.Message, "Return_type_must_be_inferred_from_a_function_95149", "Return type must be inferred from a function"),
+ Could_not_determine_function_return_type: diag(95150, ts.DiagnosticCategory.Message, "Could_not_determine_function_return_type_95150", "Could not determine function return type"),
+ Could_not_convert_to_arrow_function: diag(95151, ts.DiagnosticCategory.Message, "Could_not_convert_to_arrow_function_95151", "Could not convert to arrow function"),
+ Could_not_convert_to_named_function: diag(95152, ts.DiagnosticCategory.Message, "Could_not_convert_to_named_function_95152", "Could not convert to named function"),
+ Could_not_convert_to_anonymous_function: diag(95153, ts.DiagnosticCategory.Message, "Could_not_convert_to_anonymous_function_95153", "Could not convert to anonymous function"),
+ Can_only_convert_string_concatenation: diag(95154, ts.DiagnosticCategory.Message, "Can_only_convert_string_concatenation_95154", "Can only convert string concatenation"),
+ Selection_is_not_a_valid_statement_or_statements: diag(95155, ts.DiagnosticCategory.Message, "Selection_is_not_a_valid_statement_or_statements_95155", "Selection is not a valid statement or statements"),
+ Add_missing_function_declaration_0: diag(95156, ts.DiagnosticCategory.Message, "Add_missing_function_declaration_0_95156", "Add missing function declaration '{0}'"),
+ Add_all_missing_function_declarations: diag(95157, ts.DiagnosticCategory.Message, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"),
+ Method_not_implemented: diag(95158, ts.DiagnosticCategory.Message, "Method_not_implemented_95158", "Method not implemented."),
+ Function_not_implemented: diag(95159, ts.DiagnosticCategory.Message, "Function_not_implemented_95159", "Function not implemented."),
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."),
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'."),
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?"),
reScanJsxToken: reScanJsxToken,
reScanLessThanToken: reScanLessThanToken,
reScanQuestionToken: reScanQuestionToken,
+ reScanInvalidIdentifier: reScanInvalidIdentifier,
scanJsxToken: scanJsxToken,
scanJsDocToken: scanJsDocToken,
scan: scan,
}
return token = 79 /* PrivateIdentifier */;
default:
- if (isIdentifierStart(ch, languageVersion)) {
- pos += charSize(ch);
- while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
- pos += charSize(ch);
- tokenValue = text.substring(tokenPos, pos);
- if (ch === 92 /* backslash */) {
- tokenValue += scanIdentifierParts();
- }
- return token = getIdentifierToken();
+ var identifierKind = scanIdentifier(ch, languageVersion);
+ if (identifierKind) {
+ return token = identifierKind;
}
else if (isWhiteSpaceSingleLine(ch)) {
pos += charSize(ch);
}
}
}
+ function reScanInvalidIdentifier() {
+ ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'.");
+ pos = tokenPos = startPos;
+ tokenFlags = 0;
+ var ch = codePointAt(text, pos);
+ var identifierKind = scanIdentifier(ch, 99 /* ESNext */);
+ if (identifierKind) {
+ return token = identifierKind;
+ }
+ pos += charSize(ch);
+ return token; // Still `SyntaKind.Unknown`
+ }
+ function scanIdentifier(startCharacter, languageVersion) {
+ var ch = startCharacter;
+ if (isIdentifierStart(ch, languageVersion)) {
+ pos += charSize(ch);
+ while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
+ pos += charSize(ch);
+ tokenValue = text.substring(tokenPos, pos);
+ if (ch === 92 /* backslash */) {
+ tokenValue += scanIdentifierParts();
+ }
+ return getIdentifierToken();
+ }
+ }
function reScanGreaterToken() {
if (token === 31 /* GreaterThanToken */) {
if (text.charCodeAt(pos) === 62 /* greaterThan */) {
// they allow dashes
function scanJsxIdentifier() {
if (tokenIsIdentifierOrKeyword(token)) {
- // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
+ // An identifier or keyword has already been parsed - check for a `-` or a single instance of `:` and then append it and
+ // everything after it to the token
// Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
// Any caller should be expecting this behavior and should only read the pos or token value after calling it.
+ var namespaceSeparator = false;
while (pos < end) {
var ch = text.charCodeAt(pos);
if (ch === 45 /* minus */) {
pos++;
continue;
}
+ else if (ch === 58 /* colon */ && !namespaceSeparator) {
+ tokenValue += ":";
+ pos++;
+ namespaceSeparator = true;
+ continue;
+ }
var oldPos = pos;
tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
if (pos === oldPos) {
break;
}
}
+ // Do not include a trailing namespace separator in the token, since this is against the spec.
+ if (tokenValue.slice(-1) === ":") {
+ tokenValue = tokenValue.slice(0, -1);
+ pos--;
+ }
}
return token;
}
// nodes like variable declarations and binding elements can returned a view of their flags
// that includes the modifiers from their container. i.e. flags like export/declare aren't
// stored on the variable declaration directly, but on the containing variable statement
- // (if it has one). Similarly, flags for let/const are store on the variable declaration
+ // (if it has one). Similarly, flags for let/const are stored on the variable declaration
// list. By calling this function, all those flags are combined so that the client can treat
// the node as if it actually had those flags.
function getCombinedNodeFlags(node) {
return getCombinedFlags(node, function (n) { return n.flags; });
}
ts.getCombinedNodeFlags = getCombinedNodeFlags;
+ /* @internal */
+ ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"];
/**
* Checks to see if the locale is in the appropriate format,
* and if it is, attempts to set the appropriate language.
*/
function validateLocaleAndSetLanguage(locale, sys, errors) {
- var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
+ var lowerCaseLocale = locale.toLowerCase();
+ var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale);
if (!matchResult) {
if (errors) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
var territory = matchResult[3];
// First try the entire locale, then fall back to just language if that's all we have.
// Either ways do not fail, and fallback to the English diagnostic strings.
- if (!trySetLanguageAndTerritory(language, territory, errors)) {
+ if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) {
trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
}
// Set the UI locale for string collation
case 263 /* NamespaceImport */:
return node.parent.isTypeOnly;
case 262 /* ImportClause */:
+ case 260 /* ImportEqualsDeclaration */:
return node.isTypeOnly;
default:
return false;
break;
}
}
- to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
+ to.splice.apply(to, __spreadArray([statementIndex, 0], from));
return to;
}
function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
GetLiteralTextFlags[GetLiteralTextFlags["NeverAsciiEscape"] = 1] = "NeverAsciiEscape";
GetLiteralTextFlags[GetLiteralTextFlags["JsxAttributeEscape"] = 2] = "JsxAttributeEscape";
GetLiteralTextFlags[GetLiteralTextFlags["TerminateUnterminatedLiterals"] = 4] = "TerminateUnterminatedLiterals";
+ GetLiteralTextFlags[GetLiteralTextFlags["AllowNumericSeparator"] = 8] = "AllowNumericSeparator";
})(GetLiteralTextFlags = ts.GetLiteralTextFlags || (ts.GetLiteralTextFlags = {}));
function getLiteralText(node, sourceFile, flags) {
// If we don't need to downlevel and we can reach the original source text using
// the node's parent reference, then simply get the text as it was originally written.
- if (!nodeIsSynthesized(node) && node.parent && !(flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
- ts.isBigIntLiteral(node))) {
+ if (canUseOriginalText(node, flags)) {
return getSourceTextOfNodeFromSourceFile(sourceFile, node);
}
// If we can't reach the original source text, use the canonical form if it's a number,
return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
}
ts.getLiteralText = getLiteralText;
+ function canUseOriginalText(node, flags) {
+ if (nodeIsSynthesized(node) || !node.parent || (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated)) {
+ return false;
+ }
+ if (ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) {
+ return !!(flags & 8 /* AllowNumericSeparator */);
+ }
+ return !ts.isBigIntLiteral(node);
+ }
function getTextOfConstantValue(value) {
return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
}
}
}
ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
+ function hasPossibleExternalModuleReference(node) {
+ return isAnyImportOrReExport(node) || ts.isModuleDeclaration(node) || ts.isImportTypeNode(node) || isImportCall(node);
+ }
+ ts.hasPossibleExternalModuleReference = hasPossibleExternalModuleReference;
function isAnyImportOrReExport(node) {
return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
}
function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
var sourceFile = getSourceFileOfNode(node);
var span = getErrorSpanForNode(sourceFile, node);
+ return createFileDiagnosticFromMessageChain(sourceFile, span.start, span.length, messageChain, relatedInformation);
+ }
+ ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
+ function assertDiagnosticLocation(file, start, length) {
+ ts.Debug.assertGreaterThanOrEqual(start, 0);
+ ts.Debug.assertGreaterThanOrEqual(length, 0);
+ if (file) {
+ ts.Debug.assertLessThanOrEqual(start, file.text.length);
+ ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
+ }
+ }
+ function createFileDiagnosticFromMessageChain(file, start, length, messageChain, relatedInformation) {
+ assertDiagnosticLocation(file, start, length);
return {
- file: sourceFile,
- start: span.start,
- length: span.length,
+ file: file,
+ start: start,
+ length: length,
code: messageChain.code,
category: messageChain.category,
messageText: messageChain.next ? messageChain : messageChain.messageText,
relatedInformation: relatedInformation
};
}
- ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
+ ts.createFileDiagnosticFromMessageChain = createFileDiagnosticFromMessageChain;
function createDiagnosticForFileFromMessageChain(sourceFile, messageChain, relatedInformation) {
return {
file: sourceFile,
});
}
ts.getPropertyAssignment = getPropertyAssignment;
+ function getPropertyArrayElementValue(objectLiteral, propKey, elementValue) {
+ return ts.firstDefined(getPropertyAssignment(objectLiteral, propKey), function (property) {
+ return ts.isArrayLiteralExpression(property.initializer) ?
+ ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
+ undefined;
+ });
+ }
+ ts.getPropertyArrayElementValue = getPropertyArrayElementValue;
function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
var expression = tsConfigSourceFile.statements[0].expression;
return node.moduleReference.kind === 272 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
case 195 /* ImportType */:
return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
+ case 203 /* CallExpression */:
+ return node.arguments[0];
+ case 256 /* ModuleDeclaration */:
+ return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined;
default:
return ts.Debug.assertNever(node);
}
return parent.parent.parent;
}
}
+ ts.getNextJSDocCommentLocation = getNextJSDocCommentLocation;
/** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
function getParameterSymbolFromJSDoc(node) {
if (node.symbol) {
ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
function getEffectiveJSDocHost(node) {
var host = getJSDocHost(node);
- var decl = getSourceOfDefaultedAssignment(host) ||
- getSourceOfAssignment(host) ||
- getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
- getSingleVariableOfVariableStatement(host) ||
- getNestedModuleDeclaration(host) ||
- host;
- return decl;
+ if (host) {
+ return getSourceOfDefaultedAssignment(host)
+ || getSourceOfAssignment(host)
+ || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host)
+ || getSingleVariableOfVariableStatement(host)
+ || getNestedModuleDeclaration(host)
+ || host;
+ }
}
ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
- /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */
+ /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */
function getJSDocHost(node) {
- return ts.Debug.checkDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
+ var jsDoc = getJSDocRoot(node);
+ if (!jsDoc) {
+ return undefined;
+ }
+ var host = jsDoc.parent;
+ if (host && host.jsDoc && jsDoc === ts.lastOrUndefined(host.jsDoc)) {
+ return host;
+ }
}
ts.getJSDocHost = getJSDocHost;
+ function getJSDocRoot(node) {
+ return ts.findAncestor(node.parent, ts.isJSDoc);
+ }
+ ts.getJSDocRoot = getJSDocRoot;
function getTypeParameterFromJsDoc(node) {
var name = node.name.escapedText;
var typeParameters = node.parent.parent.parent.typeParameters;
return getBinaryOperatorPrecedence(operatorKind);
}
// TODO: Should prefix `++` and `--` be moved to the `Update` precedence?
- // TODO: We are missing `TypeAssertionExpression`
+ case 206 /* TypeAssertionExpression */:
+ case 225 /* NonNullExpression */:
case 214 /* PrefixUnaryExpression */:
case 211 /* TypeOfExpression */:
case 212 /* VoidExpression */:
case 201 /* PropertyAccessExpression */:
case 202 /* ElementAccessExpression */:
return 19 /* Member */;
+ case 224 /* AsExpression */:
+ return 11 /* Relational */;
case 107 /* ThisKeyword */:
case 105 /* SuperKeyword */:
case 78 /* Identifier */:
lookup: lookup,
getGlobalDiagnostics: getGlobalDiagnostics,
getDiagnostics: getDiagnostics,
- reattachFileDiagnostics: reattachFileDiagnostics
};
- function reattachFileDiagnostics(newFile) {
- ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
- }
function lookup(diagnostic) {
var diagnostics;
if (diagnostic.file) {
}
function isIntrinsicJsxName(name) {
var ch = name.charCodeAt(0);
- return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
+ return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-") || ts.stringContains(name, ":");
}
ts.isIntrinsicJsxName = isIntrinsicJsxName;
var indentStrings = ["", " "];
return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
}
ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
+ function getCanonicalAbsolutePath(host, path) {
+ return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory()));
+ }
function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
var file = resolver.getExternalModuleFileFromDeclaration(declaration);
if (!file || file.isDeclarationFile) {
return undefined;
}
+ // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it
+ var specifier = getExternalModuleName(declaration);
+ if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) &&
+ getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) {
+ return undefined;
+ }
return getResolvedExternalModuleName(host, file);
}
ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
return baseStr + "." + entityNameToString(expr.name);
}
}
+ else if (ts.isElementAccessExpression(expr)) {
+ var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
+ if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) {
+ return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression);
+ }
+ }
else if (ts.isIdentifier(expr)) {
return ts.unescapeLeadingUnderscores(expr.escapedText);
}
});
}
ts.mutateMap = mutateMap;
- // Return true if the given type is the constructor type for an abstract class
- function isAbstractConstructorType(type) {
- return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
- }
- ts.isAbstractConstructorType = isAbstractConstructorType;
function isAbstractConstructorSymbol(symbol) {
if (symbol.flags & 32 /* Class */) {
var declaration = getClassLikeDeclarationOfSymbol(symbol);
}
function Type(checker, flags) {
this.flags = flags;
- if (ts.Debug.isDebugging || ts.tracing.isTracing()) {
+ if (ts.Debug.isDebugging || ts.tracing) {
this.checker = checker;
}
}
}
ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
function createDetachedDiagnostic(fileName, start, length, message) {
- ts.Debug.assertGreaterThanOrEqual(start, 0);
- ts.Debug.assertGreaterThanOrEqual(length, 0);
+ assertDiagnosticLocation(/*file*/ undefined, start, length);
var text = getLocaleSpecificMessage(message);
if (arguments.length > 4) {
text = formatStringFromArgs(text, arguments, 4);
}
ts.attachFileToDiagnostics = attachFileToDiagnostics;
function createFileDiagnostic(file, start, length, message) {
- ts.Debug.assertGreaterThanOrEqual(start, 0);
- ts.Debug.assertGreaterThanOrEqual(length, 0);
- if (file) {
- ts.Debug.assertLessThanOrEqual(start, file.text.length);
- ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
- }
+ assertDiagnosticLocation(file, start, length);
var text = getLocaleSpecificMessage(message);
if (arguments.length > 4) {
text = formatStringFromArgs(text, arguments, 4);
};
}
ts.createCompilerDiagnostic = createCompilerDiagnostic;
- function createCompilerDiagnosticFromMessageChain(chain) {
+ function createCompilerDiagnosticFromMessageChain(chain, relatedInformation) {
return {
file: undefined,
start: undefined,
code: chain.code,
category: chain.category,
messageText: chain.next ? chain : chain.messageText,
+ relatedInformation: relatedInformation
};
}
ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function shouldPreserveConstEnums(compilerOptions) {
+ return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules);
+ }
+ ts.shouldPreserveConstEnums = shouldPreserveConstEnums;
function isIncrementalCompilation(options) {
return !!(options.incremental || options.composite);
}
return true;
}
ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
- function createSymlinkCache() {
+ function createSymlinkCache(cwd, getCanonicalFileName) {
var symlinkedDirectories;
+ var symlinkedDirectoriesByRealpath;
var symlinkedFiles;
return {
getSymlinkedFiles: function () { return symlinkedFiles; },
getSymlinkedDirectories: function () { return symlinkedDirectories; },
+ getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; },
setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); },
- setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); },
+ setSymlinkedDirectory: function (symlink, real) {
+ // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks
+ // where both the realpath and the symlink path are inside node_modules/.pnpm. Since
+ // this path is never a candidate for a module specifier, we can ignore it entirely.
+ var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName);
+ if (!containsIgnoredPath(symlinkPath)) {
+ symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath);
+ if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) {
+ (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink);
+ }
+ (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real);
+ }
+ }
};
}
ts.createSymlinkCache = createSymlinkCache;
function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
- var cache = createSymlinkCache();
+ var cache = createSymlinkCache(cwd, getCanonicalFileName);
var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1];
if (commonResolved && commonOriginal) {
- cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) });
+ cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) });
}
}
return cache;
}
ts.discoverProbableSymlinks = discoverProbableSymlinks;
function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
- var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
- var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
+ var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd));
+ var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd));
var isDirectory = false;
while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
!isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
return !/[.*?]/.test(lastPathComponent);
}
ts.isImplicitGlob = isImplicitGlob;
+ function getPatternFromSpec(spec, basePath, usage) {
+ var pattern = spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
+ return pattern && "^(" + pattern + ")" + (usage === "exclude" ? "($|/)" : "$");
+ }
+ ts.getPatternFromSpec = getPatternFromSpec;
function getSubPatternFromSpec(spec, basePath, usage, _a) {
var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
var subpattern = "";
ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
- var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
- var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
+ var allSupportedExtensions = __spreadArray(__spreadArray([], ts.supportedTSExtensions), ts.supportedJSExtensions);
+ var allSupportedExtensionsWithJson = __spreadArray(__spreadArray(__spreadArray([], ts.supportedTSExtensions), ts.supportedJSExtensions), [".json" /* Json */]);
function getSupportedExtensions(options, extraFileExtensions) {
var needJsExtensions = options && getAllowJSCompilerOption(options);
if (!extraFileExtensions || extraFileExtensions.length === 0) {
return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
}
- var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
+ var extensions = __spreadArray(__spreadArray([], needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions), ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
}
ts.getSupportedExtensions = getSupportedExtensions;
if (supportedExtensions === ts.supportedTSExtensions) {
return ts.supportedTSExtensionsWithJson;
}
- return __spreadArrays(supportedExtensions, [".json" /* Json */]);
+ return __spreadArray(__spreadArray([], supportedExtensions), [".json" /* Json */]);
}
ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
function isJSLike(scriptKind) {
return false;
}
ts.isSupportedSourceFileName = isSupportedSourceFileName;
+ function numberOfDirectorySeparators(str) {
+ var match = str.match(/\//g);
+ return match ? match.length : 0;
+ }
+ function compareNumberOfDirectorySeparators(path1, path2) {
+ return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2));
+ }
+ ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators;
/**
* Extension boundaries by priority. Lower numbers indicate higher priorities, and are
* aligned to the offset of the highest priority extension in the
return { pos: getTokenPosOfNode(node), end: node.end };
}
ts.rangeOfNode = rangeOfNode;
- function rangeOfTypeParameters(typeParameters) {
+ function rangeOfTypeParameters(sourceFile, typeParameters) {
// Include the `<>`
- return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
+ var pos = typeParameters.pos - 1;
+ var end = ts.skipTrivia(sourceFile.text, typeParameters.end) + 1;
+ return { pos: pos, end: end };
}
ts.rangeOfTypeParameters = rangeOfTypeParameters;
function skipTypeChecking(sourceFile, options, host) {
}
}
ts.setParentRecursive = setParentRecursive;
+ function isPackedElement(node) {
+ return !ts.isOmittedExpression(node);
+ }
+ /**
+ * Determines whether the provided node is an ArrayLiteralExpression that contains no missing elements.
+ */
+ function isPackedArrayLiteral(node) {
+ return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
+ }
+ ts.isPackedArrayLiteral = isPackedArrayLiteral;
+ /**
+ * Indicates whether the result of an `Expression` will be unused.
+ *
+ * NOTE: This requires a node with a valid `parent` pointer.
+ */
+ function expressionResultIsUnused(node) {
+ ts.Debug.assertIsDefined(node.parent);
+ while (true) {
+ var parent = node.parent;
+ // walk up parenthesized expressions, but keep a pointer to the top-most parenthesized expression
+ if (ts.isParenthesizedExpression(parent)) {
+ node = parent;
+ continue;
+ }
+ // result is unused in an expression statement, `void` expression, or the initializer or incrementer of a `for` loop
+ if (ts.isExpressionStatement(parent) ||
+ ts.isVoidExpression(parent) ||
+ ts.isForStatement(parent) && (parent.initializer === node || parent.incrementor === node)) {
+ return true;
+ }
+ if (ts.isCommaListExpression(parent)) {
+ // left side of comma is always unused
+ if (node !== ts.last(parent.elements))
+ return true;
+ // right side of comma is unused if parent is unused
+ node = parent;
+ continue;
+ }
+ if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 27 /* CommaToken */) {
+ // left side of comma is always unused
+ if (node === parent.left)
+ return true;
+ // right side of comma is unused if parent is unused
+ node = parent;
+ continue;
+ }
+ return false;
+ }
+ }
+ ts.expressionResultIsUnused = expressionResultIsUnused;
+ function containsIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); });
+ }
+ ts.containsIgnoredPath = containsIgnoredPath;
})(ts || (ts = {}));
/* @internal */
var ts;
: node;
}
// @api
- function createConstructorTypeNode(typeParameters, parameters, type) {
+ function createConstructorTypeNode() {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ return args.length === 4 ? createConstructorTypeNode1.apply(void 0, args) :
+ args.length === 3 ? createConstructorTypeNode2.apply(void 0, args) :
+ ts.Debug.fail("Incorrect number of arguments specified.");
+ }
+ function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) {
var node = createBaseSignatureDeclaration(175 /* ConstructorType */,
- /*decorators*/ undefined,
- /*modifiers*/ undefined,
+ /*decorators*/ undefined, modifiers,
/*name*/ undefined, typeParameters, parameters, type);
node.transformFlags = 1 /* ContainsTypeScript */;
return node;
}
+ /** @deprecated */
+ function createConstructorTypeNode2(typeParameters, parameters, type) {
+ return createConstructorTypeNode1(/*modifiers*/ undefined, typeParameters, parameters, type);
+ }
// @api
- function updateConstructorTypeNode(node, typeParameters, parameters, type) {
- return node.typeParameters !== typeParameters
+ function updateConstructorTypeNode() {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ return args.length === 5 ? updateConstructorTypeNode1.apply(void 0, args) :
+ args.length === 4 ? updateConstructorTypeNode2.apply(void 0, args) :
+ ts.Debug.fail("Incorrect number of arguments specified.");
+ }
+ function updateConstructorTypeNode1(node, modifiers, typeParameters, parameters, type) {
+ return node.modifiers !== modifiers
+ || node.typeParameters !== typeParameters
|| node.parameters !== parameters
|| node.type !== type
- ? updateBaseSignatureDeclaration(createConstructorTypeNode(typeParameters, parameters, type), node)
+ ? updateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node)
: node;
}
+ /** @deprecated */
+ function updateConstructorTypeNode2(node, typeParameters, parameters, type) {
+ return updateConstructorTypeNode1(node, node.modifiers, typeParameters, parameters, type);
+ }
// @api
function createTypeQueryNode(exprName) {
var node = createBaseNode(176 /* TypeQuery */);
: node;
}
// @api
- function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
+ function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) {
var node = createBaseNamedDeclaration(260 /* ImportEqualsDeclaration */, decorators, modifiers, name);
+ node.isTypeOnly = isTypeOnly;
node.moduleReference = moduleReference;
node.transformFlags |= propagateChildFlags(node.moduleReference);
if (!ts.isExternalModuleReference(node.moduleReference))
return node;
}
// @api
- function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
+ function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
+ || node.isTypeOnly !== isTypeOnly
|| node.name !== name
|| node.moduleReference !== moduleReference
- ? update(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
+ ? update(createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference), node)
: node;
}
// @api
/*typeArguments*/ undefined, argumentsList);
}
function createFunctionBindCall(target, thisArg, argumentsList) {
- return createMethodCall(target, "bind", __spreadArrays([thisArg], argumentsList));
+ return createMethodCall(target, "bind", __spreadArray([thisArg], argumentsList));
}
function createFunctionCallCall(target, thisArg, argumentsList) {
- return createMethodCall(target, "call", __spreadArrays([thisArg], argumentsList));
+ return createMethodCall(target, "call", __spreadArray([thisArg], argumentsList));
}
function createFunctionApplyCall(target, thisArg, argumentsExpression) {
return createMethodCall(target, "apply", [thisArg, argumentsExpression]);
function ensureUseStrict(statements) {
var foundUseStrict = ts.findUseStrictPrologue(statements);
if (!foundUseStrict) {
- return ts.setTextRange(createNodeArray(__spreadArrays([createUseStrictPrologue()], statements)), statements);
+ return ts.setTextRange(createNodeArray(__spreadArray([createUseStrictPrologue()], statements)), statements);
}
return statements;
}
var left = ts.isNodeArray(statements) ? statements.slice() : statements;
// splice other custom prologues from right into left
if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
- left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
+ left.splice.apply(left, __spreadArray([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
}
// splice hoisted variables from right into left
if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
- left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
+ left.splice.apply(left, __spreadArray([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
}
// splice hoisted functions from right into left
if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
- left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
+ left.splice.apply(left, __spreadArray([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
}
// splice standard prologues from right into left (that are not already in left)
if (rightStandardPrologueEnd > 0) {
if (leftStandardPrologueEnd === 0) {
- left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
+ left.splice.apply(left, __spreadArray([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
}
else {
var leftPrologues = new ts.Map();
ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.type) :
ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifiers, node.name, node.members) :
ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifiers, node.name, node.body) :
- ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifiers, node.name, node.moduleReference) :
+ ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.name, node.moduleReference) :
ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifiers, node.importClause, node.moduleSpecifier) :
ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifiers, node.expression) :
ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.exportClause, node.moduleSpecifier) :
// ES2015 Helpers
createExtendsHelper: createExtendsHelper,
createTemplateObjectHelper: createTemplateObjectHelper,
- createSpreadHelper: createSpreadHelper,
- createSpreadArraysHelper: createSpreadArraysHelper,
+ createSpreadArrayHelper: createSpreadArrayHelper,
// ES2015 Destructuring Helpers
createValuesHelper: createValuesHelper,
createReadHelper: createReadHelper,
return factory.createCallExpression(getUnscopedHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [cooked, raw]);
}
- function createSpreadHelper(argumentList) {
- context.requestEmitHelper(ts.readHelper);
- context.requestEmitHelper(ts.spreadHelper);
- return factory.createCallExpression(getUnscopedHelperName("__spread"),
- /*typeArguments*/ undefined, argumentList);
- }
- function createSpreadArraysHelper(argumentList) {
- context.requestEmitHelper(ts.spreadArraysHelper);
- return factory.createCallExpression(getUnscopedHelperName("__spreadArrays"),
- /*typeArguments*/ undefined, argumentList);
+ function createSpreadArrayHelper(to, from) {
+ context.requestEmitHelper(ts.spreadArrayHelper);
+ return factory.createCallExpression(getUnscopedHelperName("__spreadArray"),
+ /*typeArguments*/ undefined, [to, from]);
}
// ES2015 Destructuring Helpers
function createValuesHelper(expression) {
function createCreateBindingHelper(module, inputName, outputName) {
context.requestEmitHelper(ts.createBindingHelper);
return factory.createCallExpression(getUnscopedHelperName("__createBinding"),
- /*typeArguments*/ undefined, __spreadArrays([factory.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
+ /*typeArguments*/ undefined, __spreadArray([factory.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
}
function createImportStarHelper(expression) {
context.requestEmitHelper(ts.importStarHelper);
importName: "__extends",
scoped: false,
priority: 0,
- text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
+ text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
};
ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
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 };"
};
- ts.spreadHelper = {
- name: "typescript:spread",
- importName: "__spread",
- scoped: false,
- dependencies: [ts.readHelper],
- 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 };"
- };
- ts.spreadArraysHelper = {
- name: "typescript:spreadArrays",
- importName: "__spreadArrays",
+ ts.spreadArrayHelper = {
+ name: "typescript:spreadArray",
+ importName: "__spreadArray",
scoped: false,
- 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 };"
+ text: "\n var __spreadArray = (this && this.__spreadArray) || function (to, from) {\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\n to[j] = from[i];\n return to;\n };"
};
// ES2015 Destructuring Helpers
ts.valuesHelper = {
ts.awaiterHelper,
ts.extendsHelper,
ts.templateObjectHelper,
- ts.spreadHelper,
- ts.spreadArraysHelper,
+ ts.spreadArrayHelper,
ts.valuesHelper,
ts.readHelper,
ts.generatorHelper,
scoped: true,
text: helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex")
};
+ function isCallToHelper(firstSegment, helperName) {
+ return ts.isCallExpression(firstSegment)
+ && ts.isIdentifier(firstSegment.expression)
+ && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
+ && firstSegment.expression.escapedText === helperName;
+ }
+ ts.isCallToHelper = isCallToHelper;
})(ts || (ts = {}));
var ts;
(function (ts) {
return node.kind === 318 /* JSDocDeprecatedTag */;
}
ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag;
+ function isJSDocSeeTag(node) {
+ return node.kind === 332 /* JSDocSeeTag */;
+ }
+ ts.isJSDocSeeTag = isJSDocSeeTag;
function isJSDocEnumTag(node) {
return node.kind === 325 /* JSDocEnumTag */;
}
ts.createForOfBindingStatement = createForOfBindingStatement;
function insertLeadingStatement(factory, dest, source) {
if (ts.isBlock(dest)) {
- return factory.updateBlock(dest, ts.setTextRange(factory.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
+ return factory.updateBlock(dest, ts.setTextRange(factory.createNodeArray(__spreadArray([source], dest.statements)), dest.statements));
}
else {
return factory.createBlock(factory.createNodeArray([dest, source]), /*multiLine*/ true);
* Otherwise, a new StringLiteral node representing the module name will be returned.
*/
function getExternalModuleNameLiteral(factory, importNode, sourceFile, host, resolver, compilerOptions) {
- var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
- if (moduleName.kind === 10 /* StringLiteral */) {
+ var moduleName = ts.getExternalModuleName(importNode);
+ if (moduleName && ts.isStringLiteral(moduleName)) {
return tryGetModuleNameFromDeclaration(importNode, host, factory, resolver, compilerOptions)
|| tryRenameExternalModule(factory, moduleName, sourceFile)
|| factory.cloneNode(moduleName);
*/
function tryRenameExternalModule(factory, moduleName, sourceFile) {
var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
- return rename && factory.createStringLiteral(rename);
+ return rename ? factory.createStringLiteral(rename) : undefined;
}
/**
* Get the name of a module as should be written in the emitted output.
var PrivateIdentifierConstructor;
var SourceFileConstructor;
/**
- * NOTE: You should not use this, it is only exported to support `createNode` in `~/src/compat/deprecations.ts`.
+ * NOTE: You should not use this, it is only exported to support `createNode` in `~/src/deprecatedCompat/deprecations.ts`.
*/
/* @internal */
ts.parseBaseNodeFactory = {
* and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
*/
function forEachChildRecursively(rootNode, cbNode, cbNodes) {
- var stack = [rootNode];
- while (stack.length) {
- var parent = stack.pop();
- var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent));
- if (res) {
- return res;
- }
- }
- return;
- function gatherPossibleChildren(node) {
- var children = [];
- forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
- return children;
- function addWorkItem(n) {
- children.unshift(n);
- }
- }
- function visitAllPossibleChildren(parent, children) {
- for (var _i = 0, children_5 = children; _i < children_5.length; _i++) {
- var child = children_5[_i];
- if (ts.isArray(child)) {
- if (cbNodes) {
- var res = cbNodes(child, parent);
- if (res) {
- if (res === "skip")
- continue;
- return res;
- }
- }
- for (var i = child.length - 1; i >= 0; i--) {
- var realChild = child[i];
- var res = cbNode(realChild, parent);
- if (res) {
- if (res === "skip")
- continue;
- return res;
- }
- stack.push(realChild);
- }
- }
- else {
- stack.push(child);
- var res = cbNode(child, parent);
+ var queue = gatherPossibleChildren(rootNode);
+ var parents = []; // tracks parent references for elements in queue
+ while (parents.length < queue.length) {
+ parents.push(rootNode);
+ }
+ while (queue.length !== 0) {
+ var current = queue.pop();
+ var parent = parents.pop();
+ if (ts.isArray(current)) {
+ if (cbNodes) {
+ var res = cbNodes(current, parent);
if (res) {
if (res === "skip")
continue;
return res;
}
}
+ for (var i = current.length - 1; i >= 0; --i) {
+ queue.push(current[i]);
+ parents.push(parent);
+ }
+ }
+ else {
+ var res = cbNode(current, parent);
+ if (res) {
+ if (res === "skip")
+ continue;
+ return res;
+ }
+ if (current.kind >= 157 /* FirstNode */) {
+ // add children in reverse order to the queue, so popping gives the first child
+ for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) {
+ var child = _a[_i];
+ queue.push(child);
+ parents.push(current);
+ }
+ }
}
}
}
ts.forEachChildRecursively = forEachChildRecursively;
+ function gatherPossibleChildren(node) {
+ var children = [];
+ forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
+ return children;
+ function addWorkItem(n) {
+ children.unshift(n);
+ }
+ }
function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
if (setParentNodes === void 0) { setParentNodes = false; }
- var tracingData = ["parse" /* Parse */, "createSourceFile", { path: fileName }];
- ts.tracing.begin.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true);
ts.performance.mark("beforeParse");
var result;
ts.perfLogger.logStartParseSourceFile(fileName);
ts.perfLogger.logStopParseSourceFile();
ts.performance.mark("afterParse");
ts.performance.measure("Parse", "beforeParse", "afterParse");
- ts.tracing.end.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
return result;
}
ts.createSourceFile = createSourceFile;
// with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
// each identifier in order to reduce memory consumption.
function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
- identifierCount++;
if (isIdentifier) {
+ identifierCount++;
var pos = getNodePos();
// Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
var originalKeywordKind = token();
parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
return createIdentifier(/*isIdentifier*/ true);
}
+ if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) {
+ // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser.
+ return createIdentifier(/*isIdentifier*/ true);
+ }
+ identifierCount++;
// Only for end of file because the error gets reported incorrectly on embedded script tags.
var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
var isReservedWord = scanner.isReservedWord();
case 87 /* DefaultKeyword */:
return nextTokenCanFollowDefaultKeyword();
case 123 /* StaticKeyword */:
+ return nextTokenIsOnSameLineAndCanFollowModifier();
case 134 /* GetKeyword */:
case 146 /* SetKeyword */:
nextToken();
parseExpected(21 /* CloseParenToken */);
return finishNode(factory.createParenthesizedType(type), pos);
}
+ function parseModifiersForConstructorType() {
+ var modifiers;
+ if (token() === 125 /* AbstractKeyword */) {
+ var pos = getNodePos();
+ nextToken();
+ var modifier = finishNode(factory.createToken(125 /* AbstractKeyword */), pos);
+ modifiers = createNodeArray([modifier], pos);
+ }
+ return modifiers;
+ }
function parseFunctionOrConstructorType() {
var pos = getNodePos();
var hasJSDoc = hasPrecedingJSDocComment();
+ var modifiers = parseModifiersForConstructorType();
var isConstructorType = parseOptional(102 /* NewKeyword */);
var typeParameters = parseTypeParameters();
var parameters = parseParameters(4 /* Type */);
var type = parseReturnType(38 /* EqualsGreaterThanToken */, /*isType*/ false);
var node = isConstructorType
- ? factory.createConstructorTypeNode(typeParameters, parameters, type)
+ ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, type)
: factory.createFunctionTypeNode(typeParameters, parameters, type);
+ if (!isConstructorType)
+ node.modifiers = modifiers;
return withJSDoc(finishNode(node, pos), hasJSDoc);
}
function parseKeywordAndNoDot() {
function parseUnionTypeOrHigher() {
return parseUnionOrIntersectionType(51 /* BarToken */, parseIntersectionTypeOrHigher, factory.createUnionTypeNode);
}
+ function nextTokenIsNewKeyword() {
+ nextToken();
+ return token() === 102 /* NewKeyword */;
+ }
function isStartOfFunctionTypeOrConstructorType() {
if (token() === 29 /* LessThanToken */) {
return true;
if (token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType)) {
return true;
}
- return token() === 102 /* NewKeyword */;
+ return token() === 102 /* NewKeyword */ ||
+ token() === 125 /* AbstractKeyword */ && lookAhead(nextTokenIsNewKeyword);
}
function skipParameterStart() {
if (ts.isModifierKind(token())) {
return finishNode(factory.createJsxOpeningFragment(), pos);
}
var tagName = parseJsxElementName();
- var typeArguments = tryParseTypeArguments();
+ var typeArguments = (contextFlags & 131072 /* JavaScriptFile */) === 0 ? tryParseTypeArguments() : undefined;
var attributes = parseJsxAttributes();
var node;
if (token() === 31 /* GreaterThanToken */) {
expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
// handle 'foo<<T>()'
- if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
+ // parse template arguments only in TypeScript files (not in JavaScript files).
+ if ((contextFlags & 131072 /* JavaScriptFile */) === 0 && (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */)) {
// See if this is the start of a generic invocation. If so, consume it and
// keep checking for postfix expressions. Otherwise, it's just a '<' that's
// part of an arithmetic expression. Break out so we consume it higher in the
return result;
}
function parseTypeArgumentsInExpression() {
+ if ((contextFlags & 131072 /* JavaScriptFile */) !== 0) {
+ // TypeArguments must not be parsed in JavaScript files to avoid ambiguity with binary operators.
+ return undefined;
+ }
if (reScanLessThanToken() !== 29 /* LessThanToken */) {
return undefined;
}
parseExpected(62 /* EqualsToken */);
var moduleReference = parseModuleReference();
parseSemicolon();
- var node = factory.createImportEqualsDeclaration(decorators, modifiers, identifier, moduleReference);
+ var node = factory.createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, identifier, moduleReference);
var finished = withJSDoc(finishNode(node, pos), hasJSDoc);
- if (isTypeOnly) {
- parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
- }
return finished;
}
function parseImportClause(identifier, pos, isTypeOnly) {
function parseTagComments(indent, initialMargin) {
var comments = [];
var state = 0 /* BeginningOfLine */;
+ var previousWhitespace = true;
var margin;
function pushComment(text) {
if (!margin) {
indent = 0;
break;
case 59 /* AtToken */:
- if (state === 3 /* SavingBackticks */) {
+ if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) {
+ // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace
comments.push(scanner.getTokenText());
break;
}
pushComment(scanner.getTokenText());
break;
}
+ previousWhitespace = token() === 5 /* WhitespaceTrivia */;
tok = nextTokenJSDoc();
}
removeLeadingNewlines(comments);
var isNameFirst = !typeExpression;
skipWhitespaceOrAsterisk();
var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
- skipWhitespace();
+ var indentText = skipWhitespaceOrAsterisk();
if (isNameFirst) {
typeExpression = tryParseTypeExpression();
}
- var comment = parseTagComments(indent + scanner.getStartPos() - start);
+ var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
typeExpression = nestedTypeLiteral;
return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start, end);
}
function parseAuthorTag(start, tagName, indent, indentText) {
- var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
- if (!authorInfoWithEmail) {
- var end_1 = getNodePos();
- return finishNode(factory.createJSDocAuthorTag(tagName, parseTrailingTagComments(start, end_1, indent, indentText)), start, end_1);
- }
- var comments = authorInfoWithEmail;
- if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
- var comment = parseTagComments(indent);
- if (comment) {
- comments += comment;
- }
- }
- return finishNode(factory.createJSDocAuthorTag(tagName, comments), start);
+ var comments = parseAuthorNameAndEmail() + (parseTrailingTagComments(start, end, indent, indentText) || "");
+ return finishNode(factory.createJSDocAuthorTag(tagName, comments || undefined), start);
}
- function tryParseAuthorNameAndEmail() {
+ function parseAuthorNameAndEmail() {
var comments = [];
- var seenLessThan = false;
- var seenGreaterThan = false;
+ var inEmail = false;
var token = scanner.getToken();
- loop: while (true) {
- switch (token) {
- case 78 /* Identifier */:
- case 5 /* WhitespaceTrivia */:
- case 24 /* DotToken */:
- case 59 /* AtToken */:
- comments.push(scanner.getTokenText());
- break;
- case 29 /* LessThanToken */:
- if (seenLessThan || seenGreaterThan) {
- return;
- }
- seenLessThan = true;
- comments.push(scanner.getTokenText());
- break;
- case 31 /* GreaterThanToken */:
- if (!seenLessThan || seenGreaterThan) {
- return;
- }
- seenGreaterThan = true;
- comments.push(scanner.getTokenText());
- scanner.setTextPos(scanner.getTokenPos() + 1);
- break loop;
- case 4 /* NewLineTrivia */:
- case 1 /* EndOfFileToken */:
- break loop;
+ while (token !== 1 /* EndOfFileToken */ && token !== 4 /* NewLineTrivia */) {
+ if (token === 29 /* LessThanToken */) {
+ inEmail = true;
+ }
+ else if (token === 59 /* AtToken */ && !inEmail) {
+ break;
}
+ else if (token === 31 /* GreaterThanToken */ && inEmail) {
+ comments.push(scanner.getTokenText());
+ scanner.setTextPos(scanner.getTokenPos() + 1);
+ break;
+ }
+ comments.push(scanner.getTokenText());
token = nextTokenJSDoc();
}
- if (seenLessThan && seenGreaterThan) {
- return comments.length === 0 ? undefined : comments.join("");
- }
+ return comments.join("");
}
function parseImplementsTag(start, tagName, margin, indentText) {
var className = parseExpressionWithTypeArgumentsForAugments();
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
},
+ {
+ name: "excludeDirectories",
+ type: "list",
+ element: {
+ name: "excludeDirectory",
+ type: "string",
+ isFilePath: true,
+ extraValidation: specToDiagnostic
+ },
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
+ },
+ {
+ name: "excludeFiles",
+ type: "list",
+ element: {
+ name: "excludeFile",
+ type: "string",
+ isFilePath: true,
+ extraValidation: specToDiagnostic
+ },
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
+ },
];
/* @internal */
ts.commonOptionsWithBuild = [
description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
},
{
+ name: "explainFiles",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Print_names_of_files_and_the_reason_they_are_part_of_the_compilation
+ }, {
name: "listEmittedFiles",
type: "boolean",
category: ts.Diagnostics.Advanced_Options,
},
];
/* @internal */
- ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
+ ts.targetOptionDeclaration = {
+ name: "target",
+ shortName: "t",
+ type: new ts.Map(ts.getEntries({
+ es3: 0 /* ES3 */,
+ es5: 1 /* ES5 */,
+ es6: 2 /* ES2015 */,
+ es2015: 2 /* ES2015 */,
+ es2016: 3 /* ES2016 */,
+ es2017: 4 /* ES2017 */,
+ es2018: 5 /* ES2018 */,
+ es2019: 6 /* ES2019 */,
+ es2020: 7 /* ES2020 */,
+ esnext: 99 /* ESNext */,
+ })),
+ affectsSourceFile: true,
+ affectsModuleResolution: true,
+ affectsEmit: true,
+ paramType: ts.Diagnostics.VERSION,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
+ };
+ /* @internal */
+ ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [
{
name: "all",
type: "boolean",
description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
},
// Basic
- {
- name: "target",
- shortName: "t",
- type: new ts.Map(ts.getEntries({
- es3: 0 /* ES3 */,
- es5: 1 /* ES5 */,
- es6: 2 /* ES2015 */,
- es2015: 2 /* ES2015 */,
- es2016: 3 /* ES2016 */,
- es2017: 4 /* ES2017 */,
- es2018: 5 /* ES2018 */,
- es2019: 6 /* ES2019 */,
- es2020: 7 /* ES2020 */,
- esnext: 99 /* ESNext */,
- })),
- affectsSourceFile: true,
- affectsModuleResolution: true,
- affectsEmit: true,
- paramType: ts.Diagnostics.VERSION,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
- },
+ ts.targetOptionDeclaration,
{
name: "module",
shortName: "m",
paramType: ts.Diagnostics.KIND,
showInSimplifiedHelpView: true,
category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
+ description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_react_react_jsx_or_react_jsxdev,
},
{
name: "declaration",
category: ts.Diagnostics.Additional_Checks,
description: ts.Diagnostics.Include_undefined_in_index_signature_results
},
+ {
+ name: "noPropertyAccessFromIndexSignature",
+ type: "boolean",
+ showInSimplifiedHelpView: false,
+ category: ts.Diagnostics.Additional_Checks,
+ description: ts.Diagnostics.Require_undeclared_properties_from_index_signatures_to_use_element_accesses
+ },
// Module Resolution
{
name: "moduleResolution",
return ts.hasProperty(option, "transpileOptionValue");
});
/* @internal */
- ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
+ ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [
{
name: "verbose",
shortName: "v",
var values = value.split(",");
switch (opt.element.type) {
case "number":
- return ts.map(values, parseInt);
+ return ts.mapDefined(values, function (v) { return validateJsonOptionValue(opt.element, parseInt(v), errors); });
case "string":
- return ts.map(values, function (v) { return v || ""; });
+ return ts.mapDefined(values, function (v) { return validateJsonOptionValue(opt.element, v || "", errors); });
default:
return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
}
}
else if (opt.type === "boolean") {
if (optValue === "false") {
- options[opt.name] = false;
+ options[opt.name] = validateJsonOptionValue(opt, /*value*/ false, errors);
i++;
}
else {
if (args[i] !== "null") {
switch (opt.type) {
case "number":
- options[opt.name] = parseInt(args[i]);
+ options[opt.name] = validateJsonOptionValue(opt, parseInt(args[i]), errors);
i++;
break;
case "boolean":
// boolean flag has optional value true, false, others
var optValue = args[i];
- options[opt.name] = optValue !== "false";
+ options[opt.name] = validateJsonOptionValue(opt, optValue !== "false", errors);
// consume next argument as boolean flag value
if (optValue === "false" || optValue === "true") {
i++;
}
break;
case "string":
- options[opt.name] = args[i] || "";
+ options[opt.name] = validateJsonOptionValue(opt, args[i] || "", errors);
i++;
break;
case "list":
}
function convertArrayLiteralExpressionToJson(elements, elementOption) {
if (!returnValue) {
- return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
+ elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
+ return undefined;
}
// Filter out invalid values
return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
}
function convertPropertyValueToJson(valueExpression, option) {
+ var invalidReported;
switch (valueExpression.kind) {
case 109 /* TrueKeyword */:
reportInvalidOptionValue(option && option.type !== "boolean");
- return true;
+ return validateValue(/*value*/ true);
case 94 /* FalseKeyword */:
reportInvalidOptionValue(option && option.type !== "boolean");
- return false;
+ return validateValue(/*value*/ false);
case 103 /* NullKeyword */:
reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
- return null; // eslint-disable-line no-null/no-null
+ return validateValue(/*value*/ null); // eslint-disable-line no-null/no-null
case 10 /* StringLiteral */:
if (!isDoubleQuotedString(valueExpression)) {
errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
// Validate custom option type
if (!customOption.type.has(text.toLowerCase())) {
errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
+ invalidReported = true;
}
}
- return text;
+ return validateValue(text);
case 8 /* NumericLiteral */:
reportInvalidOptionValue(option && option.type !== "number");
- return Number(valueExpression.text);
+ return validateValue(Number(valueExpression.text));
case 214 /* PrefixUnaryExpression */:
if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
break; // not valid JSON syntax
}
reportInvalidOptionValue(option && option.type !== "number");
- return -Number(valueExpression.operand.text);
+ return validateValue(-Number(valueExpression.operand.text));
case 200 /* ObjectLiteralExpression */:
reportInvalidOptionValue(option && option.type !== "object");
var objectLiteralExpression = valueExpression;
// If need arises, we can modify this interface and callbacks as needed
if (option) {
var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
- return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
+ return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName));
}
else {
- return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined,
- /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
+ return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined,
+ /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined));
}
case 199 /* ArrayLiteralExpression */:
reportInvalidOptionValue(option && option.type !== "list");
- return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
+ return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element));
}
// Not in expected format
if (option) {
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));
}
return undefined;
+ function validateValue(value) {
+ var _a;
+ if (!invalidReported) {
+ var diagnostic = (_a = option === null || option === void 0 ? void 0 : option.extraValidation) === null || _a === void 0 ? void 0 : _a.call(option, value);
+ if (diagnostic) {
+ errors.push(ts.createDiagnosticForNodeInSourceFile.apply(void 0, __spreadArray([sourceFile, valueExpression], diagnostic)));
+ return undefined;
+ }
+ }
+ return value;
+ }
function reportInvalidOptionValue(isError) {
if (isError) {
errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
+ invalidReported = true;
}
}
}
*/
/** @internal */
function convertToTSConfig(configParseResult, configFileName, host) {
+ var _a, _b, _c;
var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
- 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); });
+ var files = ts.map(ts.filter(configParseResult.fileNames, !((_b = (_a = configParseResult.options.configFile) === null || _a === void 0 ? void 0 : _a.configFileSpecs) === null || _b === void 0 ? void 0 : _b.validatedIncludeSpecs) ? ts.returnTrue : matchesSpecs(configFileName, configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs, configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); });
var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
- 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 ? {
- include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
- exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
+ var config = __assign(__assign({ compilerOptions: __assign(__assign({}, optionMapToObject(optionMap)), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), watchOptions: watchOptionMap && optionMapToObject(watchOptionMap), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign(__assign({}, r), { path: r.originalPath ? r.originalPath : "", originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (((_c = configParseResult.options.configFile) === null || _c === void 0 ? void 0 : _c.configFileSpecs) ? {
+ include: filterSameAsDefaultInclude(configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs),
+ exclude: configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs
} : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
return config;
}
}
function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
if (!includeSpecs)
- return function (_) { return true; };
+ return ts.returnTrue;
var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
if (excludeRe) {
return function (path) { return excludeRe.test(path); };
}
- return function (_) { return true; };
+ return ts.returnTrue;
}
function getCustomTypeMapOfCommandLineOption(optionDefinition) {
if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
parsedConfig.watchOptions || existingWatchOptions;
options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
+ var configFileSpecs = getConfigFileSpecs();
+ if (sourceFile)
+ sourceFile.configFileSpecs = configFileSpecs;
setConfigFileInOptions(options, sourceFile);
- var projectReferences;
- var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
+ var basePathForFileNames = ts.normalizePath(configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath);
return {
options: options,
watchOptions: watchOptions,
- fileNames: fileNames,
- projectReferences: projectReferences,
+ fileNames: getFileNames(basePathForFileNames),
+ projectReferences: getProjectReferences(basePathForFileNames),
typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
raw: raw,
errors: errors,
- wildcardDirectories: wildcardDirectories,
+ // Wildcard directories (provided as part of a wildcard path) are stored in a
+ // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
+ // or a recursive directory. This information is used by filesystem watchers to monitor for
+ // new entries in these paths.
+ wildcardDirectories: getWildcardDirectories(configFileSpecs, basePathForFileNames, host.useCaseSensitiveFileNames),
compileOnSave: !!raw.compileOnSave,
- configFileSpecs: spec
};
- function getFileNames() {
+ function getConfigFileSpecs() {
var referencesOfRaw = getPropFromRaw("references", function (element) { return typeof element === "object"; }, "object");
- if (ts.isArray(referencesOfRaw)) {
- for (var _i = 0, referencesOfRaw_1 = referencesOfRaw; _i < referencesOfRaw_1.length; _i++) {
- var ref = referencesOfRaw_1[_i];
- if (typeof ref.path !== "string") {
- createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
- }
- else {
- (projectReferences || (projectReferences = [])).push({
- path: ts.getNormalizedAbsolutePath(ref.path, basePath),
- originalPath: ref.path,
- prepend: ref.prepend,
- circular: ref.circular
- });
- }
- }
- }
var filesSpecs = toPropValue(getSpecsFromRaw("files"));
if (filesSpecs) {
var hasZeroOrNoReferences = referencesOfRaw === "no-prop" || ts.isArray(referencesOfRaw) && referencesOfRaw.length === 0;
if (filesSpecs === undefined && includeSpecs === undefined) {
includeSpecs = ["**/*"];
}
- var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
- if (shouldReportNoInputFiles(result, canJsonReportNoInputFiles(raw), resolutionStack)) {
- errors.push(getErrorForNoInputFiles(result.spec, configFileName));
+ var validatedIncludeSpecs, validatedExcludeSpecs;
+ // The exclude spec list is converted into a regular expression, which allows us to quickly
+ // test whether a file or directory should be excluded before recursively traversing the
+ // file system.
+ if (includeSpecs) {
+ validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*disallowTrailingRecursion*/ true, sourceFile, "include");
}
- return result;
+ if (excludeSpecs) {
+ validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*disallowTrailingRecursion*/ false, sourceFile, "exclude");
+ }
+ return {
+ filesSpecs: filesSpecs,
+ includeSpecs: includeSpecs,
+ excludeSpecs: excludeSpecs,
+ validatedFilesSpec: ts.filter(filesSpecs, ts.isString),
+ validatedIncludeSpecs: validatedIncludeSpecs,
+ validatedExcludeSpecs: validatedExcludeSpecs,
+ };
+ }
+ function getFileNames(basePath) {
+ var fileNames = getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions);
+ if (shouldReportNoInputFiles(fileNames, canJsonReportNoInputFiles(raw), resolutionStack)) {
+ errors.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
+ }
+ return fileNames;
+ }
+ function getProjectReferences(basePath) {
+ var projectReferences;
+ var referencesOfRaw = getPropFromRaw("references", function (element) { return typeof element === "object"; }, "object");
+ if (ts.isArray(referencesOfRaw)) {
+ for (var _i = 0, referencesOfRaw_1 = referencesOfRaw; _i < referencesOfRaw_1.length; _i++) {
+ var ref = referencesOfRaw_1[_i];
+ if (typeof ref.path !== "string") {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
+ }
+ else {
+ (projectReferences || (projectReferences = [])).push({
+ path: ts.getNormalizedAbsolutePath(ref.path, basePath),
+ originalPath: ref.path,
+ prepend: ref.prepend,
+ circular: ref.circular
+ });
+ }
+ }
+ }
+ return projectReferences;
}
function toPropValue(specResult) {
return ts.isArray(specResult) ? specResult : undefined;
var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
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 || []));
}
- function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
- return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
+ function shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles, resolutionStack) {
+ return fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
}
/*@internal*/
function canJsonReportNoInputFiles(raw) {
}
ts.canJsonReportNoInputFiles = canJsonReportNoInputFiles;
/*@internal*/
- function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
+ function updateErrorForNoInputFiles(fileNames, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
var existingErrors = configParseDiagnostics.length;
- if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
+ if (shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles)) {
configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
}
else {
basePath = ts.normalizeSlashes(basePath);
var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
if (resolutionStack.indexOf(resolvedPath) >= 0) {
- errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
+ errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArray(__spreadArray([], resolutionStack), [resolvedPath]).join(" -> ")));
return { raw: json || convertToObject(sourceFile, errors) };
}
var ownConfig = json ?
if (ownConfig.extendedConfigPath) {
// copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
resolutionStack = resolutionStack.concat([resolvedPath]);
- var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache);
+ var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache);
if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
var baseRaw_1 = extendedConfig.raw;
var raw_1 = ownConfig.raw;
+ var relativeDifference_1;
var setPropertyInRawIfNotUndefined = function (propertyName) {
- var value = raw_1[propertyName] || baseRaw_1[propertyName];
- if (value) {
- raw_1[propertyName] = value;
+ if (!raw_1[propertyName] && baseRaw_1[propertyName]) {
+ raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); });
}
};
setPropertyInRawIfNotUndefined("include");
errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
return undefined;
}
- function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
+ function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) {
var _a;
var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
var value;
else {
extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
if (!extendedResult.parseDiagnostics.length) {
- var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
- extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
- if (isSuccessfulParsedTsconfig(extendedConfig)) {
- // Update the paths to reflect base path
- var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
- var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
- var mapPropertiesInRawIfNotUndefined = function (propertyName) {
- if (raw_2[propertyName]) {
- raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
- }
- };
- var raw_2 = extendedConfig.raw;
- mapPropertiesInRawIfNotUndefined("include");
- mapPropertiesInRawIfNotUndefined("exclude");
- mapPropertiesInRawIfNotUndefined("files");
- }
+ extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
}
if (extendedConfigCache) {
extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
}
return defaultOptions;
}
+ /*@internal*/
function convertJsonOption(opt, value, basePath, errors) {
if (isCompilerOptionsValue(opt, value)) {
var optType = opt.type;
else if (!ts.isString(optType)) {
return convertJsonOptionOfCustomType(opt, value, errors);
}
- return normalizeNonListOptionValue(opt, basePath, value);
+ var validatedValue = validateJsonOptionValue(opt, value, errors);
+ return isNullOrUndefined(validatedValue) ? validatedValue : normalizeNonListOptionValue(opt, basePath, validatedValue);
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
}
}
+ ts.convertJsonOption = convertJsonOption;
function normalizeOptionValue(option, basePath, value) {
if (isNullOrUndefined(value))
return undefined;
}
return value;
}
+ function validateJsonOptionValue(opt, value, errors) {
+ var _a;
+ if (isNullOrUndefined(value))
+ return undefined;
+ var d = (_a = opt.extraValidation) === null || _a === void 0 ? void 0 : _a.call(opt, value);
+ if (!d)
+ return value;
+ errors.push(ts.createCompilerDiagnostic.apply(void 0, d));
+ return undefined;
+ }
function convertJsonOptionOfCustomType(opt, value, errors) {
if (isNullOrUndefined(value))
return undefined;
var key = value.toLowerCase();
var val = opt.type.get(key);
if (val !== undefined) {
- return val;
+ return validateJsonOptionValue(opt, val, errors);
}
else {
errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
* # a path component that contains at least one wildcard character (* or ?).
*/
var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
- /**
- * Expands an array of file specifications.
- *
- * @param filesSpecs The literal file names to include.
- * @param includeSpecs The wildcard file specifications to include.
- * @param excludeSpecs The wildcard file specifications to exclude.
- * @param basePath The base path for any relative file specifications.
- * @param options Compiler options.
- * @param host The host used to resolve files and directories.
- * @param errors An array for diagnostic reporting.
- */
- function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
- basePath = ts.normalizePath(basePath);
- var validatedIncludeSpecs, validatedExcludeSpecs;
- // The exclude spec list is converted into a regular expression, which allows us to quickly
- // test whether a file or directory should be excluded before recursively traversing the
- // file system.
- if (includeSpecs) {
- validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
- }
- if (excludeSpecs) {
- validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
- }
- // Wildcard directories (provided as part of a wildcard path) are stored in a
- // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
- // or a recursive directory. This information is used by filesystem watchers to monitor for
- // new entries in these paths.
- var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
- var spec = {
- filesSpecs: filesSpecs,
- includeSpecs: includeSpecs,
- excludeSpecs: excludeSpecs,
- validatedFilesSpec: ts.filter(filesSpecs, ts.isString),
- validatedIncludeSpecs: validatedIncludeSpecs,
- validatedExcludeSpecs: validatedExcludeSpecs,
- wildcardDirectories: wildcardDirectories
- };
- return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
- }
/**
* Gets the file names from the provided config file specs that contain, files, include, exclude and
* other properties needed to resolve the file names
- * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
+ * @param configFileSpecs The config file specs extracted with file names to include, wildcards to include/exclude and other details
* @param basePath The base path for any relative file specifications.
* @param options Compiler options.
* @param host The host used to resolve files and directories.
* @param extraFileExtensions optionaly file extra file extension information from host
*/
/* @internal */
- function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
+ function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions) {
if (extraFileExtensions === void 0) { extraFileExtensions = ts.emptyArray; }
basePath = ts.normalizePath(basePath);
var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
// file map with a possibly case insensitive key. We use this map to store paths matched
// via wildcard of *.json kind
var wildCardJsonFileMap = new ts.Map();
- var validatedFilesSpec = spec.validatedFilesSpec, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
+ var validatedFilesSpec = configFileSpecs.validatedFilesSpec, validatedIncludeSpecs = configFileSpecs.validatedIncludeSpecs, validatedExcludeSpecs = configFileSpecs.validatedExcludeSpecs;
// Rather than requery this for each file and filespec, we query the supported extensions
// once and store it on the expansion context.
var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
}
var literalFiles = ts.arrayFrom(literalFileMap.values());
var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
- return {
- fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
- wildcardDirectories: wildcardDirectories,
- spec: spec
- };
+ return literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values()));
}
ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
/* @internal */
return false;
}
}
- var excludePattern = ts.getRegularExpressionForWildcard(validatedExcludeSpecs, ts.combinePaths(ts.normalizePath(currentDirectory), basePath), "exclude");
+ return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath);
+ }
+ ts.isExcludedFile = isExcludedFile;
+ /* @internal */
+ function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory) {
+ return matchesExcludeWorker(pathToCheck, ts.filter(excludeSpecs, function (spec) { return !invalidDotDotAfterRecursiveWildcardPattern.test(spec); }), useCaseSensitiveFileNames, currentDirectory);
+ }
+ ts.matchesExclude = matchesExclude;
+ function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath) {
+ var excludePattern = ts.getRegularExpressionForWildcard(excludeSpecs, ts.combinePaths(ts.normalizePath(currentDirectory), basePath), "exclude");
var excludeRegex = excludePattern && ts.getRegexFromPattern(excludePattern, useCaseSensitiveFileNames);
if (!excludeRegex)
return false;
return true;
return !ts.hasExtension(pathToCheck) && excludeRegex.test(ts.ensureTrailingDirectorySeparator(pathToCheck));
}
- ts.isExcludedFile = isExcludedFile;
- function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
+ function validateSpecs(specs, errors, disallowTrailingRecursion, jsonSourceFile, specKey) {
return specs.filter(function (spec) {
if (!ts.isString(spec))
return false;
- var diag = specToDiagnostic(spec, allowTrailingRecursion);
+ var diag = specToDiagnostic(spec, disallowTrailingRecursion);
if (diag !== undefined) {
- errors.push(createDiagnostic(diag, spec));
+ errors.push(createDiagnostic.apply(void 0, diag));
}
return diag === undefined;
});
ts.createCompilerDiagnostic(message, spec);
}
}
- function specToDiagnostic(spec, allowTrailingRecursion) {
- if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
- return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
+ function specToDiagnostic(spec, disallowTrailingRecursion) {
+ if (disallowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
+ return [ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
}
else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
- return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
+ return [ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
}
}
/**
* Gets directories in a set of include patterns that should be watched for changes.
*/
- function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
+ function getWildcardDirectories(_a, path, useCaseSensitiveFileNames) {
+ var include = _a.validatedIncludeSpecs, exclude = _a.validatedExcludeSpecs;
// We watch a directory recursively if it contains a wildcard anywhere in a directory segment
// of the pattern:
//
// Remove any subpaths under an existing recursively watched directory.
for (var key in wildcardDirectories) {
if (ts.hasProperty(wildcardDirectories, key)) {
- for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
- var recursiveKey = recursiveKeys_1[_a];
+ for (var _b = 0, recursiveKeys_1 = recursiveKeys; _b < recursiveKeys_1.length; _b++) {
+ var recursiveKey = recursiveKeys_1[_b];
if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
delete wildcardDirectories[key];
}
ts.tryResolveJSModule = tryResolveJSModule;
var jsOnlyExtensions = [Extensions.JavaScript];
var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
- var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
+ var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions), [Extensions.Json]);
var tsconfigExtensions = [Extensions.TSConfig];
function tryResolveJSModuleWorker(moduleName, initialDir, host) {
return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
ts.pathContainsNodeModules = pathContainsNodeModules;
/**
* This will be called on the successfully resolved path from `loadModuleFromFile`.
- * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
+ * (Not needed for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
*
* packageDirectory is the directory of the package itself.
* For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
}
// A path mapping may have an extension, in contrast to an import, which should omit it.
- var extension = ts.tryGetExtensionFromPath(candidate);
+ var extension = ts.tryGetExtensionFromPath(subst);
if (extension !== undefined) {
var path_1 = tryFile(candidate, onlyRecordFailures, state);
if (path_1 !== undefined) {
}
var binder = createBinder();
function bindSourceFile(file, options) {
- var tracingData = ["bind" /* Bind */, "bindSourceFile", { path: file.path }];
- ts.tracing.begin.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true);
ts.performance.mark("beforeBind");
ts.perfLogger.logStartBindFile("" + file.fileName);
binder(file, options);
ts.perfLogger.logStopBindFile();
ts.performance.mark("afterBind");
ts.performance.measure("Bind", "beforeBind", "afterBind");
- ts.tracing.end.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
}
ts.bindSourceFile = bindSourceFile;
function createBinder() {
}
});
var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
- file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
+ file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArray([diag], relatedInformation_1)));
symbol = createSymbol(0 /* None */, name);
}
}
}
// We create a return control flow graph for IIFEs and constructors. For constructors
// we use the return control flow graph in strict property initialization checks.
- currentReturnTarget = isIIFE || node.kind === 166 /* Constructor */ || (ts.isInJSFile && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) ? createBranchLabel() : undefined;
+ currentReturnTarget = isIIFE || node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) ? createBranchLabel() : undefined;
currentExceptionTarget = undefined;
currentBreakTarget = undefined;
currentContinueTarget = undefined;
if (currentReturnTarget) {
addAntecedent(currentReturnTarget, currentFlow);
currentFlow = finishFlowLabel(currentReturnTarget);
- if (node.kind === 166 /* Constructor */ || (ts.isInJSFile && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */))) {
+ if (node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */))) {
node.returnFlowNode = currentFlow;
}
}
for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
var typeAlias = delayedTypeAliases_1[_i];
var host = ts.getJSDocHost(typeAlias);
- container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
- blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
+ container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file;
+ blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file;
currentFlow = initFlowNode({ flags: 2 /* Start */ });
parent = typeAlias;
bind(typeAlias.typeExpression);
node.flowNode = currentFlow;
}
return checkContextualIdentifier(node);
+ case 157 /* QualifiedName */:
+ if (currentFlow && parent.kind === 176 /* TypeQuery */) {
+ node.flowNode = currentFlow;
+ }
+ break;
case 105 /* SuperKeyword */:
node.flowNode = currentFlow;
break;
// reachability checks
function shouldReportErrorOnModuleDeclaration(node) {
var instanceState = getModuleInstanceState(node);
- return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
+ return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options));
}
function checkUnreachable(node) {
if (!(currentFlow.flags & 1 /* Unreachable */)) {
IntersectionState[IntersectionState["Source"] = 1] = "Source";
IntersectionState[IntersectionState["Target"] = 2] = "Target";
IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
- IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
+ IntersectionState[IntersectionState["UnionIntersectionCheck"] = 8] = "UnionIntersectionCheck";
+ IntersectionState[IntersectionState["InPropertyCheck"] = 16] = "InPropertyCheck";
})(IntersectionState || (IntersectionState = {}));
var MappedTypeModifiers;
(function (MappedTypeModifiers) {
var totalInstantiationCount = 0;
var instantiationCount = 0;
var instantiationDepth = 0;
- var constraintDepth = 0;
var currentNode;
var typeCatalog = []; // NB: id is index + 1
var emptySymbols = ts.createSymbolTable();
return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
},
getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
+ getJsxFragmentFactory: function (n) {
+ var jsxFragmentFactory = getJsxFragmentFactoryEntity(n);
+ return jsxFragmentFactory && ts.unescapeLeadingUnderscores(ts.getFirstIdentifier(jsxFragmentFactory).escapedText);
+ },
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleName: function (moduleSpecifierIn) {
}
return diagnostic;
}
+ function addDeprecatedSuggestionWorker(declarations, diagnostic) {
+ var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations);
+ if (deprecatedTag) {
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here));
+ }
+ // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates.
+ suggestionDiagnostics.add(diagnostic);
+ return diagnostic;
+ }
+ function addDeprecatedSuggestion(location, declarations, deprecatedEntity) {
+ var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity);
+ return addDeprecatedSuggestionWorker(declarations, diagnostic);
+ }
+ function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) {
+ var diagnostic = deprecatedEntity
+ ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity)
+ : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString);
+ return addDeprecatedSuggestionWorker(declaration, diagnostic);
+ }
function createSymbol(flags, name, checkFlags) {
symbolCount++;
var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
case 324 /* JSDocCallbackTag */:
case 325 /* JSDocEnumTag */:
// js type aliases do not resolve names from their host, so skip past it
- location = ts.getJSDocHost(location);
+ var root = ts.getJSDocRoot(location);
+ if (root) {
+ location = root.parent;
+ }
break;
case 160 /* Parameter */:
if (lastLocation && (lastLocation === location.initializer ||
var suggestion = void 0;
if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
+ var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration);
+ if (isGlobalScopeAugmentationDeclaration) {
+ suggestion = undefined;
+ }
if (suggestion) {
var suggestionName = symbolToString(suggestion);
var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
}
else {
ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
- if (compilerOptions.preserveConstEnums) {
+ if (ts.shouldPreserveConstEnums(compilerOptions)) {
diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
}
}
return resolved;
}
function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
- if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
+ if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false) && !node.isTypeOnly) {
var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
var message = isExport
if (exportStar) {
var defaultExport = ts.find(exportStar.declarations, function (decl) {
var _a, _b;
- 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 */)));
+ 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 */)));
});
if (defaultExport) {
ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
var symbolFromVariable = void 0;
// First check if module was specified with "export=". If so, get the member from the resolved type
if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
- symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
+ symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText, /*skipObjectFunctionPropertyAugment*/ true);
}
else {
symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
- ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
+ ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
})));
}
return;
}
var host = ts.getJSDocHost(node);
- if (ts.isExpressionStatement(host) &&
+ if (host &&
+ ts.isExpressionStatement(host) &&
ts.isBinaryExpression(host.expression) &&
ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
// X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
return getDeclarationOfJSPrototypeContainer(symbol);
}
}
- if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
+ if (host && (ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
ts.isBinaryExpression(host.parent.parent) &&
ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
// X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
var tsExtension = ts.tryExtractTSExtension(moduleReference);
if (tsExtension) {
var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
- error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
+ var importSourceWithoutExtension = ts.removeExtension(moduleReference, tsExtension);
+ var replacedImportSource = importSourceWithoutExtension;
+ /**
+ * Direct users to import source with .js extension if outputting an ES module.
+ * @see https://github.com/microsoft/TypeScript/issues/42151
+ */
+ var moduleKind_1 = ts.getEmitModuleKind(compilerOptions);
+ if (moduleKind_1 >= ts.ModuleKind.ES2015) {
+ replacedImportSource += ".js";
+ }
+ error(errorNode, diag, tsExtension, replacedImportSource);
}
else if (!compilerOptions.resolveJsonModule &&
ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
typeCatalog.push(result);
return result;
}
+ function createOriginType(flags) {
+ return new Type(checker, flags);
+ }
function createIntrinsicType(kind, intrinsicName, objectFlags) {
if (objectFlags === void 0) { objectFlags = 0; }
var type = createType(kind);
return result || ts.emptyArray;
}
function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
- type.members = members;
- type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
- type.callSignatures = callSignatures;
- type.constructSignatures = constructSignatures;
- type.stringIndexInfo = stringIndexInfo;
- type.numberIndexInfo = numberIndexInfo;
- return type;
+ var resolved = type;
+ resolved.members = members;
+ resolved.properties = ts.emptyArray;
+ resolved.callSignatures = callSignatures;
+ resolved.constructSignatures = constructSignatures;
+ resolved.stringIndexInfo = stringIndexInfo;
+ resolved.numberIndexInfo = numberIndexInfo;
+ // This can loop back to getPropertyOfType() which would crash if `callSignatures` & `constructSignatures` are not initialized.
+ if (members !== emptySymbols)
+ resolved.properties = getNamedMembers(members);
+ return resolved;
}
function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
}
+ function getResolvedTypeWithoutAbstractConstructSignatures(type) {
+ if (type.constructSignatures.length === 0)
+ return type;
+ if (type.objectTypeWithoutAbstractConstructSignatures)
+ return type.objectTypeWithoutAbstractConstructSignatures;
+ var constructSignatures = ts.filter(type.constructSignatures, function (signature) { return !(signature.flags & 4 /* Abstract */); });
+ if (type.constructSignatures === constructSignatures)
+ return type;
+ var typeCopy = createAnonymousType(type.symbol, type.members, type.callSignatures, ts.some(constructSignatures) ? constructSignatures : ts.emptyArray, type.stringIndexInfo, type.numberIndexInfo);
+ type.objectTypeWithoutAbstractConstructSignatures = typeCopy;
+ typeCopy.objectTypeWithoutAbstractConstructSignatures = typeCopy;
+ return typeCopy;
+ }
function forEachSymbolTableInScope(enclosingDeclaration, callback) {
var result;
var _loop_8 = function (location) {
return {
accessibility: 2 /* CannotBeNamed */,
errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
- errorModuleName: symbolToString(symbolExternalModule)
+ errorModuleName: symbolToString(symbolExternalModule),
+ errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined,
};
}
}
getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
fileExists: function (fileName) { return host.fileExists(fileName); },
+ getFileIncludeReasons: function () { return host.getFileIncludeReasons(); },
} : undefined },
encounteredError: false,
visitedTypes: undefined,
? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
: ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("?"), /*typeArguments*/ undefined);
}
+ if (type.flags & 1048576 /* Union */ && type.origin) {
+ type = type.origin;
+ }
if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
if (ts.length(types) === 1) {
}
var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
if (typeNodes && typeNodes.length > 0) {
- var unionOrIntersectionTypeNode = type.flags & 1048576 /* Union */ ? ts.factory.createUnionTypeNode(typeNodes) : ts.factory.createIntersectionTypeNode(typeNodes);
- return unionOrIntersectionTypeNode;
+ return type.flags & 1048576 /* Union */ ? ts.factory.createUnionTypeNode(typeNodes) : ts.factory.createIntersectionTypeNode(typeNodes);
}
else {
if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
return signatureNode;
}
}
+ var abstractSignatures = ts.filter(resolved.constructSignatures, function (signature) { return !!(signature.flags & 4 /* Abstract */); });
+ if (ts.some(abstractSignatures)) {
+ var types = ts.map(abstractSignatures, getOrCreateTypeFromSignature);
+ // count the number of type elements excluding abstract constructors
+ var typeElementCount = resolved.callSignatures.length +
+ (resolved.constructSignatures.length - abstractSignatures.length) +
+ (resolved.stringIndexInfo ? 1 : 0) +
+ (resolved.numberIndexInfo ? 1 : 0) +
+ // exclude `prototype` when writing a class expression as a type literal, as per
+ // the logic in `createTypeNodesFromResolvedType`.
+ (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ ?
+ ts.countWhere(resolved.properties, function (p) { return !(p.flags & 4194304 /* Prototype */); }) :
+ ts.length(resolved.properties));
+ // don't include an empty object literal if there were no other static-side
+ // properties to write, i.e. `abstract class C { }` becomes `abstract new () => {}`
+ // and not `(abstract new () => {}) & {}`
+ if (typeElementCount) {
+ // create a copy of the object type without any abstract construct signatures.
+ types.push(getResolvedTypeWithoutAbstractConstructSignatures(resolved));
+ }
+ return typeToTypeNodeHelper(getIntersectionType(types), context);
+ }
var savedFlags = context.flags;
context.flags |= 4194304 /* InObjectTypeLiteral */;
var members = createTypeNodesFromResolvedType(resolved);
context.flags = savedFlags;
var typeLiteralNode = ts.factory.createTypeLiteralNode(members);
context.approximateLength += 2;
- return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
+ ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
+ return typeLiteralNode;
}
function typeReferenceToTypeNode(type) {
var typeArguments = getTypeArguments(type);
}
for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
var signature = _c[_b];
+ if (signature.flags & 4 /* Abstract */)
+ continue;
typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* ConstructSignature */, context));
}
if (resolvedType.stringIndexInfo) {
anyType : getTypeOfSymbol(propertySymbol);
var saveEnclosingDeclaration = context.enclosingDeclaration;
context.enclosingDeclaration = undefined;
- if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */) {
+ if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */ && isLateBoundName(propertySymbol.escapedName)) {
var decl = ts.first(propertySymbol.declarations);
if (hasLateBindableName(decl)) {
if (ts.isBinaryExpression(decl)) {
returnTypeNode = ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
}
}
+ var modifiers = options === null || options === void 0 ? void 0 : options.modifiers;
+ if ((kind === 175 /* ConstructorType */) && signature.flags & 4 /* Abstract */) {
+ var flags = ts.modifiersToFlags(modifiers);
+ modifiers = ts.factory.createModifiersFromModifierFlags(flags | 128 /* Abstract */);
+ }
context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
var node = kind === 169 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) :
kind === 170 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) :
- kind === 164 /* MethodSignature */ ? ts.factory.createMethodSignature(options === null || options === void 0 ? void 0 : options.modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) :
- kind === 165 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) :
- kind === 166 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, parameters, /*body*/ undefined) :
- kind === 167 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) :
- kind === 168 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) :
- kind === 171 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, parameters, returnTypeNode) :
+ kind === 164 /* MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) :
+ kind === 165 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) :
+ kind === 166 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) :
+ kind === 167 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) :
+ kind === 168 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) :
+ kind === 171 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) :
kind === 308 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) :
kind === 174 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
- kind === 175 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
- kind === 251 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) :
- kind === 208 /* FunctionExpression */ ? ts.factory.createFunctionExpression(options === null || options === void 0 ? void 0 : options.modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) :
- kind === 209 /* ArrowFunction */ ? ts.factory.createArrowFunction(options === null || options === void 0 ? void 0 : options.modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) :
+ kind === 175 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
+ kind === 251 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) :
+ kind === 208 /* FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) :
+ kind === 209 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) :
ts.Debug.assertNever(kind);
if (typeArguments) {
node.typeArguments = ts.factory.createNodeArray(typeArguments);
// specifier preference
var moduleResolverHost = context.tracker.moduleResolverHost;
var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
- specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined }));
+ specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined }));
(_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map());
links.specifierCache.set(contextFile.path, specifier);
}
}
return typeToTypeNodeHelper(type, context);
}
+ function trackExistingEntityName(node, context, includePrivateSymbol) {
+ var _a, _b;
+ var introducesError = false;
+ var leftmost = ts.getFirstIdentifier(node);
+ 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)))) {
+ introducesError = true;
+ return { introducesError: introducesError, node: node };
+ }
+ var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
+ if (sym) {
+ if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
+ introducesError = true;
+ }
+ else {
+ (_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 */);
+ includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
+ }
+ if (ts.isIdentifier(node)) {
+ var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.factory.cloneNode(node);
+ name.symbol = sym; // for quickinfo, which uses identifier symbol information
+ return { introducesError: introducesError, node: ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */) };
+ }
+ }
+ return { introducesError: introducesError, node: node };
+ }
function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
cancellationToken.throwIfCancellationRequested();
}
return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed;
function visitExistingNodeTreeSymbols(node) {
- var _a, _b;
// We don't _actually_ support jsdoc namepath types, emit `any` instead
if (ts.isJSDocAllType(node) || node.kind === 310 /* JSDocNamepathType */) {
return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
return ts.factory.createPropertySignature(
- /*modifiers*/ undefined, name, t.typeExpression && ts.isJSDocOptionalType(t.typeExpression.type) ? ts.factory.createToken(57 /* QuestionToken */) : undefined, overrideTypeNode || (t.typeExpression && ts.visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols)) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
+ /*modifiers*/ undefined, name, t.isBracketed || t.typeExpression && ts.isJSDocOptionalType(t.typeExpression.type) ? ts.factory.createToken(57 /* QuestionToken */) : undefined, overrideTypeNode || (t.typeExpression && ts.visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols)) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
}));
}
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
if (ts.isJSDocFunctionType(node)) {
if (ts.isJSDocConstructSignature(node)) {
var newTypeNode_1;
- return ts.factory.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.factory.createParameterDeclaration(
+ return ts.factory.createConstructorTypeNode(node.modifiers, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols),
/*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
}
if (ts.isLiteralImportTypeNode(node)) {
+ var nodeSymbol = getNodeLinks(node).resolvedSymbol;
+ if (ts.isInJSDoc(node) &&
+ nodeSymbol &&
+ (
+ // The import type resolved using jsdoc fallback logic
+ (!node.isTypeOf && !(nodeSymbol.flags & 788968 /* Type */)) ||
+ // The import type had type arguments autofilled by js fallback logic
+ !(ts.length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) {
+ return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
+ }
return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf);
}
if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
- var leftmost = ts.getFirstIdentifier(node);
- 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)))) {
- hadError = true;
- return node;
- }
- var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
- if (sym) {
- if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
- hadError = true;
- }
- else {
- (_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 */);
- includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
- }
- if (ts.isIdentifier(node)) {
- var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.factory.cloneNode(node);
- name.symbol = sym; // for quickinfo, which uses identifier symbol information
- return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */);
- }
+ var _a = trackExistingEntityName(node, context, includePrivateSymbol), introducesError = _a.introducesError, result = _a.node;
+ hadError = hadError || introducesError;
+ if (result !== node) {
+ return result;
}
}
if (file && ts.isTupleTypeNode(node) && (ts.getLineAndCharacterOfPosition(file, node.pos).line === ts.getLineAndCharacterOfPosition(file, node.end).line)) {
var deferredPrivatesStack = [];
var oldcontext = context;
context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
- var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false);
+ var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false);
if (accessibleResult.accessibility === 0 /* Accessible */) {
// Lookup the root symbol of the chain of refs we'll use to access it and serialize it
var chain = lookupSymbolChainWorker(sym, context, meaning);
var name_2 = ns.name;
var body = ns.body;
if (ts.length(excessExports)) {
- ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArrays(ns.body.statements, [ts.factory.createExportDeclaration(
+ ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements), [ts.factory.createExportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*alias*/ undefined, id); })),
/*moduleSpecifier*/ undefined)]))));
- statements = __spreadArrays(statements.slice(0, nsIndex), [ns], statements.slice(nsIndex + 1));
+ statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, nsIndex)), [ns]), statements.slice(nsIndex + 1));
}
// Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, name_2); })) {
ts.forEach(body.statements, function (s) {
addResult(s, mixinExportFlag_1 ? 1 /* Export */ : 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
});
- statements = __spreadArrays(ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), results);
+ statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; })), results);
}
}
return statements;
var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
if (ts.length(exports) > 1) {
var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
- statements = __spreadArrays(nonExports, [ts.factory.createExportDeclaration(
+ statements = __spreadArray(__spreadArray([], nonExports), [ts.factory.createExportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })),
var _loop_9 = function (group_1) {
if (group_1.length > 1) {
// remove group members from statements and then merge group members and add back to statements
- statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [
+ statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; })), [
ts.factory.createExportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
function addResult(node, additionalModifierFlags) {
if (ts.canHaveModifiers(node)) {
var newModifierFlags = 0 /* None */;
+ var enclosingDeclaration_1 = context.enclosingDeclaration &&
+ (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration);
if (additionalModifierFlags & 1 /* Export */ &&
- context.enclosingDeclaration &&
- (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) &&
+ enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) &&
canHaveExportModifier(node)) {
// Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
newModifierFlags |= 1 /* Export */;
}
if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
- (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) &&
+ (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) &&
(ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
// Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
newModifierFlags |= 2 /* Ambient */;
var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
var oldFlags = context.flags;
context.flags |= 8388608 /* InTypeAlias */;
- addResult(ts.setSyntheticLeadingComments(ts.factory.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);
+ var oldEnclosingDecl = context.enclosingDeclaration;
+ context.enclosingDeclaration = jsdocAliasDecl;
+ var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression
+ && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression)
+ && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled)
+ || typeToTypeNodeHelper(aliasType, context);
+ addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags);
context.flags = oldFlags;
+ context.enclosingDeclaration = oldEnclosingDecl;
}
function serializeInterface(symbol, symbolName, modifierFlags) {
var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* Value */); }))];
addResult(ts.factory.createInterfaceDeclaration(
/*decorators*/ undefined,
- /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags);
+ /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures), constructSignatures), callSignatures), members)), modifierFlags);
}
function getNamespaceMembersForSerialization(symbol) {
return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
return !!(p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) ||
!(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.getEffectiveModifierFlags(p.valueDeclaration) & 32 /* Static */ && ts.isClassLike(p.valueDeclaration.parent));
}
+ function sanitizeJSDocImplements(clauses) {
+ var result = ts.mapDefined(clauses, function (e) {
+ var _a;
+ var oldEnclosing = context.enclosingDeclaration;
+ context.enclosingDeclaration = e;
+ var expr = e.expression;
+ if (ts.isEntityNameExpression(expr)) {
+ if (ts.isIdentifier(expr) && ts.idText(expr) === "") {
+ return cleanup(/*result*/ undefined); // Empty heritage clause, should be an error, but prefer emitting no heritage clauses to reemitting the empty one
+ }
+ var introducesError = void 0;
+ (_a = trackExistingEntityName(expr, context, includePrivateSymbol), introducesError = _a.introducesError, expr = _a.node);
+ if (introducesError) {
+ return cleanup(/*result*/ undefined);
+ }
+ }
+ return cleanup(ts.factory.createExpressionWithTypeArguments(expr, ts.map(e.typeArguments, function (a) {
+ return serializeExistingTypeNode(context, a, includePrivateSymbol, bundled)
+ || typeToTypeNodeHelper(getTypeFromTypeNode(a), context);
+ })));
+ function cleanup(result) {
+ context.enclosingDeclaration = oldEnclosing;
+ return result;
+ }
+ });
+ if (result.length === clauses.length) {
+ return result;
+ }
+ return undefined;
+ }
function serializeAsClass(symbol, localName, modifierFlags) {
var _a;
+ var originalDecl = ts.find(symbol.declarations, ts.isClassLike);
+ var oldEnclosing = context.enclosingDeclaration;
+ context.enclosingDeclaration = originalDecl || oldEnclosing;
var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
var classType = getDeclaredTypeOfClassOrInterface(symbol);
var baseTypes = getBaseTypes(classType);
- var implementsExpressions = ts.mapDefined(getImplementsTypes(classType), serializeImplementedType);
+ var originalImplements = originalDecl && ts.getEffectiveImplementsTypeNodes(originalDecl);
+ var implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements)
+ || ts.mapDefined(getImplementsTypes(classType), serializeImplementedType);
var staticType = getTypeOfSymbol(symbol);
var isClass = !!((_a = staticType.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration);
var staticBaseType = isClass
? getBaseConstructorTypeOfClass(staticType)
: anyType;
- var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(116 /* ImplementsKeyword */, implementsExpressions)]);
+ var heritageClauses = __spreadArray(__spreadArray([], !ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]), !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(116 /* ImplementsKeyword */, implementsExpressions)]);
var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
var publicSymbolProps = ts.filter(symbolProps, function (s) {
// `valueDeclaration` could be undefined if inherited from
!ts.some(getSignaturesOfType(staticType, 1 /* Construct */));
var constructors = isNonConstructableClassLikeInJsFile ?
[ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* Private */), [], /*body*/ undefined)] :
- serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 166 /* Constructor */);
+ serializeSignatures(1 /* Construct */, staticType, staticBaseType, 166 /* Constructor */);
var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
+ context.enclosingDeclaration = oldEnclosing;
addResult(ts.setTextRange(ts.factory.createClassDeclaration(
/*decorators*/ undefined,
- /*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);
+ /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures), staticMembers), constructors), publicProperties), privateProperties)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags);
}
function serializeAsAlias(symbol, localName, modifierFlags) {
var _a, _b, _c, _d, _e;
// import _x = require('y');
addResult(ts.factory.createImportEqualsDeclaration(
/*decorators*/ undefined,
- /*modifiers*/ undefined, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* None */);
+ /*modifiers*/ undefined,
+ /*isTypeOnly*/ false, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* None */);
// import x = _x.z
addResult(ts.factory.createImportEqualsDeclaration(
/*decorators*/ undefined,
- /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags);
+ /*modifiers*/ undefined,
+ /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags);
break;
}
// else fall through and treat commonjs require just like import=
var isLocalImport = !(target.flags & 512 /* ValueModule */) && !ts.isVariableDeclaration(node);
addResult(ts.factory.createImportEqualsDeclaration(
/*decorators*/ undefined,
- /*modifiers*/ undefined, ts.factory.createIdentifier(localName), isLocalImport
+ /*modifiers*/ undefined,
+ /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), isLocalImport
? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
: ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */);
break;
var varName = getUnusedName(name, symbol);
addResult(ts.factory.createImportEqualsDeclaration(
/*decorators*/ undefined,
- /*modifiers*/ undefined, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
+ /*modifiers*/ undefined,
+ /*isTypeOnly*/ false, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
serializeExportSpecifier(name, varName);
}
}
if (ts.isParameter(declaration)) {
var func = declaration.parent;
// For a parameter of a set accessor, use the type of the get accessor if one is present
- if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
+ if (func.kind === 168 /* SetAccessor */ && hasBindableName(func)) {
var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */);
if (getter) {
var getterSignature = getSignatureFromDeclaration(getter);
}
if (symbol.flags & 134217728 /* ModuleExports */) {
var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
+ var result = createSymbol(fileSymbol.flags, "exports");
+ result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : [];
+ result.parent = symbol;
+ result.target = fileSymbol;
+ if (fileSymbol.valueDeclaration)
+ result.valueDeclaration = fileSymbol.valueDeclaration;
+ if (fileSymbol.members)
+ result.members = new ts.Map(fileSymbol.members);
+ if (fileSymbol.exports)
+ result.exports = new ts.Map(fileSymbol.exports);
var members = ts.createSymbolTable();
- members.set("exports", fileSymbol);
+ members.set("exports", result);
return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
}
// Handle catch clause variables
var signatures = getSignaturesOfType(type, 1 /* Construct */);
if (signatures.length === 1) {
var s = signatures[0];
- return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType;
+ if (!s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s)) {
+ var paramType = getTypeOfParameter(s.parameters[0]);
+ return isTypeAny(paramType) || getElementTypeOfArrayType(paramType) === anyType;
+ }
}
return false;
}
return !!name && isLateBindableName(name);
}
/**
- * Indicates whether a declaration has a dynamic name that cannot be late-bound.
+ * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound.
*/
- function hasNonBindableDynamicName(node) {
- return ts.hasDynamicName(node) && !hasLateBindableName(node);
+ function hasBindableName(node) {
+ return !ts.hasDynamicName(node) || hasLateBindableName(node);
}
/**
* Indicates whether a declaration name is a dynamic name that cannot be late-bound.
}
}
else if (type.flags & 2097152 /* Intersection */) {
- return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
+ var types = ts.sameMap(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); });
+ return types !== type.types ? getIntersectionType(types) : type;
}
return needApparentType ? getApparentType(type) : type;
}
}
function cloneSignature(sig) {
var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
- /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 19 /* PropagatingFlags */);
+ /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */);
result.target = sig.target;
result.mapper = sig.mapper;
result.unionSignatures = sig.unionSignatures;
return result;
}
function getOptionalCallSignature(signature, callChainFlags) {
- if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) {
+ if ((signature.flags & 24 /* CallChainFlags */) === callChainFlags) {
return signature;
}
if (!signature.optionalCallSignatureCache) {
signature.optionalCallSignatureCache = {};
}
- var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer";
+ var key = callChainFlags === 8 /* IsInnerCallChain */ ? "inner" : "outer";
return signature.optionalCallSignatureCache[key]
|| (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
}
function createOptionalCallSignature(signature, callChainFlags) {
- 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.");
+ ts.Debug.assert(callChainFlags === 8 /* IsInnerCallChain */ || callChainFlags === 16 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both.");
var result = cloneSignature(signature);
result.flags |= callChainFlags;
return result;
function getDefaultConstructSignatures(classType) {
var baseConstructorType = getBaseConstructorTypeOfClass(classType);
var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
+ var declaration = ts.getClassLikeDeclarationOfSymbol(classType.symbol);
+ var isAbstract = !!declaration && ts.hasSyntacticModifier(declaration, 128 /* Abstract */);
if (baseSignatures.length === 0) {
- return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)];
+ return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, isAbstract ? 4 /* Abstract */ : 0 /* None */)];
}
var baseTypeNode = getBaseTypeNodeOfClass(classType);
var isJavaScript = ts.isInJSFile(baseTypeNode);
var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
sig.typeParameters = classType.localTypeParameters;
sig.resolvedReturnType = classType;
+ sig.flags = isAbstract ? sig.flags | 4 /* Abstract */ : sig.flags & ~4 /* Abstract */;
result.push(sig);
}
}
if (signatures !== masterList) {
var signature_1 = signatures[0];
ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
- results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
+ results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
if (!results) {
return "break";
}
}
return result || ts.emptyArray;
}
- function combineUnionThisParam(left, right) {
+ function compareTypeParametersIdentical(sourceParams, targetParams) {
+ if (sourceParams.length !== targetParams.length) {
+ return false;
+ }
+ var mapper = createTypeMapper(targetParams, sourceParams);
+ for (var i = 0; i < sourceParams.length; i++) {
+ var source = sourceParams[i];
+ var target = targetParams[i];
+ if (source === target)
+ continue;
+ // We instantiate the target type parameter constraints into the source types so we can recognize `<T, U extends T>` as the same as `<A, B extends A>`
+ if (!isTypeIdenticalTo(getConstraintFromTypeParameter(source) || unknownType, instantiateType(getConstraintFromTypeParameter(target) || unknownType, mapper)))
+ return false;
+ // We don't compare defaults - we just use the type parameter defaults from the first signature that seems to match.
+ // It might make sense to combine these defaults in the future, but doing so intelligently requires knowing
+ // if the parameter is used covariantly or contravariantly (so we intersect if it's used like a parameter or union if used like a return type)
+ // and, since it's just an inference _default_, just picking one arbitrarily works OK.
+ }
+ return true;
+ }
+ function combineUnionThisParam(left, right, mapper) {
if (!left || !right) {
return left || right;
}
// A signature `this` type might be a read or a write position... It's very possible that it should be invariant
// and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
// permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
- var thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]);
+ var thisType = getIntersectionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]);
return createSymbolWithType(left, thisType);
}
- function combineUnionParameters(left, right) {
+ function combineUnionParameters(left, right, mapper) {
var leftCount = getParameterCount(left);
var rightCount = getParameterCount(right);
var longest = leftCount >= rightCount ? left : right;
var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
for (var i = 0; i < longestCount; i++) {
var longestParamType = tryGetTypeAtPosition(longest, i);
+ if (longest === right) {
+ longestParamType = instantiateType(longestParamType, mapper);
+ }
var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
+ if (shorter === right) {
+ shorterParamType = instantiateType(shorterParamType, mapper);
+ }
var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
if (needsExtraRestElement) {
var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
+ if (shorter === right) {
+ restParamSymbol.type = instantiateType(restParamSymbol.type, mapper);
+ }
params[longestCount] = restParamSymbol;
}
return params;
}
function combineSignaturesOfUnionMembers(left, right) {
+ var typeParams = left.typeParameters || right.typeParameters;
+ var paramMapper;
+ if (left.typeParameters && right.typeParameters) {
+ paramMapper = createTypeMapper(right.typeParameters, left.typeParameters);
+ // We just use the type parameter defaults from the first signature
+ }
var declaration = left.declaration;
- var params = combineUnionParameters(left, right);
- var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
+ var params = combineUnionParameters(left, right, paramMapper);
+ var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter, paramMapper);
var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
- var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params,
+ var result = createSignature(declaration, typeParams, thisParam, params,
/*resolvedReturnType*/ undefined,
- /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 19 /* PropagatingFlags */);
+ /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */);
result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
+ if (paramMapper) {
+ result.mapper = left.mapper && left.unionSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper;
+ }
return result;
}
function getUnionIndexInfo(types, kind) {
var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
if (symbol.flags & 16 /* Function */) {
constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
- createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 19 /* PropagatingFlags */) :
+ createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */) :
undefined; }));
}
if (!constructSignatures.length) {
return type;
}
if (type.flags & 1048576 /* Union */) {
- return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
+ return mapType(type, getLowerBoundOfKeyType);
}
if (type.flags & 2097152 /* Intersection */) {
return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
}
return type;
}
+ function getIsLateCheckFlag(s) {
+ return ts.getCheckFlags(s) & 4096 /* Late */;
+ }
/** Resolve the members of a mapped type { [P in K]: T } */
function resolveMappedTypeMembers(type) {
var members = ts.createSymbolTable();
var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
!(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
- var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
+ var lateFlag = modifiersProp ? getIsLateCheckFlag(modifiersProp) : 0;
+ var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, lateFlag | 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
prop.mappedType = type;
prop.nameType = propNameType;
prop.keyType = keyType;
if (type.resolvedBaseConstraint) {
return type.resolvedBaseConstraint;
}
- var nonTerminating = false;
var stack = [];
return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type);
function getImmediateBaseConstraint(t) {
if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
return circularConstraintType;
}
- if (constraintDepth >= 50) {
- // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
- // very high likelihood we're dealing with an infinite generic type that perpetually generates
- // new type identities as we descend into it. We stop the recursion here and mark this type
- // and the outer types as having circular constraints.
- ts.tracing.instant("check" /* Check */, "getImmediateBaseConstraint_DepthLimit", { typeId: t.id, originalTypeId: type.id, depth: constraintDepth });
- error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
- nonTerminating = true;
- return t.immediateBaseConstraint = noConstraintType;
- }
var result = void 0;
- if (!isDeeplyNestedType(t, stack, stack.length)) {
+ // We always explore at least 10 levels of nested constraints. Thereafter, we continue to explore
+ // up to 50 levels of nested constraints provided there are no "deeply nested" types on the stack
+ // (i.e. no types for which five instantiations have been recorded on the stack). If we reach 50
+ // levels of nesting, we are presumably exploring a repeating pattern with a long cycle that hasn't
+ // yet triggered the deeply nested limiter. We have no test cases that actually get to 50 levels of
+ // nesting, so it is effectively just a safety stop.
+ if (stack.length < 10 || stack.length < 50 && !isDeeplyNestedType(t, stack, stack.length)) {
stack.push(t);
- constraintDepth++;
result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
- constraintDepth--;
stack.pop();
}
if (!popTypeResolution()) {
}
result = circularConstraintType;
}
- if (nonTerminating) {
- result = circularConstraintType;
- }
t.immediateBaseConstraint = result || noConstraintType;
}
return t.immediateBaseConstraint;
if (t.flags & 3145728 /* UnionOrIntersection */) {
var types = t.types;
var baseTypes = [];
+ var different = false;
for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
var type_3 = types_8[_i];
var baseType = getBaseConstraint(type_3);
if (baseType) {
+ if (baseType !== type_3) {
+ different = true;
+ }
baseTypes.push(baseType);
}
+ else {
+ different = true;
+ }
+ }
+ if (!different) {
+ return t;
}
return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
}
if (t.flags & 16777216 /* Conditional */) {
var constraint = getConstraintFromConditionalType(t);
- constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
- var result = constraint && getBaseConstraint(constraint);
- constraintDepth--;
- return result;
+ return constraint && getBaseConstraint(constraint);
}
if (t.flags & 33554432 /* Substitution */) {
return getBaseConstraint(t.substitute);
// that type may need further reduction to remove empty intersections.
return getReducedType(getApparentType(getReducedType(type)));
}
- function createUnionOrIntersectionProperty(containingType, name) {
+ function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) {
var singleProp;
var propSet;
var indexTypes;
var current = _a[_i];
var type = getApparentType(current);
if (!(type === errorType || type.flags & 131072 /* Never */)) {
- var prop = getPropertyOfType(type, name);
+ var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment);
var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
if (prop) {
if (isUnion) {
// constituents, in which case the isPartial flag is set when the containing type is union type. We need
// these partial properties when identifying discriminant properties, but otherwise they are filtered out
// and do not appear to be present in the union type.
- function getUnionOrIntersectionProperty(type, name) {
- var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
- var property = properties.get(name);
+ function getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment) {
+ var _a, _b;
+ var property = ((_a = type.propertyCacheWithoutObjectFunctionPropertyAugment) === null || _a === void 0 ? void 0 : _a.get(name)) ||
+ !skipObjectFunctionPropertyAugment ? (_b = type.propertyCache) === null || _b === void 0 ? void 0 : _b.get(name) : undefined;
if (!property) {
- property = createUnionOrIntersectionProperty(type, name);
+ property = createUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
if (property) {
+ var properties = skipObjectFunctionPropertyAugment ? type.propertyCacheWithoutObjectFunctionPropertyAugment || (type.propertyCacheWithoutObjectFunctionPropertyAugment = ts.createSymbolTable()) : type.propertyCache || (type.propertyCache = ts.createSymbolTable());
properties.set(name, property);
}
}
return property;
}
- function getPropertyOfUnionOrIntersectionType(type, name) {
- var property = getUnionOrIntersectionProperty(type, name);
+ function getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment) {
+ var property = getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
// We need to filter out partial properties in union types
return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
}
* @param type a type to look up property from
* @param name a name of property to look up in a given type
*/
- function getPropertyOfType(type, name) {
+ function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment) {
type = getReducedApparentType(type);
if (type.flags & 524288 /* Object */) {
var resolved = resolveStructuredTypeMembers(type);
if (symbol && symbolIsValue(symbol)) {
return symbol;
}
+ if (skipObjectFunctionPropertyAugment)
+ return undefined;
var functionType = resolved === anyFunctionType ? globalFunctionType :
resolved.callSignatures.length ? globalCallableFunctionType :
resolved.constructSignatures.length ? globalNewableFunctionType :
return getPropertyOfObjectType(globalObjectType, name);
}
if (type.flags & 3145728 /* UnionOrIntersection */) {
- return getPropertyOfUnionOrIntersectionType(type, name);
+ return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment);
}
return undefined;
}
!ts.hasJSDocParameterTags(declaration) &&
!ts.getJSDocType(declaration);
if (isUntypedSignatureInJSFile) {
- flags |= 16 /* IsUntypedSignatureInJSFile */;
+ flags |= 32 /* IsUntypedSignatureInJSFile */;
}
// If this is a JSDoc construct signature, then skip the first parameter in the
// parameter list. The first parameter represents the return type of the construct
}
// If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) &&
- !hasNonBindableDynamicName(declaration) &&
+ hasBindableName(declaration) &&
(!hasThisParameter || !thisParameter)) {
var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */;
var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
flags |= 1 /* HasRestParameter */;
}
+ if (ts.isConstructorTypeNode(declaration) && ts.hasSyntacticModifier(declaration, 128 /* Abstract */) ||
+ ts.isConstructorDeclaration(declaration) && ts.hasSyntacticModifier(declaration.parent, 128 /* Abstract */)) {
+ flags |= 4 /* Abstract */;
+ }
links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters,
/*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
}
return false;
switch (node.kind) {
case 78 /* Identifier */:
- return node.escapedText === "arguments" && ts.isExpressionNode(node);
+ return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol;
case 163 /* PropertyDeclaration */:
case 165 /* MethodDeclaration */:
case 167 /* GetAccessor */:
case 168 /* SetAccessor */:
return node.name.kind === 158 /* ComputedPropertyName */
&& traverse(node.name);
+ case 201 /* PropertyAccessExpression */:
+ case 202 /* ElementAccessExpression */:
+ return traverse(node.expression);
default:
return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
}
return errorType;
}
var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
- signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
+ signature.unionSignatures ? instantiateType(getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */), signature.mapper) :
getReturnTypeFromAnnotation(signature.declaration) ||
(ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
- if (signature.flags & 4 /* IsInnerCallChain */) {
+ if (signature.flags & 8 /* IsInnerCallChain */) {
type = addOptionalTypeMarker(type);
}
- else if (signature.flags & 8 /* IsOuterCallChain */) {
+ else if (signature.flags & 16 /* IsOuterCallChain */) {
type = getOptionalType(type);
}
if (!popTypeResolution()) {
if (typeNode) {
return getTypeFromTypeNode(typeNode);
}
- if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
+ if (declaration.kind === 167 /* GetAccessor */ && hasBindableName(declaration)) {
var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
if (jsDocType) {
return jsDocType;
else if (grandParent.kind === 194 /* TemplateLiteralTypeSpan */) {
inferences = ts.append(inferences, stringType);
}
+ // When an 'infer T' declaration is in the constraint position of a mapped type, we infer a 'keyof any'
+ // constraint.
+ else if (grandParent.kind === 159 /* TypeParameter */ && grandParent.parent.kind === 190 /* MappedType */) {
+ inferences = ts.append(inferences, keyofConstraintType);
+ }
}
}
}
}
return result;
}
+ function getAliasId(aliasSymbol, aliasTypeArguments) {
+ return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : "";
+ }
// This function is used to propagate certain flags when creating new object type references and union types.
// It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
// of an object literal or the anyFunctionType. This is because there are operations in the type checker
type.resolvedTypeArguments = source.resolvedTypeArguments;
return type;
}
- function createDeferredTypeReference(target, node, mapper) {
- var aliasSymbol = getAliasSymbolForTypeNode(node);
- var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
+ function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) {
+ if (!aliasSymbol) {
+ aliasSymbol = getAliasSymbolForTypeNode(node);
+ var localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
+ aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments;
+ }
var type = createObjectType(4 /* Reference */, target.symbol);
type.target = target;
type.node = node;
type.mapper = mapper;
type.aliasSymbol = aliasSymbol;
- type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments;
+ type.aliasTypeArguments = aliasTypeArguments;
return type;
}
function getTypeArguments(type) {
}
return checkNoTypeArguments(node, symbol) ? type : errorType;
}
- function getTypeAliasInstantiation(symbol, typeArguments) {
+ function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) {
var type = getDeclaredTypeOfSymbol(symbol);
if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName) && typeArguments && typeArguments.length === 1) {
return getStringMappingType(symbol, typeArguments[0]);
}
var links = getSymbolLinks(symbol);
var typeParameters = links.typeParameters;
- var id = getTypeListId(typeArguments);
+ var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments);
var instantiation = links.instantiations.get(id);
if (!instantiation) {
- links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
+ links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments));
}
return instantiation;
}
ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
return errorType;
}
- return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node));
+ var aliasSymbol = getAliasSymbolForTypeNode(node);
+ return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
}
return checkNoTypeArguments(node, symbol) ? type : errorType;
}
// is true for each of the synthesized type parameters.
function createTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
var arity = elementFlags.length;
- var minLength = ts.findLastIndex(elementFlags, function (f) { return !!(f & (1 /* Required */ | 8 /* Variadic */)); }) + 1;
+ var minLength = ts.countWhere(elementFlags, function (f) { return !!(f & (1 /* Required */ | 8 /* Variadic */)); });
var typeParameters;
var properties = [];
var combinedFlags = 0;
return type;
}
function createNormalizedTypeReference(target, typeArguments) {
- return target.objectFlags & 8 /* Tuple */ && target.combinedFlags & 8 /* Variadic */ ?
- createNormalizedTupleType(target, typeArguments) :
- createTypeReference(target, typeArguments);
+ return target.objectFlags & 8 /* Tuple */ ? createNormalizedTupleType(target, typeArguments) : createTypeReference(target, typeArguments);
}
function createNormalizedTupleType(target, elementTypes) {
var _a, _b, _c;
- // Transform [A, ...(X | Y | Z)] into [A, ...X] | [A, ...Y] | [A, ...Z]
- var unionIndex = ts.findIndex(elementTypes, function (t, i) { return !!(target.elementFlags[i] & 8 /* Variadic */ && t.flags & (131072 /* Never */ | 1048576 /* Union */)); });
- if (unionIndex >= 0) {
- return checkCrossProductUnion(ts.map(elementTypes, function (t, i) { return target.elementFlags[i] & 8 /* Variadic */ ? t : unknownType; })) ?
- mapType(elementTypes[unionIndex], function (t) { return createNormalizedTupleType(target, ts.replaceElement(elementTypes, unionIndex, t)); }) :
- errorType;
- }
- // If there are no variadic elements with non-generic types, just create a type reference with the same target type.
- var spreadIndex = ts.findIndex(elementTypes, function (t, i) { return !!(target.elementFlags[i] & 8 /* Variadic */) && !(t.flags & 58982400 /* InstantiableNonPrimitive */) && !isGenericMappedType(t); });
- if (spreadIndex < 0) {
+ if (!(target.combinedFlags & 14 /* NonRequired */)) {
+ // No need to normalize when we only have regular required elements
return createTypeReference(target, elementTypes);
}
- // We have non-generic variadic elements that need normalization.
+ if (target.combinedFlags & 8 /* Variadic */) {
+ // Transform [A, ...(X | Y | Z)] into [A, ...X] | [A, ...Y] | [A, ...Z]
+ var unionIndex_1 = ts.findIndex(elementTypes, function (t, i) { return !!(target.elementFlags[i] & 8 /* Variadic */ && t.flags & (131072 /* Never */ | 1048576 /* Union */)); });
+ if (unionIndex_1 >= 0) {
+ return checkCrossProductUnion(ts.map(elementTypes, function (t, i) { return target.elementFlags[i] & 8 /* Variadic */ ? t : unknownType; })) ?
+ mapType(elementTypes[unionIndex_1], function (t) { return createNormalizedTupleType(target, ts.replaceElement(elementTypes, unionIndex_1, t)); }) :
+ errorType;
+ }
+ }
+ // We have optional, rest, or variadic elements that may need normalizing. Normalization ensures that all variadic
+ // elements are generic and that the tuple type has one of the following layouts, disregarding variadic elements:
+ // (1) Zero or more required elements, followed by zero or more optional elements, followed by zero or one rest element.
+ // (2) Zero or more required elements, followed by a rest element, followed by zero or more required elements.
+ // In either layout, zero or more generic variadic elements may be present at any location.
var expandedTypes = [];
var expandedFlags = [];
var expandedDeclarations = [];
- var optionalIndex = -1;
- var restTypes;
+ var lastRequiredIndex = -1;
+ var firstRestIndex = -1;
+ var lastOptionalOrRestIndex = -1;
var _loop_13 = function (i) {
var type = elementTypes[i];
var flags = target.elementFlags[i];
if (flags & 8 /* Variadic */) {
if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) {
- // Generic variadic elements stay as they are (except following a rest element).
- addElementOrRest(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]);
+ // Generic variadic elements stay as they are.
+ addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]);
}
else if (isTupleType(type)) {
+ var elements = getTypeArguments(type);
+ if (elements.length + expandedTypes.length >= 10000) {
+ error(currentNode, ts.isPartOfTypeNode(currentNode)
+ ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent
+ : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent);
+ return { value: errorType };
+ }
// Spread variadic elements with tuple types into the resulting tuple.
- ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElementOrRest(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); });
+ ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); });
}
else {
// Treat everything else as an array type and create a rest element.
- addElementOrRest(isArrayLikeType(type) && getIndexTypeOfType(type, 1 /* Number */) || errorType, 4 /* Rest */, (_b = target.labeledElementDeclarations) === null || _b === void 0 ? void 0 : _b[i]);
+ addElement(isArrayLikeType(type) && getIndexTypeOfType(type, 1 /* Number */) || errorType, 4 /* Rest */, (_b = target.labeledElementDeclarations) === null || _b === void 0 ? void 0 : _b[i]);
}
}
else {
// Copy other element kinds with no change.
- addElementOrRest(type, flags, (_c = target.labeledElementDeclarations) === null || _c === void 0 ? void 0 : _c[i]);
+ addElement(type, flags, (_c = target.labeledElementDeclarations) === null || _c === void 0 ? void 0 : _c[i]);
}
};
for (var i = 0; i < elementTypes.length; i++) {
- _loop_13(i);
+ var state_4 = _loop_13(i);
+ if (typeof state_4 === "object")
+ return state_4.value;
}
- if (restTypes) {
- // Create a union of the collected rest element types.
- expandedTypes[expandedTypes.length - 1] = getUnionType(restTypes);
+ // Turn optional elements preceding the last required element into required elements
+ for (var i = 0; i < lastRequiredIndex; i++) {
+ if (expandedFlags[i] & 2 /* Optional */)
+ expandedFlags[i] = 1 /* Required */;
+ }
+ if (firstRestIndex >= 0 && firstRestIndex < lastOptionalOrRestIndex) {
+ // Turn elements between first rest and last optional/rest into a single rest element
+ expandedTypes[firstRestIndex] = getUnionType(ts.sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), function (t, i) { return expandedFlags[firstRestIndex + i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t; }));
+ expandedTypes.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
+ expandedFlags.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
+ expandedDeclarations === null || expandedDeclarations === void 0 ? void 0 : expandedDeclarations.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
}
var tupleTarget = getTupleTargetType(expandedFlags, target.readonly, expandedDeclarations);
return tupleTarget === emptyGenericType ? emptyObjectType :
expandedFlags.length ? createTypeReference(tupleTarget, expandedTypes) :
tupleTarget;
- function addElementOrRest(type, flags, declaration) {
- if (restTypes) {
- // A rest element was previously added, so simply collect the type of this element.
- restTypes.push(flags & 8 /* Variadic */ ? getIndexedAccessType(type, numberType) : type);
+ function addElement(type, flags, declaration) {
+ if (flags & 1 /* Required */) {
+ lastRequiredIndex = expandedFlags.length;
+ }
+ if (flags & 4 /* Rest */ && firstRestIndex < 0) {
+ firstRestIndex = expandedFlags.length;
+ }
+ if (flags & (2 /* Optional */ | 4 /* Rest */)) {
+ lastOptionalOrRestIndex = expandedFlags.length;
+ }
+ expandedTypes.push(type);
+ expandedFlags.push(flags);
+ if (expandedDeclarations && declaration) {
+ expandedDeclarations.push(declaration);
}
else {
- if (flags & 1 /* Required */ && optionalIndex >= 0) {
- // Turn preceding optional elements into required elements
- for (var i = optionalIndex; i < expandedFlags.length; i++) {
- if (expandedFlags[i] & 2 /* Optional */)
- expandedFlags[i] = 1 /* Required */;
- }
- optionalIndex = -1;
- }
- else if (flags & 2 /* Optional */ && optionalIndex < 0) {
- optionalIndex = expandedFlags.length;
- }
- else if (flags & 4 /* Rest */) {
- // Start collecting element types when a rest element is added.
- restTypes = [type];
- }
- expandedTypes.push(type);
- expandedFlags.push(flags);
- if (expandedDeclarations && declaration) {
- expandedDeclarations.push(declaration);
- }
- else {
- expandedDeclarations = undefined;
- }
+ expandedDeclarations = undefined;
}
}
}
function getKnownKeysOfTupleType(type) {
return getUnionType(ts.append(ts.arrayOf(type.target.fixedLength, function (i) { return getLiteralType("" + i); }), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType)));
}
+ // Return count of starting consecutive tuple elements of the given kind(s)
+ function getStartElementCount(type, flags) {
+ var index = ts.findIndex(type.elementFlags, function (f) { return !(f & flags); });
+ return index >= 0 ? index : type.elementFlags.length;
+ }
+ // Return count of ending consecutive tuple elements of the given kind(s)
+ function getEndElementCount(type, flags) {
+ return type.elementFlags.length - ts.findLastIndex(type.elementFlags, function (f) { return !(f & flags); }) - 1;
+ }
function getTypeFromOptionalTypeNode(node) {
var type = getTypeFromTypeNode(node.type);
return strictNullChecks ? getOptionalType(type) : type;
function addTypeToUnion(typeSet, includes, type) {
var flags = type.flags;
if (flags & 1048576 /* Union */) {
- return addTypesToUnion(typeSet, includes, type.types);
+ return addTypesToUnion(typeSet, includes | (isNamedUnionType(type) ? 1048576 /* Union */ : 0), type.types);
}
// We ignore 'never' types in unions
if (!(flags & 131072 /* Never */)) {
}
return includes;
}
- function isSetOfLiteralsFromSameEnum(types) {
- var first = types[0];
- if (first.flags & 1024 /* EnumLiteral */) {
- var firstEnum = getParentOfSymbol(first.symbol);
- for (var i = 1; i < types.length; i++) {
- var other = types[i];
- if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
- return false;
- }
- }
- return true;
- }
- return false;
- }
- function removeSubtypes(types, primitivesOnly) {
+ function removeSubtypes(types, hasObjectTypes) {
+ // We assume that redundant primitive types have already been removed from the types array and that there
+ // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty
+ // object types, and if none of those are present we can exclude primitive types from the subtype check.
+ var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); });
var len = types.length;
- if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
- return true;
- }
var i = len;
var count = 0;
while (i > 0) {
i--;
var source = types[i];
- for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
- var target = types_11[_i];
- if (source !== target) {
- if (count === 100000) {
- // After 100000 subtype checks we estimate the remaining amount of work by assuming the
- // same ratio of checks per element. If the estimated number of remaining type checks is
- // greater than an upper limit we deem the union type too complex to represent. The
- // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
- // caps union types at 5000 unique literal types and 1000 unique object types.
- var estimatedCount = (count / (len - i)) * len;
- if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
- ts.tracing.instant("check" /* Check */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) });
- error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
- return false;
+ if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) {
+ for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
+ var target = types_11[_i];
+ if (source !== target) {
+ if (count === 100000) {
+ // After 100000 subtype checks we estimate the remaining amount of work by assuming the
+ // same ratio of checks per element. If the estimated number of remaining type checks is
+ // greater than 1M we deem the union type too complex to represent. This for example
+ // caps union types at 1000 unique object types.
+ var estimatedCount = (count / (len - i)) * len;
+ if (estimatedCount > 1000000) {
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) });
+ error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
+ return false;
+ }
+ }
+ count++;
+ if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
+ !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
+ isTypeDerivedFrom(source, target))) {
+ ts.orderedRemoveItemAt(types, i);
+ break;
}
- }
- count++;
- if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
- !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
- isTypeDerivedFrom(source, target))) {
- ts.orderedRemoveItemAt(types, i);
- break;
}
}
}
}
return true;
}
- function removeRedundantLiteralTypes(types, includes) {
+ function removeRedundantLiteralTypes(types, includes, reduceVoidUndefined) {
var i = types.length;
while (i > 0) {
i--;
var t = types[i];
- var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
- t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
- t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
- t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
+ var flags = t.flags;
+ var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
+ flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
+ flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
+ flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
+ reduceVoidUndefined && flags & 32768 /* Undefined */ && includes & 16384 /* Void */ ||
isFreshLiteralType(t) && containsType(types, t.regularType);
if (remove) {
ts.orderedRemoveItemAt(types, i);
}
}
}
+ function isNamedUnionType(type) {
+ return !!(type.flags & 1048576 /* Union */ && (type.aliasSymbol || type.origin));
+ }
+ function addNamedUnions(namedUnions, types) {
+ for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
+ var t = types_12[_i];
+ if (t.flags & 1048576 /* Union */) {
+ var origin = t.origin;
+ if (t.aliasSymbol || origin && !(origin.flags & 1048576 /* Union */)) {
+ ts.pushIfUnique(namedUnions, t);
+ }
+ else if (origin && origin.flags & 1048576 /* Union */) {
+ addNamedUnions(namedUnions, origin.types);
+ }
+ }
+ }
+ }
+ function createOriginUnionOrIntersectionType(flags, types) {
+ var result = createOriginType(flags);
+ result.types = types;
+ return result;
+ }
// We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
// flag is specified we also reduce the constituent type set to only include types that aren't subtypes
// of other types. Subtype reduction is expensive for large union types and is possible only when union
// expression constructs such as array literals and the || and ?: operators). Named types can
// circularly reference themselves and therefore cannot be subtype reduced during their declaration.
// For example, "type Item = string | (() => Item" is a named type that circularly references itself.
- function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
+ function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments, origin) {
if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
if (types.length === 0) {
return neverType;
if (includes & 3 /* AnyOrUnknown */) {
return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
}
- switch (unionReduction) {
- case 1 /* Literal */:
- if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
- removeRedundantLiteralTypes(typeSet, includes);
- }
- if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) {
- removeStringLiteralsMatchedByTemplateLiterals(typeSet);
- }
- break;
- case 2 /* Subtype */:
- if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
- return errorType;
- }
- break;
+ if (unionReduction & (1 /* Literal */ | 2 /* Subtype */)) {
+ if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) {
+ removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2 /* Subtype */));
+ }
+ if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) {
+ removeStringLiteralsMatchedByTemplateLiterals(typeSet);
+ }
+ }
+ if (unionReduction & 2 /* Subtype */) {
+ if (!removeSubtypes(typeSet, !!(includes & 524288 /* Object */))) {
+ return errorType;
+ }
}
if (typeSet.length === 0) {
return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
neverType;
}
}
- var objectFlags = (includes & 469647395 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
+ if (!origin && includes & 1048576 /* Union */) {
+ var namedUnions = [];
+ addNamedUnions(namedUnions, types);
+ var reducedTypes = [];
+ var _loop_15 = function (t) {
+ if (!ts.some(namedUnions, function (union) { return containsType(union.types, t); })) {
+ reducedTypes.push(t);
+ }
+ };
+ for (var _i = 0, typeSet_1 = typeSet; _i < typeSet_1.length; _i++) {
+ var t = typeSet_1[_i];
+ _loop_15(t);
+ }
+ if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) {
+ return namedUnions[0];
+ }
+ // We create a denormalized origin type only when the union was created from one or more named unions
+ // (unions with alias symbols or origins) and when there is no overlap between those named unions.
+ var namedTypesCount = ts.reduceLeft(namedUnions, function (sum, union) { return sum + union.types.length; }, 0);
+ if (namedTypesCount + reducedTypes.length === typeSet.length) {
+ for (var _a = 0, namedUnions_1 = namedUnions; _a < namedUnions_1.length; _a++) {
+ var t = namedUnions_1[_a];
+ insertType(reducedTypes, t);
+ }
+ origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes);
+ }
+ }
+ var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
(includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0);
- return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments);
+ return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin);
}
function getUnionTypePredicate(signatures) {
var first;
function typePredicateKindsMatch(a, b) {
return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
}
+ function createUnionType(types, aliasSymbol, aliasTypeArguments, origin) {
+ var result = createType(1048576 /* Union */);
+ result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
+ result.types = types;
+ result.origin = origin;
+ result.aliasSymbol = aliasSymbol;
+ result.aliasTypeArguments = aliasTypeArguments;
+ return result;
+ }
// This function assumes the constituent type list is sorted and deduplicated.
- function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
+ function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments, origin) {
if (types.length === 0) {
return neverType;
}
if (types.length === 1) {
return types[0];
}
- var id = getTypeListId(types);
+ var typeKey = !origin ? getTypeListId(types) :
+ origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) :
+ origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) :
+ "#" + origin.type.id;
+ var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments);
var type = unionTypes.get(id);
if (!type) {
- type = createType(1048576 /* Union */);
+ type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin);
+ type.objectFlags |= objectFlags;
unionTypes.set(id, type);
- type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
- type.types = types;
- /*
- Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
- For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
- (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
- It's important that we create equivalent union types only once, so that's an unfortunate side effect.
- */
- type.aliasSymbol = aliasSymbol;
- type.aliasTypeArguments = aliasTypeArguments;
}
return type;
}
// Add the given types to the given type set. Order is preserved, freshness is removed from literal
// types, duplicates are removed, and nested types of the given kind are flattened into the set.
function addTypesToIntersection(typeSet, includes, types) {
- for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
- var type = types_12[_i];
+ for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
+ var type = types_13[_i];
includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
}
return includes;
var result = createType(2097152 /* Intersection */);
result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
result.types = types;
- result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
+ result.aliasSymbol = aliasSymbol;
result.aliasTypeArguments = aliasTypeArguments;
return result;
}
if (typeSet.length === 1) {
return typeSet[0];
}
- var id = getTypeListId(typeSet);
+ var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments);
var result = intersectionTypes.get(id);
if (!result) {
if (includes & 1048576 /* Union */) {
result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
}
else {
- // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
- // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
- // If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
+ // We are attempting to construct a type of the form X & (A | B) & (C | D). Transform this into a type of
+ // the form X & A & C | X & A & D | X & B & C | X & B & D. If the estimated size of the resulting union type
+ // exceeds 100000 constituents, report an error.
if (!checkCrossProductUnion(typeSet)) {
return errorType;
}
- var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
- var unionType = typeSet[unionIndex_1];
- result = getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
+ var constituents = getCrossProductIntersections(typeSet);
+ // We attach a denormalized origin type when at least one constituent of the cross-product union is an
+ // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions).
+ var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* Intersection */); }) ? createOriginUnionOrIntersectionType(2097152 /* Intersection */, typeSet) : undefined;
+ result = getUnionType(constituents, 1 /* Literal */, aliasSymbol, aliasTypeArguments, origin);
}
}
else {
}
return result;
}
+ function getCrossProductUnionSize(types) {
+ return ts.reduceLeft(types, function (n, t) { return t.flags & 1048576 /* Union */ ? n * t.types.length : t.flags & 131072 /* Never */ ? 0 : n; }, 1);
+ }
function checkCrossProductUnion(types) {
- var size = ts.reduceLeft(types, function (n, t) { return n * (t.flags & 1048576 /* Union */ ? t.types.length : t.flags & 131072 /* Never */ ? 0 : 1); }, 1);
+ var size = getCrossProductUnionSize(types);
if (size >= 100000) {
- ts.tracing.instant("check" /* Check */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size });
error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
return false;
}
return true;
}
+ function getCrossProductIntersections(types) {
+ var count = getCrossProductUnionSize(types);
+ var intersections = [];
+ for (var i = 0; i < count; i++) {
+ var constituents = types.slice();
+ var n = i;
+ for (var j = types.length - 1; j >= 0; j--) {
+ if (types[j].flags & 1048576 /* Union */) {
+ var sourceTypes = types[j].types;
+ var length_5 = sourceTypes.length;
+ constituents[j] = sourceTypes[n % length_5];
+ n = Math.floor(n / length_5);
+ }
+ }
+ var t = getIntersectionType(constituents);
+ if (!(t.flags & 131072 /* Never */))
+ intersections.push(t);
+ }
+ return intersections;
+ }
function getTypeFromIntersectionTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
result.stringsOnly = stringsOnly;
return result;
}
+ function createOriginIndexType(type) {
+ var result = createOriginType(4194304 /* Index */);
+ result.type = type;
+ return result;
+ }
function getIndexTypeForGenericType(type, stringsOnly) {
return stringsOnly ?
type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
}
+ function instantiateTypeAsMappedNameType(nameType, type, t) {
+ return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t));
+ }
function getIndexTypeForMappedType(type, noIndexSignatures) {
var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); });
var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType);
+ // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well
+ // since they won't appear in the constraint, due to subtype reducing with the string/number index types
+ var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type)));
return nameType ?
- mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) :
+ getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) :
constraint;
}
- // Ordinarily we reduce a keyof M where M is a mapped type { [P in K as N<P>]: X } to simply N<K>. This however presumes
- // that N distributes over union types, i.e. that N<A | B | C> is equivalent to N<A> | N<B> | N<C>. That presumption is
- // generally true, except when N is a non-distributive conditional type or an instantiable type with non-distributive
- // conditional type as a constituent. In those cases, we cannot reduce keyof M and need to preserve it as is.
- function isNonDistributiveNameType(type) {
- return !!(type && (type.flags & 16777216 /* Conditional */ && !type.root.isDistributive ||
- type.flags & (3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */) && ts.some(type.types, isNonDistributiveNameType) ||
- type.flags & (4194304 /* Index */ | 268435456 /* StringMapping */) && isNonDistributiveNameType(type.type) ||
- type.flags & 8388608 /* IndexedAccess */ && isNonDistributiveNameType(type.indexType) ||
- type.flags & 33554432 /* Substitution */ && isNonDistributiveNameType(type.substitute)));
+ // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N<P>]: X }, to simply N<K>. This however presumes
+ // that N distributes over union types, i.e. that N<A | B | C> is equivalent to N<A> | N<B> | N<C>. That presumption may not
+ // be true when N is a non-distributive conditional type or an instantiable type with a non-distributive conditional type as
+ // a constituent. In those cases, we cannot reduce keyof M and need to preserve it as is.
+ function maybeNonDistributiveNameType(type) {
+ return !!(type && (type.flags & 16777216 /* Conditional */ && (!type.root.isDistributive || maybeNonDistributiveNameType(type.checkType)) ||
+ type.flags & (3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */) && ts.some(type.types, maybeNonDistributiveNameType) ||
+ type.flags & (4194304 /* Index */ | 268435456 /* StringMapping */) && maybeNonDistributiveNameType(type.type) ||
+ type.flags & 8388608 /* IndexedAccess */ && maybeNonDistributiveNameType(type.indexType) ||
+ type.flags & 33554432 /* Substitution */ && maybeNonDistributiveNameType(type.substitute)));
}
function getLiteralTypeFromPropertyName(name) {
if (ts.isPrivateIdentifier(name)) {
}
return neverType;
}
- function getLiteralTypeFromProperties(type, include) {
- return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
+ function getLiteralTypeFromProperties(type, include, includeOrigin) {
+ var origin = includeOrigin && (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */) || type.aliasSymbol) ? createOriginIndexType(type) : undefined;
+ return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }), 1 /* Literal */,
+ /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, origin);
}
function getNonEnumNumberIndexInfo(type) {
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
}
function getIndexType(type, stringsOnly, noIndexSignatures) {
if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
+ var includeOrigin = stringsOnly === keyofStringsOnly && !noIndexSignatures;
type = getReducedType(type);
return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
- type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && isNonDistributiveNameType(getNameTypeFromMappedType(type)) ? getIndexTypeForGenericType(type, stringsOnly) :
+ type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && maybeNonDistributiveNameType(getNameTypeFromMappedType(type)) ? getIndexTypeForGenericType(type, stringsOnly) :
ts.getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, noIndexSignatures) :
type === wildcardType ? wildcardType :
type.flags & 2 /* Unknown */ ? neverType :
type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
- stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
- !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
- getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
- getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
+ stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */, includeOrigin) :
+ !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */, includeOrigin)]) :
+ getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */, includeOrigin)]) :
+ getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */, includeOrigin);
}
function getExtractStringType(type) {
if (keyofStringsOnly) {
function getTypeFromTemplateTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = getTemplateLiteralType(__spreadArrays([node.head.text], ts.map(node.templateSpans, function (span) { return span.literal.text; })), ts.map(node.templateSpans, function (span) { return getTypeFromTypeNode(span.type); }));
+ links.resolvedType = getTemplateLiteralType(__spreadArray([node.head.text], ts.map(node.templateSpans, function (span) { return span.literal.text; })), ts.map(node.templateSpans, function (span) { return getTypeFromTypeNode(span.type); }));
}
return links.resolvedType;
}
return getLiteralType(text);
}
newTexts.push(text);
+ if (ts.every(newTexts, function (t) { return t === ""; }) && ts.every(newTypes, function (t) { return !!(t.flags & 4 /* String */); })) {
+ return stringType;
+ }
var id = getTypeListId(newTypes) + "|" + ts.map(newTexts, function (t) { return t.length; }).join(",") + "|" + newTexts.join("");
var type = templateLiteralTypes.get(id);
if (!type) {
return ts.some(type.types, isJSLiteralType);
}
if (type.flags & 465829888 /* Instantiable */) {
- return isJSLiteralType(getResolvedBaseConstraint(type));
+ var constraint = getResolvedBaseConstraint(type);
+ return constraint !== type && isJSLiteralType(constraint);
}
return false;
}
undefined;
}
function isUncalledFunctionReference(node, symbol) {
- return !(symbol.flags & (16 /* Function */ | 8192 /* Method */))
- || !ts.isCallLikeExpression(ts.findAncestor(node, function (n) { return !ts.isAccessExpression(n); }) || node.parent)
- && ts.every(symbol.declarations, function (d) { return !ts.isFunctionLike(d) || !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); });
+ if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
+ var parent = ts.findAncestor(node.parent, function (n) { return !ts.isAccessExpression(n); }) || node.parent;
+ if (ts.isCallLikeExpression(parent)) {
+ return ts.isCallOrNewExpression(parent) && ts.isIdentifier(node) && hasMatchingArgument(parent, node);
+ }
+ return ts.every(symbol.declarations, function (d) { return !ts.isFunctionLike(d) || !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); });
+ }
+ return true;
}
function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags, noUncheckedIndexedAccessCandidate, reportDeprecated) {
var _a;
if (prop) {
if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) {
var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode);
- errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName);
+ addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName);
}
if (accessExpression) {
markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */);
return anyType;
}
if (accessExpression && !isConstEnumObjectType(objectType)) {
+ if (isObjectLiteralType(objectType)) {
+ if (noImplicitAny && indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
+ diagnostics.add(ts.createDiagnosticForNode(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType)));
+ return undefinedType;
+ }
+ else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
+ var types = ts.map(objectType.properties, function (property) {
+ return getTypeOfSymbol(property);
+ });
+ return getUnionType(ts.append(types, undefinedType));
+ }
+ }
if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
}
else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
- error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
+ var typeName = typeToString(objectType);
+ error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "[" + ts.getTextOfNode(accessExpression.argumentExpression) + "]");
}
else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
return writing ? getIntersectionType(types) : getUnionType(types);
}
}
- function unwrapSubstitution(type) {
- if (type.flags & 33554432 /* Substitution */) {
- return type.substitute;
- }
- return type;
- }
// Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
// the type itself if no transformation is possible. The writing flag indicates that the type is
// the target of an assignment.
type[cache] = circularConstraintType;
// We recursively simplify the object type as it may in turn be an indexed access type. For example, with
// '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
- var objectType = unwrapSubstitution(getSimplifiedType(type.objectType, writing));
+ var objectType = getSimplifiedType(type.objectType, writing);
var indexType = getSimplifiedType(type.indexType, writing);
// T[A | B] -> T[A] | T[B] (reading)
// T[A | B] -> T[A] & T[B] (writing)
return objectType;
}
// Defer the operation by creating an indexed access type.
- var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "");
+ var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments);
var type = indexedAccessTypes.get(id);
if (!type) {
indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined));
}
return type;
}
- function getConditionalType(root, mapper) {
+ function isTypicalNondistributiveConditional(root) {
+ return !root.isDistributive
+ && root.node.checkType.kind === 179 /* TupleType */
+ && ts.length(root.node.checkType.elements) === 1
+ && root.node.extendsType.kind === 179 /* TupleType */
+ && ts.length(root.node.extendsType.elements) === 1;
+ }
+ /**
+ * We syntactually check for common nondistributive conditional shapes and unwrap them into
+ * the intended comparison - we do this so we can check if the unwrapped types are generic or
+ * not and appropriately defer condition calculation
+ */
+ function unwrapNondistributiveConditionalTuple(root, type) {
+ return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type;
+ }
+ function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) {
var result;
var extraTypes;
- var _loop_15 = function () {
- var checkType = instantiateType(root.checkType, mapper);
+ // We loop here for an immediately nested conditional type in the false position, effectively treating
+ // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
+ // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
+ while (true) {
+ var isUnwrapped = isTypicalNondistributiveConditional(root);
+ var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper);
var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType);
- var extendsType = instantiateType(root.extendsType, mapper);
+ var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper);
if (checkType === wildcardType || extendsType === wildcardType) {
- return { value: wildcardType };
+ return wildcardType;
}
var combinedMapper = void 0;
if (root.inferTypeParameters) {
var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
- // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
- // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
- // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
- // so in those cases we refain from performing inference and retain the uninfered type parameter
- if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) {
+ if (!checkTypeInstantiable) {
// We don't want inferences from constraints as they may cause us to eagerly resolve the
// conditional type instead of deferring resolution. Also, we always want strict function
// types rules (i.e. proper contravariance) for inferences.
combinedMapper = mergeTypeMappers(mapper, context.mapper);
}
// Instantiate the extends type including inferences for 'infer T' type parameters
- var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
+ var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType;
// We attempt to resolve the conditional type only when the check and extends types are non-generic
if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) {
// Return falseType for a definitely false extends check. We check an instantiations of the two
// types with type parameters mapped to the wildcard type, the most permissive instantiations
// possible (the wildcard type is assignable to and from all types). If those are not related,
// then no instantiations will be and we can just return the false branch type.
- if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
+ if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
// Return union of trueType and falseType for 'any' since it matches anything
- if (checkType.flags & 1 /* Any */) {
+ if (checkType.flags & 1 /* Any */ && !isUnwrapped) {
(extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper));
}
// If falseType is an immediately nested conditional type that isn't distributive or has an
var newRoot = falseType_1.root;
if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
root = newRoot;
- return "continue";
+ continue;
}
}
result = instantiateType(falseType_1, mapper);
- return "break";
+ break;
}
// Return trueType for a definitely true extends check. We check instantiations of the two
// types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
// doesn't immediately resolve to 'string' instead of being deferred.
if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
result = instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper);
- return "break";
+ break;
}
}
// Return a deferred type for a check that is neither definitely true nor definitely false
- var erasedCheckType = getActualTypeVariable(checkType);
result = createType(16777216 /* Conditional */);
result.root = root;
- result.checkType = erasedCheckType;
- result.extendsType = extendsType;
+ result.checkType = instantiateType(root.checkType, mapper);
+ result.extendsType = instantiateType(root.extendsType, mapper);
result.mapper = mapper;
result.combinedMapper = combinedMapper;
- result.aliasSymbol = root.aliasSymbol;
- result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
- return "break";
- };
- // We loop here for an immediately nested conditional type in the false position, effectively treating
- // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
- // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
- while (true) {
- var state_4 = _loop_15();
- if (typeof state_4 === "object")
- return state_4.value;
- if (state_4 === "break")
- break;
+ result.aliasSymbol = aliasSymbol || root.aliasSymbol;
+ result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
+ break;
}
return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
}
return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
}
function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
- if (type.types.length === 2) {
- var firstType = type.types[0];
- var secondType = type.types[1];
- if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
- return isEmptyObjectType(firstType) ? firstType : isEmptyObjectType(secondType) ? secondType : emptyObjectType;
- }
- if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(firstType)) {
- return getAnonymousPartialType(secondType);
- }
- if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(secondType)) {
- return getAnonymousPartialType(firstType);
- }
+ if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
+ return ts.find(type.types, isEmptyObjectType) || emptyObjectType;
+ }
+ var firstType = ts.find(type.types, function (t) { return !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t); });
+ if (!firstType) {
+ return undefined;
+ }
+ var secondType = firstType && ts.find(type.types, function (t) { return t !== firstType && !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t); });
+ if (secondType) {
+ return undefined;
}
+ return getAnonymousPartialType(firstType);
function getAnonymousPartialType(type) {
// gets the type as if it had been spread, but where everything in the spread is made optional
var members = ts.createSymbolTable();
else if (isSpreadableProperty(prop)) {
var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
var flags = 4 /* Property */ | 16777216 /* Optional */;
- var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
- result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
+ var result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? 8 /* Readonly */ : 0));
+ result.type = isSetonlyAccessor ? undefinedType : getUnionType([getTypeOfSymbol(prop), undefinedType]);
result.declarations = prop.declarations;
result.nameType = getSymbolLinks(prop).nameType;
result.syntheticOrigin = prop;
return prop;
}
var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
- var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
+ var result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? 8 /* Readonly */ : 0));
result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
result.declarations = prop.declarations;
result.nameType = getSymbolLinks(prop).nameType;
}
function getRegularTypeOfLiteralType(type) {
return type.flags & 2944 /* Literal */ ? type.regularType :
- type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) :
+ type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) :
type;
}
function isFreshLiteralType(type) {
// See GH#17600.
var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol),
/*resolvedReturnType*/ undefined,
- /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 19 /* PropagatingFlags */);
+ /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 39 /* PropagatingFlags */);
result.target = signature;
result.mapper = mapper;
return result;
}
return result;
}
- function getObjectTypeInstantiation(type, mapper) {
+ function getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) {
var declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
var links = getNodeLinks(declaration);
var target = type.objectFlags & 4 /* Reference */ ? links.resolvedType :
// instantiation cache key from the type IDs of the type arguments.
var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
- var id = getTypeListId(typeArguments);
+ var newAliasSymbol = aliasSymbol || type.aliasSymbol;
+ var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
+ var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments);
if (!target.instantiations) {
target.instantiations = new ts.Map();
- target.instantiations.set(getTypeListId(typeParameters), target);
+ target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target);
}
var result = target.instantiations.get(id);
if (!result) {
var newMapper = createTypeMapper(typeParameters, typeArguments);
- result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) :
- target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) :
- instantiateAnonymousType(target, newMapper);
+ result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) :
+ target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) :
+ instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments);
target.instantiations.set(id, result);
}
return result;
}
return undefined;
}
- function instantiateMappedType(type, mapper) {
+ function instantiateMappedType(type, mapper, aliasSymbol, aliasTypeArguments) {
// For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
// operation depends on T as follows:
// * If T is a primitive type no mapping is performed and the result is simply T.
if (typeVariable) {
var mappedTypeVariable = instantiateType(typeVariable, mapper);
if (typeVariable !== mappedTypeVariable) {
- return mapType(getReducedType(mappedTypeVariable), function (t) {
+ return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) {
if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
if (!type.declaration.nameType) {
if (isArrayType(t)) {
return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper));
}
return t;
- });
+ }, aliasSymbol, aliasTypeArguments);
}
}
- return instantiateAnonymousType(type, mapper);
+ // If the constraint type of the instantiation is the wildcard type, return the wildcard type.
+ return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments);
}
function getModifiedReadonlyState(state, modifiers) {
return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
propType;
}
- function instantiateAnonymousType(type, mapper) {
+ function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) {
var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
if (type.objectFlags & 32 /* Mapped */) {
result.declaration = type.declaration;
}
result.target = type;
result.mapper = mapper;
- result.aliasSymbol = type.aliasSymbol;
- result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
+ result.aliasSymbol = aliasSymbol || type.aliasSymbol;
+ result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
return result;
}
- function getConditionalTypeInstantiation(type, mapper) {
+ function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) {
var root = type.root;
if (root.outerTypeParameters) {
// We are instantiating a conditional type that has one or more type parameters in scope. Apply the
// mapper to the type parameters to produce the effective list of type arguments, and compute the
// instantiation cache key from the type IDs of the type arguments.
var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
- var id = getTypeListId(typeArguments);
+ var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments);
var result = root.instantiations.get(id);
if (!result) {
var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
- result = instantiateConditionalType(root, newMapper);
+ result = instantiateConditionalType(root, newMapper, aliasSymbol, aliasTypeArguments);
root.instantiations.set(id, result);
}
return result;
}
return type;
}
- function instantiateConditionalType(root, mapper) {
+ function instantiateConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) {
// Check if we have a conditional type where the check type is a naked type parameter. If so,
// the conditional type is distributive over union types and when T is instantiated to a union
// type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
var checkType_1 = root.checkType;
var instantiatedType = getMappedType(checkType_1, mapper);
if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
- return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); });
+ return mapTypeWithAlias(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }, aliasSymbol, aliasTypeArguments);
}
}
- return getConditionalType(root, mapper);
+ return getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments);
}
function instantiateType(type, mapper) {
- if (!(type && mapper && couldContainTypeVariables(type))) {
+ return type && mapper ? instantiateTypeWithAlias(type, mapper, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined) : type;
+ }
+ function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) {
+ if (!couldContainTypeVariables(type)) {
return type;
}
if (instantiationDepth === 50 || instantiationCount >= 5000000) {
// We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
// with a combination of infinite generic types that perpetually generate new type identities. We stop
// the recursion here by yielding the error type.
- ts.tracing.instant("check" /* Check */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount });
error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
return errorType;
}
totalInstantiationCount++;
instantiationCount++;
instantiationDepth++;
- var result = instantiateTypeWorker(type, mapper);
+ var result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments);
instantiationDepth--;
return result;
}
- function instantiateTypeWorker(type, mapper) {
+ function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) {
var flags = type.flags;
if (flags & 262144 /* TypeParameter */) {
return getMappedType(type, mapper);
if (flags & 524288 /* Object */) {
var objectFlags = type.objectFlags;
if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) {
- if (objectFlags & 4 /* Reference */ && !(type.node)) {
+ if (objectFlags & 4 /* Reference */ && !type.node) {
var resolvedTypeArguments = type.resolvedTypeArguments;
var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type;
}
- return getObjectTypeInstantiation(type, mapper);
+ return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments);
}
return type;
}
if (flags & 3145728 /* UnionOrIntersection */) {
- var types = type.types;
+ var origin = type.flags & 1048576 /* Union */ ? type.origin : undefined;
+ var types = origin && origin.flags & 3145728 /* UnionOrIntersection */ ? origin.types : type.types;
var newTypes = instantiateTypes(types, mapper);
- return newTypes === types ? type :
- flags & 2097152 /* Intersection */ ?
- getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) :
- getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
+ if (newTypes === types && aliasSymbol === type.aliasSymbol) {
+ return type;
+ }
+ var newAliasSymbol = aliasSymbol || type.aliasSymbol;
+ var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
+ return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ?
+ getIntersectionType(newTypes, newAliasSymbol, newAliasTypeArguments) :
+ getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments);
}
if (flags & 4194304 /* Index */) {
return getIndexType(instantiateType(type.type, mapper));
return getStringMappingType(type.symbol, instantiateType(type.type, mapper));
}
if (flags & 8388608 /* IndexedAccess */) {
- return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
+ var newAliasSymbol = aliasSymbol || type.aliasSymbol;
+ var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
+ return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, newAliasSymbol, newAliasTypeArguments);
}
if (flags & 16777216 /* Conditional */) {
- return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
+ return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper), aliasSymbol, aliasTypeArguments);
}
if (flags & 33554432 /* Substitution */) {
var maybeVariable = instantiateType(type.baseType, mapper);
reportIncompatibleStack();
}
if (overflow) {
- ts.tracing.instant("check" /* Check */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth });
var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
if (errorOutputContainer) {
(errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
}
var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
if (relatedInfo) {
- ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInfo));
+ ts.addRelatedInfo.apply(void 0, __spreadArray([diag], relatedInfo));
}
if (errorOutputContainer) {
(errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
reportError.apply(void 0, stack[0]);
if (info) {
// Actually do the last relation error
- reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
+ reportRelationError.apply(void 0, __spreadArray([/*headMessage*/ undefined], info));
}
return;
}
for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
var originalValue = msg.elidedInCompatabilityPyramid;
- msg.elidedInCompatabilityPyramid = false; // Teporarily override elision to ensure error is reported
- reportError.apply(void 0, __spreadArrays([msg], args));
+ msg.elidedInCompatabilityPyramid = false; // Temporarily override elision to ensure error is reported
+ reportError.apply(void 0, __spreadArray([msg], args));
msg.elidedInCompatabilityPyramid = originalValue;
}
if (info) {
// Actually do the last relation error
- reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
+ reportRelationError.apply(void 0, __spreadArray([/*headMessage*/ undefined], info));
}
}
function reportError(message, arg0, arg1, arg2, arg3) {
if (isPerformingExcessPropertyChecks) {
if (hasExcessProperties(source, target, reportErrors)) {
if (reportErrors) {
- reportRelationError(headMessage, source, target);
+ reportRelationError(headMessage, source, originalTarget.aliasSymbol ? originalTarget : target);
}
return 0 /* False */;
}
(getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
if (reportErrors) {
+ var sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source);
+ var targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target);
var calls = getSignaturesOfType(source, 0 /* Call */);
var constructs = getSignaturesOfType(source, 1 /* Construct */);
if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
- 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));
+ reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString);
}
else {
- reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
+ reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString);
}
}
return 0 /* False */;
}
+ traceUnionsOrIntersectionsTooLarge(source, target);
var result = 0 /* False */;
var saveErrorInfo = captureErrorCalculationState();
// Note that these checks are specifically ordered to produce correct results. In particular,
// we need to deconstruct unions before intersections (because unions are always at the top),
// and we need to handle "each" relations before "some" relations for the same kind of type.
- if (source.flags & 1048576 /* Union */) {
- result = relation === comparableRelation ?
- someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
- eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState);
+ if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) {
+ result = getConstituentCount(source) * getConstituentCount(target) >= 4 ?
+ recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */) :
+ structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */);
}
- else {
- if (target.flags & 1048576 /* Union */) {
- result = typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
- }
- else if (target.flags & 2097152 /* Intersection */) {
- result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
- }
- else if (source.flags & 2097152 /* Intersection */) {
- // Check to see if any constituents of the intersection are immediately related to the target.
- //
- // Don't report errors though. Checking whether a constituent is related to the source is not actually
- // useful and leads to some confusing error messages. Instead it is better to let the below checks
- // take care of this, or to not elaborate at all. For instance,
- //
- // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
- //
- // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
- // than to report that 'D' is not assignable to 'A' or 'B'.
- //
- // - For a primitive type or type parameter (such as 'number = A & B') there is no point in
- // breaking the intersection apart.
- result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
- }
- if (!result && (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */)) {
- if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
- resetErrorInfo(saveErrorInfo);
- }
+ if (!result && !(source.flags & 1048576 /* Union */) && (source.flags & (469499904 /* StructuredOrInstantiable */) || target.flags & 469499904 /* StructuredOrInstantiable */)) {
+ if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
+ resetErrorInfo(saveErrorInfo);
}
}
if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
}
}
}
+ function traceUnionsOrIntersectionsTooLarge(source, target) {
+ if (!ts.tracing) {
+ return;
+ }
+ if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) {
+ var sourceUnionOrIntersection = source;
+ var targetUnionOrIntersection = target;
+ if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) {
+ // There's a fast path for comparing primitive unions
+ return;
+ }
+ var sourceSize = sourceUnionOrIntersection.types.length;
+ var targetSize = targetUnionOrIntersection.types.length;
+ if (sourceSize * targetSize > 1E6) {
+ ts.tracing.instant("checkTypes" /* CheckTypes */, "traceUnionsOrIntersectionsTooLarge_DepthLimit", {
+ sourceId: source.id,
+ sourceSize: sourceSize,
+ targetId: target.id,
+ targetSize: targetSize,
+ pos: errorNode === null || errorNode === void 0 ? void 0 : errorNode.pos,
+ end: errorNode === null || errorNode === void 0 ? void 0 : errorNode.end
+ });
+ }
+ }
+ }
function isIdenticalTo(source, target) {
var flags = source.flags & target.flags;
if (!(flags & 469237760 /* Substructure */)) {
return 0 /* False */;
}
+ traceUnionsOrIntersectionsTooLarge(source, target);
if (flags & 3145728 /* UnionOrIntersection */) {
var result_6 = eachTypeRelatedToSomeType(source, target);
if (result_6) {
}
return 0 /* False */;
}
+ function getUndefinedStrippedTargetIfNeeded(source, target) {
+ // As a builtin type, `undefined` is a very low type ID - making it almsot always first, making this a very fast check to see
+ // if we need to strip `undefined` from the target
+ if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ &&
+ !(source.types[0].flags & 32768 /* Undefined */) && target.types[0].flags & 32768 /* Undefined */) {
+ return extractTypesOfKind(target, ~32768 /* Undefined */);
+ }
+ return target;
+ }
function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
var result = -1 /* True */;
var sourceTypes = source.types;
+ // We strip `undefined` from the target if the `source` trivially doesn't contain it for our correspondence-checking fastpath
+ // since `undefined` is frequently added by optionality and would otherwise spoil a potentially useful correspondence
+ var undefinedStrippedTarget = getUndefinedStrippedTargetIfNeeded(source, target);
for (var i = 0; i < sourceTypes.length; i++) {
var sourceType = sourceTypes[i];
- if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) {
+ if (undefinedStrippedTarget.flags & 1048576 /* Union */ && sourceTypes.length >= undefinedStrippedTarget.types.length && sourceTypes.length % undefinedStrippedTarget.types.length === 0) {
// many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
- var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
+ // such unions will have identical lengths, and their corresponding elements will match up. Another common scenario is where a large
+ // union has a union of objects intersected with it. In such cases, if the input was, eg `("a" | "b" | "c") & (string | boolean | {} | {whatever})`,
+ // the result will have the structure `"a" | "b" | "c" | "a" & {} | "b" & {} | "c" & {} | "a" & {whatever} | "b" & {whatever} | "c" & {whatever}`
+ // - the resulting union has a length which is a multiple of the original union, and the elements correspond modulo the length of the original union
+ var related_1 = isRelatedTo(sourceType, undefinedStrippedTarget.types[i % undefinedStrippedTarget.types.length], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
if (related_1) {
result &= related_1;
continue;
if (overflow) {
return 0 /* False */;
}
- var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation);
+ var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 16 /* InPropertyCheck */ : 0), relation);
var entry = relation.get(id);
if (entry !== undefined) {
if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
};
}
if (expandingFlags === 3 /* Both */) {
- ts.tracing.instant("check" /* Check */, "recursiveTypeRelatedTo_DepthLimit", {
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", {
sourceId: source.id,
sourceIdStack: sourceStack.map(function (t) { return t.id; }),
targetId: target.id,
return result;
}
function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
- ts.tracing.push("check" /* Check */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id });
var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState);
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
return result;
}
function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) {
if (intersectionState & 4 /* PropertyCheck */) {
return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
}
+ if (intersectionState & 8 /* UnionIntersectionCheck */) {
+ // Note that these checks are specifically ordered to produce correct results. In particular,
+ // we need to deconstruct unions before intersections (because unions are always at the top),
+ // and we need to handle "each" relations before "some" relations for the same kind of type.
+ if (source.flags & 1048576 /* Union */) {
+ return relation === comparableRelation ?
+ someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */) :
+ eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */);
+ }
+ if (target.flags & 1048576 /* Union */) {
+ return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
+ }
+ if (target.flags & 2097152 /* Intersection */) {
+ return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
+ }
+ // Source is an intersection. Check to see if any constituents of the intersection are immediately related
+ // to the target.
+ //
+ // Don't report errors though. Checking whether a constituent is related to the source is not actually
+ // useful and leads to some confusing error messages. Instead it is better to let the below checks
+ // take care of this, or to not elaborate at all. For instance,
+ //
+ // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
+ //
+ // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
+ // than to report that 'D' is not assignable to 'A' or 'B'.
+ //
+ // - For a primitive type or type parameter (such as 'number = A & B') there is no point in
+ // breaking the intersection apart.
+ return someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
+ }
var flags = source.flags & target.flags;
if (relation === identityRelation && !(flags & 524288 /* Object */)) {
if (flags & 4194304 /* Index */) {
numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
if (numCombinations > 25) {
// We've reached the complexity limit.
- ts.tracing.instant("check" /* Check */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations });
return 0 /* False */;
}
}
var matchingTypes = [];
var _loop_17 = function (combination) {
var hasMatch = false;
- outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) {
- var type = _a[_i];
+ outer: for (var _c = 0, _d = target.types; _c < _d.length; _c++) {
+ var type = _d[_c];
var _loop_18 = function (i) {
var sourceProperty = sourcePropertiesFiltered[i];
var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
}
if (props.length === 1) {
var propName = symbolToString(unmatchedProperty);
- reportError.apply(void 0, __spreadArrays([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
+ reportError.apply(void 0, __spreadArray([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
if (ts.length(unmatchedProperty.declarations)) {
associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
}
}
return 0 /* False */;
}
- var maxArity = Math.max(sourceArity, targetArity);
- for (var i = 0; i < maxArity; i++) {
- var targetFlags = i < targetArity ? target.target.elementFlags[i] : targetRestFlag;
- var sourceFlags = isTupleType(source) && i < sourceArity ? source.target.elementFlags[i] : sourceRestFlag;
- var canExcludeDiscriminants = !!excludedProperties;
- if (sourceFlags && targetFlags) {
- if (targetFlags & 8 /* Variadic */ && !(sourceFlags & 8 /* Variadic */) ||
- (sourceFlags & 8 /* Variadic */ && !(targetFlags & 12 /* Variable */))) {
- if (reportErrors) {
- reportError(ts.Diagnostics.Element_at_index_0_is_variadic_in_one_type_but_not_in_the_other, i);
- }
- return 0 /* False */;
+ var sourceTypeArguments = getTypeArguments(source);
+ var targetTypeArguments = getTypeArguments(target);
+ var startCount = Math.min(isTupleType(source) ? getStartElementCount(source.target, 11 /* NonRest */) : 0, getStartElementCount(target.target, 11 /* NonRest */));
+ var endCount = Math.min(isTupleType(source) ? getEndElementCount(source.target, 11 /* NonRest */) : 0, targetRestFlag ? getEndElementCount(target.target, 11 /* NonRest */) : 0);
+ var canExcludeDiscriminants = !!excludedProperties;
+ for (var i = 0; i < targetArity; i++) {
+ var sourceIndex = i < targetArity - endCount ? i : i + sourceArity - targetArity;
+ var sourceFlags = isTupleType(source) && (i < startCount || i >= targetArity - endCount) ? source.target.elementFlags[sourceIndex] : 4 /* Rest */;
+ var targetFlags = target.target.elementFlags[i];
+ if (targetFlags & 8 /* Variadic */ && !(sourceFlags & 8 /* Variadic */)) {
+ if (reportErrors) {
+ reportError(ts.Diagnostics.Source_provides_no_match_for_variadic_element_at_position_0_in_target, i);
}
- if (targetFlags & 1 /* Required */) {
- if (!(sourceFlags & 1 /* Required */)) {
- if (reportErrors) {
- reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, i, typeToString(source), typeToString(target));
- }
- return 0 /* False */;
- }
+ return 0 /* False */;
+ }
+ if (sourceFlags & 8 /* Variadic */ && !(targetFlags & 12 /* Variable */)) {
+ if (reportErrors) {
+ reportError(ts.Diagnostics.Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target, sourceIndex, i);
}
- // We can only exclude discriminant properties if we have not yet encountered a variable-length element.
- if (canExcludeDiscriminants) {
- if (sourceFlags & 12 /* Variable */ || targetFlags & 12 /* Variable */) {
- canExcludeDiscriminants = false;
- }
- if (canExcludeDiscriminants && (excludedProperties === null || excludedProperties === void 0 ? void 0 : excludedProperties.has(("" + i)))) {
- continue;
- }
+ return 0 /* False */;
+ }
+ if (targetFlags & 1 /* Required */ && !(sourceFlags & 1 /* Required */)) {
+ if (reportErrors) {
+ reportError(ts.Diagnostics.Source_provides_no_match_for_required_element_at_position_0_in_target, i);
+ }
+ return 0 /* False */;
+ }
+ // We can only exclude discriminant properties if we have not yet encountered a variable-length element.
+ if (canExcludeDiscriminants) {
+ if (sourceFlags & 12 /* Variable */ || targetFlags & 12 /* Variable */) {
+ canExcludeDiscriminants = false;
}
- var sourceType = getTypeArguments(source)[Math.min(i, sourceArity - 1)];
- var targetType = getTypeArguments(target)[Math.min(i, targetArity - 1)];
- var targetCheckType = sourceFlags & 8 /* Variadic */ && targetFlags & 4 /* Rest */ ? createArrayType(targetType) : targetType;
- var related = isRelatedTo(sourceType, targetCheckType, reportErrors, /*headMessage*/ undefined, intersectionState);
- if (!related) {
- if (reportErrors) {
- reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, i);
+ if (canExcludeDiscriminants && (excludedProperties === null || excludedProperties === void 0 ? void 0 : excludedProperties.has(("" + i)))) {
+ continue;
+ }
+ }
+ var sourceType = !isTupleType(source) ? sourceTypeArguments[0] :
+ i < startCount || i >= targetArity - endCount ? sourceTypeArguments[sourceIndex] :
+ getElementTypeOfSliceOfTupleType(source, startCount, endCount) || neverType;
+ var targetType = targetTypeArguments[i];
+ var targetCheckType = sourceFlags & 8 /* Variadic */ && targetFlags & 4 /* Rest */ ? createArrayType(targetType) : targetType;
+ var related = isRelatedTo(sourceType, targetCheckType, reportErrors, /*headMessage*/ undefined, intersectionState);
+ if (!related) {
+ if (reportErrors) {
+ if (i < startCount || i >= targetArity - endCount || sourceArity - startCount - endCount === 1) {
+ reportIncompatibleError(ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, sourceIndex, i);
+ }
+ else {
+ reportIncompatibleError(ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, startCount, sourceArity - endCount - 1, i);
}
- return 0 /* False */;
}
- result &= related;
+ return 0 /* False */;
}
+ result &= related;
}
return result;
}
var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
0 /* Call */ : kind);
if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
- if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
+ var sourceIsAbstract = !!(sourceSignatures[0].flags & 4 /* Abstract */);
+ var targetIsAbstract = !!(targetSignatures[0].flags & 4 /* Abstract */);
+ if (sourceIsAbstract && !targetIsAbstract) {
// An abstract constructor type is not assignable to a non-abstract constructor type
// as it would otherwise be possible to new an abstract class. Note that the assignability
// check we perform for an extends clause excludes construct signatures from the target,
continue;
}
if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
- var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
+ var propType = getTypeOfSymbol(prop);
+ var type = propType.flags & 32768 /* Undefined */ || !(kind === 0 /* String */ && prop.flags & 16777216 /* Optional */)
+ ? propType
+ : getTypeWithFacts(propType, 524288 /* NEUndefined */);
+ var related = isRelatedTo(type, target, reportErrors);
if (!related) {
if (reportErrors) {
reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
var variances = cache.variances;
if (!variances) {
- ts.tracing.push("check" /* Check */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 });
// The emptyArray singleton is used to signal a recursive invocation.
cache.variances = ts.emptyArray;
variances = [];
_loop_19(tp);
}
cache.variances = variances;
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
}
return variances;
}
}
function literalTypesWithSameBaseType(types) {
var commonBaseType;
- for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
- var t = types_13[_i];
+ for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
+ var t = types_14[_i];
var baseType = getBaseTypeOfLiteralType(t);
if (!commonBaseType) {
commonBaseType = baseType;
type.flags & 256 /* NumberLiteral */ ? numberType :
type.flags & 2048 /* BigIntLiteral */ ? bigintType :
type.flags & 512 /* BooleanLiteral */ ? booleanType :
- type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
+ type.flags & 1048576 /* Union */ ? mapType(type, getBaseTypeOfLiteralType) :
type;
}
function getWidenedLiteralType(type) {
type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
- type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
+ type.flags & 1048576 /* Union */ ? mapType(type, getWidenedLiteralType) :
type;
}
function getWidenedUniqueESSymbolType(type) {
return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
- type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
+ type.flags & 1048576 /* Union */ ? mapType(type, getWidenedUniqueESSymbolType) :
type;
}
function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
var restType = getRestTypeOfTupleType(type);
return restType && createArrayType(restType);
}
- function getEndLengthOfType(type) {
- return isTupleType(type) ? getTypeReferenceArity(type) - ts.findLastIndex(type.target.elementFlags, function (f) { return !(f & (1 /* Required */ | 2 /* Optional */)); }) - 1 : 0;
- }
function getElementTypeOfSliceOfTupleType(type, index, endSkipCount, writing) {
if (endSkipCount === void 0) { endSkipCount = 0; }
if (writing === void 0) { writing = false; }
}
function getFalsyFlagsOfTypes(types) {
var result = 0;
- for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
- var t = types_14[_i];
+ for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
+ var t = types_15[_i];
result |= getFalsyFlags(t);
}
return result;
// Two object types that each have a property that is unmatched in the other are definitely unrelated.
return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) :
!!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
- !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
+ !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ false);
}
function getTypeFromInference(inference) {
return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
invokeOnce(source, target, inferFromObjectTypes);
}
}
- if (source.flags & 25165824 /* Simplifiable */) {
- var simplified = getSimplifiedType(source, contravariant);
- if (simplified !== source) {
- inferFromTypes(simplified, target);
- }
- }
}
function inferWithPriority(source, target, newPriority) {
var savePriority = priority;
}
function getSingleTypeVariableFromIntersectionTypes(types) {
var typeVariable;
- for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
- var type = types_15[_i];
+ for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
+ var type = types_16[_i];
var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
if (!t || typeVariable && t !== typeVariable) {
return undefined;
return;
}
var startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0;
- var sourceRestType = !isTupleType(source) || sourceArity > 0 && source.target.elementFlags[sourceArity - 1] & 4 /* Rest */ ?
- getTypeArguments(source)[sourceArity - 1] : undefined;
- var endLength = !(target.target.combinedFlags & 12 /* Variable */) ? 0 :
- sourceRestType ? getEndLengthOfType(target) :
- Math.min(getEndLengthOfType(source), getEndLengthOfType(target));
- var sourceEndLength = sourceRestType ? 0 : endLength;
+ var endLength = Math.min(isTupleType(source) ? getEndElementCount(source.target, 3 /* Fixed */) : 0, target.target.hasRestElement ? getEndElementCount(target.target, 3 /* Fixed */) : 0);
// Infer between starting fixed elements.
for (var i = 0; i < startLength; i++) {
inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
}
- if (sourceRestType && sourceArity - startLength === 1) {
+ if (!isTupleType(source) || sourceArity - startLength - endLength === 1 && source.target.elementFlags[startLength] & 4 /* Rest */) {
// Single rest element remains in source, infer from that to every element in target
+ var restType = getTypeArguments(source)[startLength];
for (var i = startLength; i < targetArity - endLength; i++) {
- inferFromTypes(elementFlags[i] & 8 /* Variadic */ ? createArrayType(sourceRestType) : sourceRestType, elementTypes[i]);
+ inferFromTypes(elementFlags[i] & 8 /* Variadic */ ? createArrayType(restType) : restType, elementTypes[i]);
}
}
else {
var targetInfo = getInferenceInfoForType(elementTypes[startLength]);
if (targetInfo && targetInfo.impliedArity !== undefined) {
// Infer slices from source based on implied arity of T.
- inferFromTypes(sliceTupleType(source, startLength, sourceEndLength + sourceArity - targetInfo.impliedArity), elementTypes[startLength]);
- inferFromTypes(sliceTupleType(source, startLength + targetInfo.impliedArity, sourceEndLength), elementTypes[startLength + 1]);
+ inferFromTypes(sliceTupleType(source, startLength, endLength + sourceArity - targetInfo.impliedArity), elementTypes[startLength]);
+ inferFromTypes(sliceTupleType(source, startLength + targetInfo.impliedArity, endLength), elementTypes[startLength + 1]);
}
}
else if (middleLength === 1 && elementFlags[startLength] & 8 /* Variadic */) {
// Middle of target is exactly one variadic element. Infer the slice between the fixed parts in the source.
// If target ends in optional element(s), make a lower priority a speculative inference.
var endsInOptional = target.target.elementFlags[targetArity - 1] & 2 /* Optional */;
- var sourceSlice = isTupleType(source) ? sliceTupleType(source, startLength, sourceEndLength) : createArrayType(sourceRestType);
+ var sourceSlice = isTupleType(source) ? sliceTupleType(source, startLength, endLength) : createArrayType(getTypeArguments(source)[0]);
inferWithPriority(sourceSlice, elementTypes[startLength], endsInOptional ? 2 /* SpeculativeTuple */ : 0);
}
else if (middleLength === 1 && elementFlags[startLength] & 4 /* Rest */) {
// Middle of target is exactly one rest element. If middle of source is not empty, infer union of middle element types.
- var restType = isTupleType(source) ? getElementTypeOfSliceOfTupleType(source, startLength, sourceEndLength) : sourceRestType;
+ var restType = isTupleType(source) ? getElementTypeOfSliceOfTupleType(source, startLength, endLength) : getTypeArguments(source)[0];
if (restType) {
inferFromTypes(restType, elementTypes[startLength]);
}
}
// Infer between ending fixed elements
for (var i = 0; i < endLength; i++) {
- inferFromTypes(sourceRestType || getTypeArguments(source)[sourceArity - i - 1], elementTypes[targetArity - i - 1]);
+ inferFromTypes(getTypeArguments(source)[sourceArity - i - 1], elementTypes[targetArity - i - 1]);
}
return;
}
return ts.isAccessExpression(target) &&
getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
isMatchingReference(source.expression, target.expression);
+ case 157 /* QualifiedName */:
+ return ts.isAccessExpression(target) &&
+ source.right.escapedText === getAccessedPropertyName(target) &&
+ isMatchingReference(source.left, target.expression);
+ case 216 /* BinaryExpression */:
+ return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target));
}
return false;
}
function isOrContainsMatchingReference(source, target) {
return isMatchingReference(source, target) || containsMatchingReference(source, target);
}
- function hasMatchingArgument(callExpression, reference) {
- if (callExpression.arguments) {
- for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
+ function hasMatchingArgument(expression, reference) {
+ if (expression.arguments) {
+ for (var _i = 0, _a = expression.arguments; _i < _a.length; _i++) {
var argument = _a[_i];
if (isOrContainsMatchingReference(reference, argument)) {
return true;
}
}
}
- if (callExpression.expression.kind === 201 /* PropertyAccessExpression */ &&
- isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
+ if (expression.expression.kind === 201 /* PropertyAccessExpression */ &&
+ isOrContainsMatchingReference(reference, expression.expression.expression)) {
return true;
}
return false;
}
function getTypeFactsOfTypes(types) {
var result = 0 /* None */;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var t = types_16[_i];
+ for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
+ var t = types_17[_i];
result |= getTypeFacts(t);
}
return result;
return 0 /* None */;
}
if (flags & 465829888 /* Instantiable */) {
- return getTypeFacts(getBaseConstraintOfType(type) || unknownType);
+ return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) :
+ strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */;
}
if (flags & 3145728 /* UnionOrIntersection */) {
return getTypeFactsOfTypes(type.types);
if (type.flags & 1048576 /* Union */) {
var types = type.types;
var filtered = ts.filter(types, f);
- return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
+ if (filtered === types) {
+ return type;
+ }
+ var origin = type.origin;
+ var newOrigin = void 0;
+ if (origin && origin.flags & 1048576 /* Union */) {
+ // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends
+ // up removing a smaller number of types than in the normalized constituent set (meaning some of the
+ // filtered types are within nested unions in the origin), then we can't construct a new origin type.
+ // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type.
+ // Otherwise, construct a new filtered origin type.
+ var originTypes = origin.types;
+ var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); });
+ if (originTypes.length - originFiltered.length === types.length - filtered.length) {
+ if (originFiltered.length === 1) {
+ return originFiltered[0];
+ }
+ newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered);
+ }
+ }
+ return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin);
}
return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
}
if (!(type.flags & 1048576 /* Union */)) {
return mapper(type);
}
+ var origin = type.origin;
+ var types = origin && origin.flags & 1048576 /* Union */ ? origin.types : type.types;
var mappedTypes;
- for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
- var t = _a[_i];
- var mapped = mapper(t);
+ var changed = false;
+ for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
+ var t = types_18[_i];
+ var mapped = t.flags & 1048576 /* Union */ ? mapType(t, mapper, noReductions) : mapper(t);
+ changed || (changed = t !== mapped);
if (mapped) {
if (!mappedTypes) {
mappedTypes = [mapped];
}
}
}
- return mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
+ return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : type;
+ }
+ function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) {
+ return type.flags & 1048576 /* Union */ && aliasSymbol ?
+ getUnionType(ts.map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) :
+ mapType(type, mapper);
+ }
+ function getConstituentCount(type) {
+ return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1;
}
function extractTypesOfKind(type, kind) {
return filterType(type, function (t) { return (t.flags & kind) !== 0; });
}
function isEvolvingArrayTypeList(types) {
var hasEvolvingArrayType = false;
- for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
- var t = types_17[_i];
+ for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
+ var t = types_19[_i];
if (!(t.flags & 131072 /* Never */)) {
if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
return false;
}
return hasEvolvingArrayType;
}
- // At flow control branch or loop junctions, if the type along every antecedent code path
- // is an evolving array type, we construct a combined evolving array type. Otherwise we
- // finalize all evolving array types.
- function getUnionOrEvolvingArrayType(types, subtypeReduction) {
- return isEvolvingArrayTypeList(types) ?
- getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
- getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
- }
// Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
// 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
function isEvolvingArrayOperationTarget(node) {
return getExplicitThisType(node);
case 105 /* SuperKeyword */:
return checkSuperExpression(node);
- case 201 /* PropertyAccessExpression */:
+ case 201 /* PropertyAccessExpression */: {
var type = getTypeOfDottedName(node.expression, diagnostic);
- var prop = type && getPropertyOfType(type, node.name.escapedText);
- return prop && getExplicitTypeOfSymbol(prop, diagnostic);
+ if (type) {
+ var name = node.name;
+ var prop = void 0;
+ if (ts.isPrivateIdentifier(name)) {
+ if (!type.symbol) {
+ return undefined;
+ }
+ prop = getPropertyOfType(type, ts.getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText));
+ }
+ else {
+ prop = getPropertyOfType(type, name.escapedText);
+ }
+ return prop && getExplicitTypeOfSymbol(prop, diagnostic);
+ }
+ return undefined;
+ }
case 207 /* ParenthesizedExpression */:
return getTypeOfDottedName(node.expression, diagnostic);
}
return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
}
else if (flags & 8 /* LoopLabel */) {
+ var antecedents = flow.antecedents;
+ if (antecedents === undefined || antecedents.length === 0) {
+ return false;
+ }
// A loop is reachable if the control flow path that leads to the top is reachable.
- flow = flow.antecedents[0];
+ flow = antecedents[0];
}
else if (flags & 128 /* SwitchClause */) {
// The control flow path representing an unmatched value in a switch statement with
if (flowDepth === 2000) {
// We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
// and disable further control flow analysis in the containing function or module body.
- ts.tracing.instant("check" /* Check */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id });
flowAnalysisDisabled = true;
reportFlowControlError(reference);
return errorType;
cache.set(key, result);
return result;
}
+ // At flow control branch or loop junctions, if the type along every antecedent code path
+ // is an evolving array type, we construct a combined evolving array type. Otherwise we
+ // finalize all evolving array types.
+ function getUnionOrEvolvingArrayType(types, subtypeReduction) {
+ if (isEvolvingArrayTypeList(types)) {
+ return getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType)));
+ }
+ var result = getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
+ if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* Union */ && ts.arraysEqual(result.types, declaredType.types)) {
+ return declaredType;
+ }
+ return result;
+ }
function isMatchingReferenceDiscriminant(expr, computedType) {
var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType;
if (!(type.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
if (propName === undefined) {
return type;
}
- var propType = getTypeOfPropertyOfType(type, propName);
+ var includesNullable = strictNullChecks && maybeTypeOfKind(type, 98304 /* Nullable */);
+ var removeNullable = includesNullable && ts.isOptionalChain(access);
+ var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName);
if (!propType) {
return type;
}
+ propType = removeNullable ? getOptionalType(propType) : propType;
var narrowedPropType = narrowType(propType);
return filterType(type, function (t) {
var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
return assignableType;
}
}
- // If the candidate type is a subtype of the target type, narrow to the candidate type,
- // if the target type is a subtype of the candidate type, narrow to the target type,
- // otherwise, narrow to an intersection of the two types.
- return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]);
+ // If the candidate type is a subtype of the target type, narrow to the candidate type.
+ // Otherwise, if the target type is assignable to the candidate type, keep the target type.
+ // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
+ // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
+ // two types.
+ return isTypeSubtypeOf(candidate, type) ? candidate :
+ isTypeAssignableTo(type, candidate) ? type :
+ isTypeAssignableTo(candidate, type) ? candidate :
+ getIntersectionType([type, candidate]);
}
function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
if (hasMatchingArgument(callExpression, reference)) {
}
function markAliasReferenced(symbol, location) {
if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
- if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
- markAliasSymbolAsReferenced(symbol);
- }
- else {
- markConstEnumAliasAsReferenced(symbol);
+ var target = resolveAlias(symbol);
+ if (target.flags & 111551 /* Value */) {
+ // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled
+ // (because the const enum value will not be inlined), or if (2) the alias is an export
+ // of a const enum declaration that will be preserved.
+ if (compilerOptions.isolatedModules ||
+ ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) ||
+ !isConstEnumOrConstEnumOnlyModule(target)) {
+ markAliasSymbolAsReferenced(symbol);
+ }
+ else {
+ markConstEnumAliasAsReferenced(symbol);
+ }
}
}
}
}
var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol;
- if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node.parent, sourceSymbol)) {
- errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText);
+ if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) {
+ addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText);
}
var declaration = localOrExportSymbol.valueDeclaration;
if (localOrExportSymbol.flags & 32 /* Class */) {
var objectLiteral = element.parent;
var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
if (type) {
- if (!hasNonBindableDynamicName(element)) {
+ if (hasBindableName(element)) {
// For a (non-symbol) computed property, there is no reason to look up the name
// in the type. It will just be "__computed", which does not appear in any
// SymbolTable.
}
function getContextualTypeForChildJsxExpression(node, child) {
var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
- // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
+ // JSX expression is in children of JSX Element, we will look for an "children" attribute (we get the name from JSX.ElementAttributesProperty)
var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
return undefined;
var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
}
+ case 225 /* NonNullExpression */:
+ return getContextualType(parent, contextFlags);
case 283 /* JsxExpression */:
return getContextualTypeForJsxExpression(parent);
case 280 /* JsxAttribute */:
}
return undefined;
function tryFindWhenConstTypeReference(node) {
- if (ts.isCallLikeExpression(node.parent)) {
- return getContextualTypeForArgument(node.parent, node);
- }
- return undefined;
+ return getContextualType(node);
}
}
function getInferenceContext(node) {
function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
var managedSym = getJsxLibraryManagedAttributes(ns);
if (managedSym) {
- var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
+ var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters
var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
+ if (managedSym.flags & 524288 /* TypeAlias */) {
+ var params = getSymbolLinks(managedSym).typeParameters;
+ if (ts.length(params) >= 2) {
+ var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context));
+ return getTypeAliasInstantiation(managedSym, args);
+ }
+ }
if (ts.length(declaredManagedType.typeParameters) >= 2) {
var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
return createTypeReference(declaredManagedType, args);
}
- else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
- var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
- return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
- }
}
return attributesType;
}
}
var signatureList;
var types = type.types;
- for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
- var current = types_18[_i];
+ for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
+ var current = types_20[_i];
var signature = getContextualCallSignature(current, node);
if (signature) {
if (!signatureList) {
}
function checkSpreadExpression(node, checkMode) {
if (languageVersion < 2 /* ES2015 */) {
- checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
+ checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */);
}
var arrayOrIterableType = checkExpression(node.expression, checkMode);
return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
var e = elements[i];
if (e.kind === 220 /* SpreadElement */) {
if (languageVersion < 2 /* ES2015 */) {
- checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
+ checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */);
}
var spreadType = checkExpression(e.expression, checkMode, forceTuple);
if (isArrayLikeType(spreadType)) {
checkJsxChildren(node);
return getJsxElementTypeAt(node) || anyType;
}
- /**
- * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
- */
function isUnhyphenatedJsxName(name) {
- // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
return !ts.stringContains(name, "-");
}
/**
var assignmentKind = ts.getAssignmentTargetKind(node);
var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
if (ts.isPrivateIdentifier(right)) {
- checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldGet */);
+ checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */);
}
var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
var prop;
}
prop = getPropertyOfType(apparentType, right.escapedText);
}
- if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
+ // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums.
+ // The exceptions are:
+ // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and
+ // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`.
+ if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) {
markAliasReferenced(parentSymbol, node);
}
var propType;
error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
}
propType = (compilerOptions.noUncheckedIndexedAccess && !ts.isAssignmentTarget(node)) ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
+ if (compilerOptions.noPropertyAccessFromIndexSignature && ts.isPropertyAccessExpression(node)) {
+ error(right, ts.Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, ts.unescapeLeadingUnderscores(right.escapedText));
+ }
}
else {
if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) {
- errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText);
+ addDeprecatedSuggestion(right, prop.declarations, right.escapedText);
}
checkPropertyNotUsedBeforeDeclaration(prop, node, right);
markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */);
// assignment target, and the referenced property was declared as a variable, property,
// accessor, or optional method.
var assignmentKind = ts.getAssignmentTargetKind(node);
- if (!ts.isAccessExpression(node) ||
- assignmentKind === 1 /* Definite */ ||
+ if (assignmentKind === 1 /* Definite */ ||
prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
return propType;
}
// and if we are in a constructor of the same class as the property declaration, assume that
// the property is uninitialized at the top of the control flow.
var assumeUninitialized = false;
- if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) {
+ if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) {
var declaration = prop && prop.valueDeclaration;
if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
var flowContainer = getControlFlowContainer(node);
}
}
if (typeHasStaticProperty(propNode.escapedText, containingType)) {
- errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
+ var propName = ts.declarationNameToString(propNode);
+ var typeName = typeToString(containingType);
+ errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "." + propName);
}
else {
var promisedType = getPromisedTypeOfPromise(containingType);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
+ function getThisArgumentType(thisArgumentNode) {
+ if (!thisArgumentNode) {
+ return voidType;
+ }
+ var thisArgumentType = checkExpression(thisArgumentNode);
+ return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) :
+ ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) :
+ thisArgumentType;
+ }
function inferTypeArguments(node, signature, args, checkMode, context) {
if (ts.isJsxOpeningLikeElement(node)) {
return inferJsxTypeArguments(node, signature, checkMode, context);
var thisType = getThisTypeOfSignature(signature);
if (thisType) {
var thisArgumentNode = getThisArgumentOfCall(node);
- var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
- inferTypes(context.inferences, thisArgumentType, thisType);
+ inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType);
}
for (var i = 0; i < argCount; i++) {
var arg = args[i];
/*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
function checkTagNameDoesNotExpectTooManyArguments() {
var _a;
+ if (getJsxNamespaceContainerForImplicitImport(node)) {
+ return true; // factory is implicitly jsx/jsxdev - assume it fits the bill, since we don't strongly look for the jsx/jsxs/jsxDEV factory APIs anywhere else (at least not yet)
+ }
var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
if (!tagType) {
return true;
// If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
// If the expression is a new expression, then the check is skipped.
var thisArgumentNode = getThisArgumentOfCall(node);
- var thisArgumentType = void 0;
- if (thisArgumentNode) {
- thisArgumentType = checkExpression(thisArgumentNode);
- if (ts.isOptionalChainRoot(thisArgumentNode.parent)) {
- thisArgumentType = getNonNullableType(thisArgumentType);
- }
- else if (ts.isOptionalChain(thisArgumentNode.parent)) {
- thisArgumentType = removeOptionalTypeMarker(thisArgumentType);
- }
- }
- else {
- thisArgumentType = voidType;
- }
+ var thisArgumentType = getThisArgumentType(thisArgumentNode);
var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
}
if (restType) {
var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined, checkMode);
- var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
+ var restArgCount = args.length - argCount;
+ var errorNode = !reportErrors ? undefined :
+ restArgCount === 0 ? node :
+ restArgCount === 1 ? args[argCount] :
+ ts.setTextRangePosEnd(createSyntheticExpression(node, spreadType), args[argCount].pos, args[args.length - 1].end);
if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
}
function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
if (ts.isCallExpression(node)) {
- var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length;
- return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3);
+ var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_6 = _a.length;
+ return ts.createFileDiagnostic(sourceFile, start, length_6, message, arg0, arg1, arg2, arg3);
}
else {
return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
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);
// The below is a spread to guarantee we get a new (mutable) array - our `flatMap` helper tries to do "smart" optimizations where it reuses input
// arrays and the emptyArray singleton where possible, which is decidedly not what we want while we're still constructing this diagnostic
- var related = __spreadArrays(ts.flatMap(diags_3, function (d) { return d.relatedInformation; }));
+ var related = __spreadArray([], ts.flatMap(diags_3, function (d) { return d.relatedInformation; }));
var diag = void 0;
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; })) {
- var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length;
- diag = { file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related };
+ var _b = diags_3[0], file = _b.file, start = _b.start, length_7 = _b.length;
+ diag = { file: file, start: start, length: length_7, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related };
}
else {
diag = ts.createDiagnosticForNodeFromMessageChain(node, chain, related);
if (ts.isCallChain(node)) {
var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
- ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ :
- 4 /* IsInnerCallChain */;
+ ts.isOutermostOptionalChain(node) ? 16 /* IsOuterCallChain */ :
+ 8 /* IsInnerCallChain */;
funcType = nonOptionalType;
}
else {
if (!isConstructorAccessible(node, constructSignatures[0])) {
return resolveErrorCall(node);
}
- // If the expression is a class of abstract type, then it cannot be instantiated.
- // Note, only class declarations can be declared abstract.
+ // If the expression is a class of abstract type, or an abstract construct signature,
+ // then it cannot be instantiated.
// In the case of a merged class-module or class-interface declaration,
// only the class declaration node will have the Abstract flag set.
+ if (constructSignatures.some(function (signature) { return signature.flags & 4 /* Abstract */; })) {
+ error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
+ return resolveErrorCall(node);
+ }
var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
if (valueDecl && ts.hasSyntacticModifier(valueDecl, 128 /* Abstract */)) {
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
if (apparentType.flags & 1048576 /* Union */) {
var types = apparentType.types;
var hasSignatures = false;
- for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
- var constituent = types_19[_i];
+ for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
+ var constituent = types_21[_i];
var signatures = getSignaturesOfType(constituent, kind);
if (signatures.length !== 0) {
hasSignatures = true;
ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
}
if (ts.isCallExpression(errorTarget.parent)) {
- var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length;
+ var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_8 = _b.length;
diagnostic.start = start;
- diagnostic.length = length_7;
+ diagnostic.length = length_8;
}
diagnostics.add(diagnostic);
invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
}
- if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ &&
+ if (node.kind === 203 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 233 /* ExpressionStatement */ &&
returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
if (!ts.isDottedName(node.expression)) {
error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
function checkDeprecatedSignature(signature, node) {
if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) {
var suggestionNode = getDeprecatedSuggestionNode(node);
- errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature));
+ var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node));
+ addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature));
}
}
function getDeprecatedSuggestionNode(node) {
if (!checkGrammarTaggedTemplateChain(node))
checkGrammarTypeArguments(node, node.typeArguments);
if (languageVersion < 2 /* ES2015 */) {
- checkExternalEmitHelpers(node, 524288 /* MakeTemplateObject */);
+ checkExternalEmitHelpers(node, 262144 /* MakeTemplateObject */);
}
var signature = getResolvedSignature(node);
checkDeprecatedSignature(signature, node);
}
return createTupleType(types, flags, /*readonly*/ false, ts.length(names) === ts.length(types) ? names : undefined);
}
+ // Return the number of parameters in a signature. The rest parameter, if present, counts as one
+ // parameter. For example, the parameter count of (x: number, y: number, ...z: string[]) is 3 and
+ // the parameter count of (x: number, ...args: [number, ...string[], boolean])) is also 3. In the
+ // latter example, the effective rest type is [...string[], boolean].
function getParameterCount(signature) {
var length = signature.parameters.length;
if (signatureHasRestParameter(signature)) {
}
}
if (minArgumentCount === undefined) {
- if (!strongArityForUntypedJS && signature.flags & 16 /* IsUntypedSignatureInJSFile */) {
+ if (!strongArityForUntypedJS && signature.flags & 32 /* IsUntypedSignatureInJSFile */) {
return 0;
}
minArgumentCount = signature.minArgumentCount;
}
if (type.flags & 3145728 /* UnionOrIntersection */) {
var types = type.types;
- for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
- var t = types_20[_i];
+ for (var _i = 0, types_22 = types; _i < types_22.length; _i++) {
+ var t = types_22[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
rightType = checkNonNullType(rightType, right);
// TypeScript 1.0 spec (April 2014): 4.15.5
// The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
- // and the right operand to be of type Any, an object type, or a type parameter type.
+ // and the right operand to be
+ //
+ // 1. assignable to the non-primitive type,
+ // 2. an unconstrained type parameter,
+ // 3. a union or intersection including one or more type parameters, whose constituents are all assignable to the
+ // the non-primitive type, or are unconstrainted type parameters, or have constraints assignable to the
+ // non-primitive type, or
+ // 4. a type parameter whose constraint is
+ // i. an object type,
+ // ii. the non-primitive type, or
+ // iii. a union or intersection with at least one constituent assignable to an object or non-primitive type.
+ //
+ // The divergent behavior for type parameters and unions containing type parameters is a workaround for type
+ // parameters not being narrowable. If the right operand is a concrete type, we can error if there is any chance
+ // it is a primitive. But if the operand is a type parameter, it cannot be narrowed, so we don't issue an error
+ // unless *all* instantiations would result in an error.
+ //
// The result is always of the Boolean primitive type.
if (!(allTypesAssignableToKind(leftType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) ||
isTypeAssignableToKind(leftType, 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 262144 /* TypeParameter */))) {
error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
}
- if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
- error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
+ var rightTypeConstraint = getConstraintOfType(rightType);
+ if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) ||
+ rightTypeConstraint && (isTypeAssignableToKind(rightType, 3145728 /* UnionOrIntersection */) && !allTypesAssignableToKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) ||
+ !maybeTypeOfKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */))) {
+ error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_not_be_a_primitive);
}
return booleanType;
}
checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
}
if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
- checkExternalEmitHelpers(target.parent, 2097152 /* ClassPrivateFieldSet */);
+ checkExternalEmitHelpers(target.parent, 1048576 /* ClassPrivateFieldSet */);
}
return sourceType;
}
workStacks.leftType[stackIndex] = leftType;
var operator = node.operatorToken.kind;
if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
+ if (operator === 55 /* AmpersandAmpersandToken */) {
+ var parent = ts.walkUpParenthesizedExpressions(node.parent);
+ checkTestingKnownTruthyCallableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined);
+ }
checkTruthinessOfType(leftType, node.left);
}
advanceState(2 /* FinishCheck */);
// Async generator functions prior to ESNext require the __await, __asyncDelegator,
// and __asyncValues helpers
if (isAsync && languageVersion < 99 /* ESNext */) {
- checkExternalEmitHelpers(node, 53248 /* AsyncDelegatorIncludes */);
+ checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
}
// Generator functions prior to ES2015 require the __values helper
if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
|| anyType;
}
- return getContextualIterationType(2 /* Next */, func) || anyType;
+ var type = getContextualIterationType(2 /* Next */, func);
+ if (!type) {
+ type = anyType;
+ if (produceDiagnostics && noImplicitAny && !ts.expressionResultIsUnused(node)) {
+ var contextualType = getContextualType(node);
+ if (!contextualType || isTypeAny(contextualType)) {
+ error(node, ts.Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation);
+ }
+ }
+ }
+ return type;
}
function checkConditionalExpression(node, checkMode) {
var type = checkTruthinessExpression(node.condition);
- checkTestingKnownTruthyCallableType(node.condition, node.whenTrue, type);
+ checkTestingKnownTruthyCallableType(node.condition, type, node.whenTrue);
var type1 = checkExpression(node.whenTrue, checkMode);
var type2 = checkExpression(node.whenFalse, checkMode);
return getUnionType([type1, type2], 2 /* Subtype */);
}
}
function checkExpression(node, checkMode, forceTuple) {
- ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end });
var saveCurrentNode = currentNode;
currentNode = node;
instantiationCount = 0;
checkConstEnumAccess(node, type);
}
currentNode = saveCurrentNode;
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
return type;
}
function checkConstEnumAccess(node, type) {
if (!(functionFlags & 4 /* Invalid */)) {
// Async generators prior to ESNext require the __await and __asyncGenerator helpers
if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
- checkExternalEmitHelpers(node, 12288 /* AsyncGeneratorIncludes */);
+ checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
}
// Async functions prior to ES2017 require the __awaiter helper
if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
if (ts.isPrivateIdentifier(node.name)) {
error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
}
- if (!hasNonBindableDynamicName(node)) {
+ if (hasBindableName(node)) {
// TypeScript 1.0 spec (April 2014): 8.4.3
// Accessors for the same member name must specify the same accessibility.
var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */;
var symbol = getNodeLinks(node).resolvedSymbol;
if (symbol) {
if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) {
- errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName);
+ addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName);
}
if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) {
error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
var seenOptionalElement = false;
var seenRestElement = false;
var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember);
- for (var i = 0; i < elementTypes.length; i++) {
- var e = elementTypes[i];
+ for (var _i = 0, elementTypes_1 = elementTypes; _i < elementTypes_1.length; _i++) {
+ var e = elementTypes_1[_i];
if (e.kind !== 192 /* NamedTupleMember */ && hasNamedElement) {
grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names);
break;
}
}
else if (flags & 4 /* Rest */) {
+ if (seenRestElement) {
+ grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_cannot_follow_another_rest_element);
+ break;
+ }
seenRestElement = true;
}
else if (flags & 2 /* Optional */) {
+ if (seenRestElement) {
+ grammarErrorOnNode(e, ts.Diagnostics.An_optional_element_cannot_follow_a_rest_element);
+ break;
+ }
seenOptionalElement = true;
}
else if (seenOptionalElement) {
grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
break;
}
- if (seenRestElement && i !== elementTypes.length - 1) {
- grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
- break;
- }
}
ts.forEach(node.elements, checkSourceElement);
getTypeFromTypeNode(node);
}
function getEntityNameForDecoratorMetadataFromTypeList(types) {
var commonEntityName;
- for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
- var typeNode = types_21[_i];
+ for (var _i = 0, types_23 = types; _i < types_23.length; _i++) {
+ var typeNode = types_23[_i];
while (typeNode.kind === 186 /* ParenthesizedType */ || typeNode.kind === 192 /* NamedTupleMember */) {
typeNode = typeNode.type; // Skip parens if need be
}
// as well as accessors in classes/object literals
checkComputedPropertyName(node.name);
}
- if (!hasNonBindableDynamicName(node)) {
+ if (hasBindableName(node)) {
// first we want to check the local symbol that contain this declaration
// - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
// - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
if (ts.isInJSFile(node)) {
var typeTag = ts.getJSDocTypeTag(node);
if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
- error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
+ error(typeTag.typeExpression.type, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
}
}
}
var parent = typeParameter.parent;
if (parent.kind !== 185 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) {
+ var sourceFile = ts.getSourceFileOfNode(parent);
var range = ts.isJSDocTemplateTag(parent)
// Whole @template tag
? ts.rangeOfNode(parent)
// Include the `<>` in the error message
- : ts.rangeOfTypeParameters(parent.typeParameters);
+ : ts.rangeOfTypeParameters(sourceFile, parent.typeParameters);
var only = parent.typeParameters.length === 1;
var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
var arg0 = only ? name : undefined;
- addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
+ addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, message, arg0));
}
}
else {
return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
}
function isValidUnusedLocalDeclaration(declaration) {
- if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
- return !!ts.findAncestor(declaration.parent, function (ancestor) {
- return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false :
- ts.isForOfStatement(ancestor) ? true : "quit";
- });
+ if (ts.isBindingElement(declaration)) {
+ if (ts.isObjectBindingPattern(declaration.parent)) {
+ /**
+ * ignore starts with underscore names _
+ * const { a: _a } = { a: 1 }
+ */
+ return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name));
+ }
+ return isIdentifierThatStartsWithUnderscore(declaration.name);
}
return ts.isAmbientModule(declaration) ||
(ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
if (parameter && name) {
if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
- addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
+ if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) {
+ addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
+ }
+ else {
+ addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
+ }
}
}
else {
return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags);
}
function checkVariableDeclaration(node) {
- ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end });
checkGrammarVariableDeclaration(node);
checkVariableLikeDeclaration(node);
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
}
function checkBindingElement(node) {
checkGrammarBindingElement(node);
// Grammar checking
checkGrammarStatementInAmbientContext(node);
var type = checkTruthinessExpression(node.expression);
- checkTestingKnownTruthyCallableType(node.expression, node.thenStatement, type);
+ checkTestingKnownTruthyCallableType(node.expression, type, node.thenStatement);
checkSourceElement(node.thenStatement);
if (node.thenStatement.kind === 231 /* EmptyStatement */) {
error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
}
checkSourceElement(node.elseStatement);
}
- function checkTestingKnownTruthyCallableType(condExpr, body, type) {
+ function checkTestingKnownTruthyCallableType(condExpr, type, body) {
if (!strictNullChecks) {
return;
}
- var testedNode = ts.isIdentifier(condExpr)
- ? condExpr
- : ts.isPropertyAccessExpression(condExpr)
- ? condExpr.name
- : undefined;
- if (!testedNode) {
+ var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr;
+ var testedNode = ts.isIdentifier(location) ? location
+ : ts.isPropertyAccessExpression(location) ? location.name
+ : ts.isBinaryExpression(location) && ts.isIdentifier(location.right) ? location.right
+ : undefined;
+ var isPropertyExpressionCast = ts.isPropertyAccessExpression(location)
+ && ts.isAssertionExpression(ts.skipParentheses(location.expression));
+ if (!testedNode || isPropertyExpressionCast) {
return;
}
var possiblyFalsy = getFalsyFlags(type);
if (callSignatures.length === 0) {
return;
}
- var testedFunctionSymbol = getSymbolAtLocation(testedNode);
- if (!testedFunctionSymbol) {
+ var testedSymbol = getSymbolAtLocation(testedNode);
+ if (!testedSymbol) {
return;
}
- var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) {
+ var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol)
+ || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol);
+ if (!isUsed) {
+ error(location, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
+ }
+ }
+ function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) {
+ return !!ts.forEachChild(body, function check(childNode) {
if (ts.isIdentifier(childNode)) {
var childSymbol = getSymbolAtLocation(childNode);
- if (childSymbol && childSymbol === testedFunctionSymbol) {
+ if (childSymbol && childSymbol === testedSymbol) {
// If the test was a simple identifier, the above check is sufficient
- if (ts.isIdentifier(condExpr)) {
+ if (ts.isIdentifier(expr)) {
return true;
}
// Otherwise we need to ensure the symbol is called on the same target
testedExpression.kind === 107 /* ThisKeyword */ && childExpression.kind === 107 /* ThisKeyword */) {
return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
}
- if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
+ else if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
return false;
}
childExpression = childExpression.expression;
testedExpression = testedExpression.expression;
}
+ else if (ts.isCallExpression(testedExpression) && ts.isCallExpression(childExpression)) {
+ childExpression = childExpression.expression;
+ testedExpression = testedExpression.expression;
+ }
else {
return false;
}
}
return ts.forEachChild(childNode, check);
});
- if (!functionIsUsedInBody) {
- error(condExpr, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
+ }
+ function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) {
+ while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
+ var isUsed = ts.forEachChild(node.right, function visit(child) {
+ if (ts.isIdentifier(child)) {
+ var symbol = getSymbolAtLocation(child);
+ if (symbol && symbol === testedSymbol) {
+ return true;
+ }
+ }
+ return ts.forEachChild(child, visit);
+ });
+ if (isUsed) {
+ return true;
+ }
+ node = node.parent;
}
+ return false;
}
function checkDoStatement(node) {
// Grammar checking
var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
// for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
- checkExternalEmitHelpers(node, 32768 /* ForAwaitOfIncludes */);
+ checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
}
}
else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
// Only process instance properties with computed names here.
// Static properties cannot be in conflict with indexers,
// and properties with literal names were already checked.
- if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
+ if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) {
var symbol = getSymbolOfNode(member);
var propType = getTypeOfSymbol(symbol);
checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
// Report static side error only when instance type is assignable
checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
}
- if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
- error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
+ if (baseConstructorType.flags & 8650752 /* TypeVariable */) {
+ if (!isMixinConstructorType(staticType)) {
+ error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
+ }
+ else {
+ var constructSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
+ if (constructSignatures.some(function (signature) { return signature.flags & 4 /* Abstract */; }) && !ts.hasSyntacticModifier(node, 128 /* Abstract */)) {
+ error(node.name || node, ts.Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract);
+ }
+ }
}
if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
// When the static base type is a "class-like" constructor function (but not actually a class), we verify
if (implementedTypeNodes) {
for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
var typeRefNode = implementedTypeNodes_1[_b];
- if (!ts.isEntityNameExpression(typeRefNode.expression)) {
+ if (!ts.isEntityNameExpression(typeRefNode.expression) || ts.isOptionalChain(typeRefNode.expression)) {
error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
}
checkTypeReferenceNode(typeRefNode);
checkObjectTypeForDuplicateDeclarations(node);
}
ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
- if (!ts.isEntityNameExpression(heritageElement.expression)) {
+ if (!ts.isEntityNameExpression(heritageElement.expression) || ts.isOptionalChain(heritageElement.expression)) {
error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
}
checkTypeReferenceNode(heritageElement);
if (symbol.flags & 512 /* ValueModule */
&& !inAmbientContext
&& symbol.declarations.length > 1
- && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
+ && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) {
var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
if (firstNonAmbientClassOrFunc) {
if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
return true;
}
function checkAliasSymbol(node) {
+ var _a;
var symbol = getSymbolOfNode(node);
var target = resolveAlias(symbol);
if (target !== unknownSymbol) {
&& !(node.flags & 8388608 /* Ambient */)) {
error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
}
- if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) {
- errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName);
+ if (ts.isImportSpecifier(node) && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }))) {
+ addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName);
}
}
}
ts.idText(node.propertyName || node.name) === "default" &&
compilerOptions.esModuleInterop &&
moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
- checkExternalEmitHelpers(node, 262144 /* ImportDefault */);
+ checkExternalEmitHelpers(node, 131072 /* ImportDefault */);
}
}
function checkImportDeclaration(node) {
checkImportBinding(importClause.namedBindings);
if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015 && compilerOptions.esModuleInterop) {
// import * as ns from "foo";
- checkExternalEmitHelpers(node, 131072 /* ImportStar */);
+ checkExternalEmitHelpers(node, 65536 /* ImportStar */);
}
}
else {
checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
}
}
+ if (node.isTypeOnly) {
+ grammarErrorOnNode(node, ts.Diagnostics.An_import_alias_cannot_use_import_type);
+ }
}
else {
- if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 8388608 /* Ambient */)) {
+ if (moduleKind >= ts.ModuleKind.ES2015 && !node.isTypeOnly && !(node.flags & 8388608 /* Ambient */)) {
// Import equals declaration is deprecated in es6 or above
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);
}
grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
}
if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
- checkExternalEmitHelpers(node, 4194304 /* CreateBinding */);
+ checkExternalEmitHelpers(node, 2097152 /* CreateBinding */);
}
checkGrammarExportDeclaration(node);
if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
// For ES2015 modules, we emit it as a pair of `import * as a_1 ...; export { a_1 as ns }` and don't need the helper.
// We only use the helper here when in esModuleInterop
if (compilerOptions.esModuleInterop) {
- checkExternalEmitHelpers(node, 131072 /* ImportStar */);
+ checkExternalEmitHelpers(node, 65536 /* ImportStar */);
}
}
else {
// export * from "foo"
- checkExternalEmitHelpers(node, 65536 /* ExportStar */);
+ checkExternalEmitHelpers(node, 32768 /* ExportStar */);
}
}
}
return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
});
}
+ function canConvertImportDeclarationToTypeOnly(statement) {
+ return ts.isImportDeclaration(statement) &&
+ statement.importClause &&
+ !statement.importClause.isTypeOnly &&
+ importClauseContainsReferencedImport(statement.importClause) &&
+ !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
+ !importClauseContainsConstEnumUsedAsValue(statement.importClause);
+ }
+ function canConvertImportEqualsDeclarationToTypeOnly(statement) {
+ return ts.isImportEqualsDeclaration(statement) &&
+ ts.isExternalModuleReference(statement.moduleReference) &&
+ !statement.isTypeOnly &&
+ getSymbolOfNode(statement).isReferenced &&
+ !isReferencedAliasDeclaration(statement, /*checkChildren*/ false) &&
+ !getSymbolLinks(getSymbolOfNode(statement)).constEnumReferenced;
+ }
function checkImportsForTypeOnlyConversion(sourceFile) {
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var statement = _a[_i];
- if (ts.isImportDeclaration(statement) &&
- statement.importClause &&
- !statement.importClause.isTypeOnly &&
- importClauseContainsReferencedImport(statement.importClause) &&
- !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
- !importClauseContainsConstEnumUsedAsValue(statement.importClause)) {
- error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error);
+ if (canConvertImportDeclarationToTypeOnly(statement) || canConvertImportEqualsDeclarationToTypeOnly(statement)) {
+ error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error);
}
}
}
moduleKind !== ts.ModuleKind.System &&
moduleKind < ts.ModuleKind.ES2015 &&
ts.idText(node.propertyName || node.name) === "default") {
- checkExternalEmitHelpers(node, 262144 /* ImportDefault */);
+ checkExternalEmitHelpers(node, 131072 /* ImportDefault */);
}
}
}
return checkPropertyDeclaration(node);
case 162 /* PropertySignature */:
return checkPropertySignature(node);
- case 174 /* FunctionType */:
case 175 /* ConstructorType */:
+ case 174 /* FunctionType */:
case 169 /* CallSignature */:
case 170 /* ConstructSignature */:
case 171 /* IndexSignature */:
}
}
function checkDeferredNode(node) {
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end });
var saveCurrentNode = currentNode;
currentNode = node;
instantiationCount = 0;
break;
}
currentNode = saveCurrentNode;
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
}
function checkSourceFile(node) {
- var tracingData = ["check" /* Check */, "checkSourceFile", { path: node.path }];
- ts.tracing.begin.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true);
ts.performance.mark("beforeCheck");
checkSourceFileWorker(node);
ts.performance.mark("afterCheck");
ts.performance.measure("Check", "beforeCheck", "afterCheck");
- ts.tracing.end.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
}
function unusedIsError(kind, isAmbient) {
if (isAmbient) {
// const enums and modules that contain only const enums are not considered values from the emit perspective
// unless 'preserveConstEnums' option is set to true
return !!(target.flags & 111551 /* Value */) &&
- (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
+ (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target));
}
function isConstEnumOrConstEnumOnlyModule(s) {
return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
function isReferencedAliasDeclaration(node, checkChildren) {
if (isAliasSymbolDeclaration(node)) {
var symbol = getSymbolOfNode(node);
- if (symbol && getSymbolLinks(symbol).referenced) {
+ var links = symbol && getSymbolLinks(symbol);
+ if (links === null || links === void 0 ? void 0 : links.referenced) {
return true;
}
var target = getSymbolLinks(symbol).target; // TODO: GH#18217
if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ &&
target.flags & 111551 /* Value */ &&
- (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
+ (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) {
// An `export import ... =` of a value symbol is always considered referenced
return true;
}
isOptionalParameter: isOptionalParameter,
moduleExportsSomeValue: moduleExportsSomeValue,
isArgumentsLocalBinding: isArgumentsLocalBinding,
- getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
+ getExternalModuleFileFromDeclaration: function (nodeIn) {
+ var node = ts.getParseTreeNode(nodeIn, ts.hasPossibleExternalModuleReference);
+ return node && getExternalModuleFileFromDeclaration(node);
+ },
getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
isLiteralConstDeclaration: isLiteralConstDeclaration,
var helpersModule = resolveHelpersModule(sourceFile, location);
if (helpersModule !== unknownSymbol) {
var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
- for (var helper = 1 /* FirstEmitHelper */; helper <= 4194304 /* LastEmitHelper */; helper <<= 1) {
+ for (var helper = 1 /* FirstEmitHelper */; helper <= 2097152 /* LastEmitHelper */; helper <<= 1) {
if (uncheckedHelpers & helper) {
var name = getHelperName(helper);
var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
case 128 /* Generator */: return "__generator";
case 256 /* Values */: return "__values";
case 512 /* Read */: return "__read";
- case 1024 /* Spread */: return "__spread";
- case 2048 /* SpreadArrays */: return "__spreadArrays";
- case 4096 /* Await */: return "__await";
- case 8192 /* AsyncGenerator */: return "__asyncGenerator";
- case 16384 /* AsyncDelegator */: return "__asyncDelegator";
- case 32768 /* AsyncValues */: return "__asyncValues";
- case 65536 /* ExportStar */: return "__exportStar";
- case 131072 /* ImportStar */: return "__importStar";
- case 262144 /* ImportDefault */: return "__importDefault";
- case 524288 /* MakeTemplateObject */: return "__makeTemplateObject";
- case 1048576 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
- case 2097152 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
- case 4194304 /* CreateBinding */: return "__createBinding";
+ case 1024 /* SpreadArray */: return "__spreadArray";
+ case 2048 /* Await */: return "__await";
+ case 4096 /* AsyncGenerator */: return "__asyncGenerator";
+ case 8192 /* AsyncDelegator */: return "__asyncDelegator";
+ case 16384 /* AsyncValues */: return "__asyncValues";
+ case 32768 /* ExportStar */: return "__exportStar";
+ case 65536 /* ImportStar */: return "__importStar";
+ case 131072 /* ImportDefault */: return "__importDefault";
+ case 262144 /* MakeTemplateObject */: return "__makeTemplateObject";
+ case 524288 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
+ case 1048576 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
+ case 2097152 /* CreateBinding */: return "__createBinding";
default: return ts.Debug.fail("Unrecognized helper");
}
}
if (flags & 128 /* Abstract */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
}
- if (node.kind !== 252 /* ClassDeclaration */) {
+ if (node.kind !== 252 /* ClassDeclaration */ &&
+ node.kind !== 175 /* ConstructorType */) {
if (node.kind !== 165 /* MethodDeclaration */ &&
node.kind !== 163 /* PropertyDeclaration */ &&
node.kind !== 167 /* GetAccessor */ &&
case 251 /* FunctionDeclaration */:
return nodeHasAnyModifiersExcept(node, 129 /* AsyncKeyword */);
case 252 /* ClassDeclaration */:
+ case 175 /* ConstructorType */:
return nodeHasAnyModifiersExcept(node, 125 /* AbstractKeyword */);
case 253 /* InterfaceDeclaration */:
case 232 /* VariableStatement */:
return nodeHasAnyModifiersExcept(node, 84 /* ConstKeyword */);
default:
ts.Debug.fail();
- return false;
}
}
}
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));
});
var diagnostics_2 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
- ts.addRelatedInfo.apply(void 0, __spreadArrays([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_2));
+ ts.addRelatedInfo.apply(void 0, __spreadArray([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_2));
return true;
}
}
return true;
}
if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
- if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) {
- // use of 'for-await-of' in non-async function
+ if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) {
var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
- if (!hasParseDiagnostics(sourceFile)) {
- var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
- var func = ts.getContainingFunction(forInOrOfStatement);
- if (func && func.kind !== 166 /* Constructor */) {
- ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
- var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
- ts.addRelatedInfo(diagnostic, relatedInfo);
- }
- diagnostics.add(diagnostic);
- return true;
+ if (ts.isInTopLevelContext(forInOrOfStatement)) {
+ if (!hasParseDiagnostics(sourceFile)) {
+ if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
+ diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module));
+ }
+ if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
+ diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher));
+ }
+ }
+ }
+ else {
+ // use of 'for-await-of' in non-async function
+ if (!hasParseDiagnostics(sourceFile)) {
+ var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules);
+ var func = ts.getContainingFunction(forInOrOfStatement);
+ if (func && func.kind !== 166 /* Constructor */) {
+ ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
+ var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
+ ts.addRelatedInfo(diagnostic, relatedInfo);
+ }
+ diagnostics.add(diagnostic);
+ return true;
+ }
}
return false;
}
if (node.exclamationToken && (node.parent.parent.kind !== 232 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
var message = node.initializer
? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions
- : ts.Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations;
+ : !node.type
+ ? ts.Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations
+ : ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context;
return grammarErrorOnNode(node.exclamationToken, message);
}
var moduleKind = ts.getEmitModuleKind(compilerOptions);
case 174 /* FunctionType */:
return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
case 175 /* ConstructorType */:
- return factory.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
+ return factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
case 176 /* TypeQuery */:
return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName));
case 177 /* TypeLiteral */:
case 259 /* NamespaceExportDeclaration */:
return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
case 260 /* ImportEqualsDeclaration */:
- return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference));
+ return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference));
case 261 /* ImportDeclaration */:
return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression));
case 262 /* ImportClause */:
bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
// If the right-hand value of the assignment is also an assignment target then
// we need to cache the right-hand value.
- initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
+ initializer = ensureIdentifier(flattenContext, ts.visitNode(initializer, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, initializer);
node = context.factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, initializer);
}
}
// Note when updating logic here also update getEntityNameForDecoratorMetadata
// so that aliases can be marked as referenced
var serializedUnion;
- for (var _i = 0, types_22 = types; _i < types_22.length; _i++) {
- var typeNode = types_22[_i];
+ for (var _i = 0, types_24 = types; _i < types_24.length; _i++) {
+ var typeNode = types_24[_i];
while (typeNode.kind === 186 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
return !ts.nodeIsMissing(node.body);
}
function visitPropertyDeclaration(node) {
- if (node.flags & 8388608 /* Ambient */) {
+ if (node.flags & 8388608 /* Ambient */ || ts.hasSyntacticModifier(node, 128 /* Abstract */)) {
return undefined;
}
var updated = factory.updatePropertyDeclaration(node,
*/
function shouldEmitEnumDeclaration(node) {
return !ts.isEnumConst(node)
- || compilerOptions.preserveConstEnums
- || compilerOptions.isolatedModules;
+ || ts.shouldPreserveConstEnums(compilerOptions);
}
/**
* Visits an enum declaration.
// If we can't find a parse tree node, assume the node is instantiated.
return true;
}
- return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
+ return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions));
}
/**
* Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
* @param node The import equals declaration node.
*/
function visitImportEqualsDeclaration(node) {
+ // Always elide type-only imports
+ if (node.isTypeOnly) {
+ return undefined;
+ }
if (ts.isExternalModuleImportEqualsDeclaration(node)) {
var isReferenced = resolver.isReferencedAliasDeclaration(node);
// If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
return visitPropertyDeclaration(node);
case 232 /* VariableStatement */:
return visitVariableStatement(node);
- case 158 /* ComputedPropertyName */:
- return visitComputedPropertyName(node);
case 201 /* PropertyAccessExpression */:
return visitPropertyAccessExpression(node);
case 214 /* PrefixUnaryExpression */:
var savedPendingStatements = pendingStatements;
pendingStatements = [];
var visitedNode = ts.visitEachChild(node, visitor, context);
- var statement = ts.some(pendingStatements) ? __spreadArrays([visitedNode], pendingStatements) :
+ var statement = ts.some(pendingStatements) ? __spreadArray([visitedNode], pendingStatements) :
visitedNode;
pendingStatements = savedPendingStatements;
return statement;
var node = ts.visitEachChild(name, visitor, context);
if (ts.some(pendingExpressions)) {
var expressions = pendingExpressions;
- expressions.push(name.expression);
+ expressions.push(node.expression);
pendingExpressions = [];
node = factory.updateComputedPropertyName(node, factory.inlineExpressions(expressions));
}
if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
// Transform call expressions of private names to properly bind the `this` parameter.
var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
+ if (ts.isCallChain(node)) {
+ return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"),
+ /*questionDotToken*/ undefined,
+ /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
+ }
return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"),
- /*typeArguments*/ undefined, __spreadArrays([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
+ /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
}
return ts.visitEachChild(node, visitor, context);
}
pendingExpressions = undefined;
node = factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorDestructuringTarget), node.operatorToken, ts.visitNode(node.right, visitor));
var expr = ts.some(pendingExpressions) ?
- factory.inlineExpressions(ts.compact(__spreadArrays(pendingExpressions, [node]))) :
+ factory.inlineExpressions(ts.compact(__spreadArray(__spreadArray([], pendingExpressions), [node]))) :
node;
pendingExpressions = savedPendingExpressions;
return expr;
return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members);
}
function isPropertyDeclarationThatRequiresConstructorStatement(member) {
- if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member)) {
+ if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) {
return false;
}
if (context.getCompilerOptions().useDefineForClassFields) {
return undefined;
}
var propertyOriginalNode = ts.getOriginalNode(property);
- var initializer = property.initializer || emitAssignment ? (_a = ts.visitNode(property.initializer, visitor, ts.isExpression)) !== null && _a !== void 0 ? _a : factory.createVoidZero() : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
- : factory.createVoidZero();
+ if (ts.hasSyntacticModifier(propertyOriginalNode, 128 /* Abstract */)) {
+ return undefined;
+ }
+ var initializer = property.initializer || emitAssignment ? (_a = ts.visitNode(property.initializer, visitor, ts.isExpression)) !== null && _a !== void 0 ? _a : factory.createVoidZero()
+ : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
+ : factory.createVoidZero();
if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
var memberAccess = ts.createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ propertyName);
return factory.createAssignment(memberAccess, initializer);
? substitutePropertyAccessExpression(expression)
: substituteElementAccessExpression(expression);
return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"),
- /*typeArguments*/ undefined, __spreadArrays([
+ /*typeArguments*/ undefined, __spreadArray([
factory.createThis()
], node.arguments));
}
var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
var block = ts.visitNode(node.block, visitor, ts.isBlock);
if (ts.some(visitedBindings)) {
- block = factory.updateBlock(block, __spreadArrays([
+ block = factory.updateBlock(block, __spreadArray([
factory.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
], block.statements));
}
? substitutePropertyAccessExpression(expression)
: substituteElementAccessExpression(expression);
return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"),
- /*typeArguments*/ undefined, __spreadArrays([
+ /*typeArguments*/ undefined, __spreadArray([
factory.createThis()
], node.arguments));
}
if (!ts.isSimpleCopiableExpression(expression)) {
thisArg = factory.createTempVariable(hoistVariableDeclaration);
expression = factory.createAssignment(thisArg, expression);
- // if (inParameterInitializer) tempVariableInParameter = true;
}
else {
thisArg = expression;
if (!ts.isSimpleCopiableExpression(leftExpression)) {
capturedLeft = factory.createTempVariable(hoistVariableDeclaration);
leftExpression = factory.createAssignment(capturedLeft, leftExpression);
- // if (inParameterInitializer) tempVariableInParameter = true;
}
var rightExpression = capturedLeft;
var thisArg;
if (!ts.isSimpleCopiableExpression(rightExpression)) {
thisArg = factory.createTempVariable(hoistVariableDeclaration);
rightExpression = factory.createAssignment(thisArg, rightExpression);
- // if (inParameterInitializer) tempVariableInParameter = true;
}
else {
thisArg = rightExpression;
var target = isDelete
? factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createTrue(), /*colonToken*/ undefined, factory.createDeleteExpression(rightExpression))
: factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createVoidZero(), /*colonToken*/ undefined, rightExpression);
+ ts.setTextRange(target, node);
return thisArg ? factory.createSyntheticReferenceExpression(target, thisArg) : target;
}
function createNotNullCondition(left, right, invert) {
if (!ts.isSimpleCopiableExpression(left)) {
right = factory.createTempVariable(hoistVariableDeclaration);
left = factory.createAssignment(right, left);
- // if (inParameterInitializer) tempVariableInParameter = true;
}
- return factory.createConditionalExpression(createNotNullCondition(left, right),
+ return ts.setTextRange(factory.createConditionalExpression(createNotNullCondition(left, right),
/*questionToken*/ undefined, right,
- /*colonToken*/ undefined, ts.visitNode(node.right, visitor, ts.isExpression));
+ /*colonToken*/ undefined, ts.visitNode(node.right, visitor, ts.isExpression)), node);
}
function visitDeleteExpression(node) {
return ts.isOptionalChain(ts.skipParentheses(node.expression))
if (ts.isBlock(statement))
ts.setOriginalNode(loopBody, statement);
var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
- var emitFlags = 0;
+ var emitFlags = 524288 /* ReuseTempVariableScope */;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
}
function addStatementToStartOfBlock(block, statement) {
var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
- return factory.updateBlock(block, __spreadArrays([statement], transformedStatements));
+ return factory.updateBlock(block, __spreadArray([statement], transformedStatements));
}
/**
* Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
// [output]
// new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
var _a = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
- return factory.createNewExpression(factory.createFunctionApplyCall(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(factory.createNodeArray(__spreadArrays([factory.createVoidZero()], node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)),
+ return factory.createNewExpression(factory.createFunctionApplyCall(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(factory.createNodeArray(__spreadArray([factory.createVoidZero()], node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)),
/*typeArguments*/ undefined, []);
}
return ts.visitEachChild(node, visitor, context);
*
* @param elements The array of Expression nodes.
* @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
+ * This should be `true` when spreading into an `ArrayLiteral`, and `false` when spreading into an
+ * argument list.
* @param multiLine A value indicating whether the result should be emitted on multiple lines.
*/
function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
+ // When there is no leading SpreadElement:
+ //
// [source]
// [a, ...b, c]
//
// [output (downlevelIteration)]
- // __spread([a], b, [c])
+ // __spreadArray(__spreadArray([a], __read(b)), [c])
//
// [output]
- // __spreadArrays([a], b, [c])
+ // __spreadArray(__spreadArray([a], b), [c])
+ //
+ // When there *is* a leading SpreadElement:
+ //
+ // [source]
+ // [...a, b]
+ //
+ // [output (downlevelIteration)]
+ // __spreadArray(__spreadArray([], __read(a)), [b])
+ //
+ // [output]
+ // __spreadArray(__spreadArray([], a), [b])
+ //
+ // NOTE: We use `isPackedArrayLiteral` below rather than just `isArrayLiteral`
+ // because ES2015 spread will replace _missing_ array elements with `undefined`,
+ // so we cannot just use an array as is. For example:
+ //
+ // `[1, ...[2, , 3]]` becomes `[1, 2, undefined, 3]`
+ //
+ // However, for packed array literals (i.e., an array literal with no OmittedExpression
+ // elements), we can use the array as-is.
// Map spans of spread expressions into their expressions and spans of other
// expressions into an array literal.
var numElements = elements.length;
var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
}));
- if (compilerOptions.downlevelIteration) {
- if (segments.length === 1) {
- var firstSegment = segments[0];
- if (isCallToHelper(firstSegment, "___spread")) {
- return segments[0];
- }
- }
- return emitHelpers().createSpreadHelper(segments);
+ if (segments.length === 1) {
+ var firstSegment = segments[0];
+ // If we don't need a unique copy, then we are spreading into an argument list for
+ // a CallExpression or NewExpression. When using `--downlevelIteration`, we need
+ // to coerce this into an array for use with `apply`, so we will use the code path
+ // that follows instead.
+ if (!needsUniqueCopy && !compilerOptions.downlevelIteration
+ || ts.isPackedArrayLiteral(firstSegment) // see NOTE (above)
+ || ts.isCallToHelper(firstSegment, "___spreadArray")) {
+ return segments[0];
+ }
+ }
+ var helpers = emitHelpers();
+ var startsWithSpread = ts.isSpreadElement(elements[0]);
+ var expression = startsWithSpread ? factory.createArrayLiteralExpression() :
+ segments[0];
+ for (var i = startsWithSpread ? 0 : 1; i < segments.length; i++) {
+ expression = helpers.createSpreadArrayHelper(expression, compilerOptions.downlevelIteration && !ts.isPackedArrayLiteral(segments[i]) ? // see NOTE (above)
+ helpers.createReadHelper(segments[i], /*count*/ undefined) :
+ segments[i]);
}
- else {
- if (segments.length === 1) {
- var firstSegment = segments[0];
- if (!needsUniqueCopy
- || isPackedArrayLiteral(firstSegment)
- || isCallToHelper(firstSegment, "___spreadArrays")) {
- return segments[0];
- }
- }
- return emitHelpers().createSpreadArraysHelper(segments);
- }
- }
- function isPackedElement(node) {
- return !ts.isOmittedExpression(node);
- }
- function isPackedArrayLiteral(node) {
- return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
- }
- function isCallToHelper(firstSegment, helperName) {
- return ts.isCallExpression(firstSegment)
- && ts.isIdentifier(firstSegment.expression)
- && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
- && firstSegment.expression.escapedText === helperName;
+ return expression;
}
function partitionSpread(node) {
return ts.isSpreadElement(node)
temp = declareLocal();
var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
emitAssignment(temp, factory.createArrayLiteralExpression(leadingElement
- ? __spreadArrays([leadingElement], initialElements) : initialElements));
+ ? __spreadArray([leadingElement], initialElements) : initialElements));
leadingElement = undefined;
}
var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
return temp
? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
- : ts.setTextRange(factory.createArrayLiteralExpression(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine), location);
+ : ts.setTextRange(factory.createArrayLiteralExpression(leadingElement ? __spreadArray([leadingElement], expressions) : expressions, multiLine), location);
function reduceElement(expressions, element) {
if (containsYield(element) && expressions.length > 0) {
var hasAssignedTemp = temp !== undefined;
}
emitAssignment(temp, hasAssignedTemp
? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
- : factory.createArrayLiteralExpression(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine));
+ : factory.createArrayLiteralExpression(leadingElement ? __spreadArray([leadingElement], expressions) : expressions, multiLine));
leadingElement = undefined;
expressions = [];
}
// define(mofactory.updateSourceFile", "module2"], function ...
var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
factory.createExpressionStatement(factory.createCallExpression(define,
- /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
+ /*typeArguments*/ undefined, __spreadArray(__spreadArray([], (moduleName ? [moduleName] : [])), [
// Add the dependency array argument:
//
// ["require", "exports", module1", "module2", ...]
- factory.createArrayLiteralExpression(jsonSourceFile ? ts.emptyArray : __spreadArrays([
+ factory.createArrayLiteralExpression(jsonSourceFile ? ts.emptyArray : __spreadArray(__spreadArray([
factory.createStringLiteral("require"),
factory.createStringLiteral("exports")
- ], aliasedModuleNames, unaliasedModuleNames)),
+ ], aliasedModuleNames), unaliasedModuleNames)),
// Add the module body function argument:
//
// function (require, exports, module1, module2) ...
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
- /*typeParameters*/ undefined, __spreadArrays([
+ /*typeParameters*/ undefined, __spreadArray([
factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
], importAliasNames),
ts.setEmitFlags(factory.createIfStatement(factory.createStrictInequality(factory.createIdentifier("v"), factory.createIdentifier("undefined")), factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), factory.createIdentifier("v")))), 1 /* SingleLine */)
]), factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("define"), "function"), factory.createPropertyAccessExpression(factory.createIdentifier("define"), "amd")), factory.createBlock([
factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("define"),
- /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
- factory.createArrayLiteralExpression(__spreadArrays([
+ /*typeArguments*/ undefined, __spreadArray(__spreadArray([], (moduleName ? [moduleName] : [])), [
+ factory.createArrayLiteralExpression(__spreadArray(__spreadArray([
factory.createStringLiteral("require"),
factory.createStringLiteral("exports")
- ], aliasedModuleNames, unaliasedModuleNames)),
+ ], aliasedModuleNames), unaliasedModuleNames)),
factory.createIdentifier("factory")
])))
])))
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
- /*typeParameters*/ undefined, __spreadArrays([
+ /*typeParameters*/ undefined, __spreadArray([
factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
], importAliasNames),
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
}
function visitImportCallExpression(node) {
- var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
+ var externalModuleName = ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions);
+ var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
+ // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output.
+ var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument;
var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
* @param node The node to substitute.
*/
function substituteExpressionIdentifier(node) {
+ var _a, _b;
if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
if (externalHelpersModuleName) {
}
else if (ts.isImportSpecifier(importDeclaration)) {
var name = importDeclaration.propertyName || importDeclaration.name;
- return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(name)),
+ return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(name)),
/*location*/ node);
}
}
var exportName = exportedNames_3[_i];
// Mark the node to prevent triggering this rule again.
noSubstitution[ts.getNodeId(expression)] = true;
- expression = createExportExpression(exportName, expression);
+ expression = factory.createParenthesizedExpression(createExportExpression(exportName, expression));
}
return expression;
}
// }
// };
// });
+ var externalModuleName = ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions);
+ var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), destructuringAndImportCallVisitor);
+ // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output.
+ var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument;
return factory.createCallExpression(factory.createPropertyAccessExpression(contextObject, factory.createIdentifier("import")),
- /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
+ /*typeArguments*/ undefined, argument ? [argument] : []);
}
/**
* Visits a DestructuringAssignment to flatten destructuring to exported symbols.
* @param node The node to substitute.
*/
function substituteShorthandPropertyAssignment(node) {
+ var _a, _b;
var name = node.name;
if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
var importDeclaration = resolver.getReferencedImportDeclaration(name);
/*location*/ node);
}
else if (ts.isImportSpecifier(importDeclaration)) {
- return ts.setTextRange(factory.createPropertyAssignment(factory.cloneNode(name), factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name))),
+ return ts.setTextRange(factory.createPropertyAssignment(factory.cloneNode(name), factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name))),
/*location*/ node);
}
}
* @param node The node to substitute.
*/
function substituteExpressionIdentifier(node) {
+ var _a, _b;
if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
if (externalHelpersModuleName) {
/*location*/ node);
}
else if (ts.isImportSpecifier(importDeclaration)) {
- return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name)),
+ return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name)),
/*location*/ node);
}
}
if (!ts.isExternalModule(node) || ts.some(result.statements, ts.isExternalModuleIndicator)) {
return result;
}
- return factory.updateSourceFile(result, ts.setTextRange(factory.createNodeArray(__spreadArrays(result.statements, [ts.createEmptyExports(factory)])), result.statements));
+ return factory.updateSourceFile(result, ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], result.statements), [ts.createEmptyExports(factory)])), result.statements));
}
return node;
}
ts.isTypeAliasDeclaration(node) ||
ts.isConstructorDeclaration(node) ||
ts.isIndexSignatureDeclaration(node) ||
- ts.isPropertyAccessExpression(node);
+ ts.isPropertyAccessExpression(node) ||
+ ts.isJSDocTypeAlias(node);
}
ts.canProduceDiagnostics = canProduceDiagnostics;
function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
else if (ts.isImportEqualsDeclaration(node)) {
return getImportEntityNameVisibilityError;
}
- else if (ts.isTypeAliasDeclaration(node)) {
+ else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) {
return getTypeAliasDeclarationVisibilityError;
}
else {
typeName: node.name
};
}
- function getTypeAliasDeclarationVisibilityError() {
+ function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) {
return {
- diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
- errorNode: node.type,
- typeName: node.name
+ diagnosticMessage: symbolAccessibilityResult.errorModuleName
+ ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2
+ : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
+ errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type,
+ typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name,
};
}
}
reportNonlocalAugmentation: reportNonlocalAugmentation
};
var errorNameNode;
+ var errorFallbackNode;
var currentSourceFile;
var refs;
var libs;
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
}
function reportPrivateInBaseOfClassExpression(propertyName) {
- if (errorNameNode) {
- context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
+ if (errorNameNode || errorFallbackNode) {
+ context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
}
}
function reportInaccessibleUniqueSymbolError() {
}
}
function reportTruncationError() {
- if (errorNameNode) {
- context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed));
+ if (errorNameNode || errorFallbackNode) {
+ context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed));
}
}
function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
}
function transformDeclarationsForJS(sourceFile, bundled) {
var oldDiag = getSymbolAccessibilityDiagnostic;
- getSymbolAccessibilityDiagnostic = function (s) { return ({
+ getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({
diagnosticMessage: s.errorModuleName
? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
: ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
errorNode: s.errorNode || sourceFile
- }); };
+ })); };
var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
getSymbolAccessibilityDiagnostic = oldDiag;
return result;
refs.forEach(referenceVisitor);
emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
- combinedStatements = ts.setTextRange(factory.createNodeArray(__spreadArrays(combinedStatements, [ts.createEmptyExports(factory)])), combinedStatements);
+ combinedStatements = ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], combinedStatements), [ts.createEmptyExports(factory)])), combinedStatements);
}
}
var updated = factory.updateSourceFile(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
// Rewrite external module names if necessary
var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
return factory.updateImportEqualsDeclaration(decl,
- /*decorators*/ undefined, decl.modifiers, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
+ /*decorators*/ undefined, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
}
else {
var oldDiag = getSymbolAccessibilityDiagnostic;
return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
}
case 175 /* ConstructorType */: {
- return cleanup(factory.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
+ return cleanup(factory.updateConstructorTypeNode(input, ensureModifiers(input), ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
}
case 195 /* ImportType */: {
if (!ts.isLiteralImportTypeNode(input))
diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
errorNode: input
}); };
+ errorFallbackNode = input;
var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
+ errorFallbackNode = undefined;
var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */));
return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
}
// 3. Some things are exported, some are not, and there's no marker - add an empty marker
if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
if (needsScopeFixMarker) {
- lateStatements = factory.createNodeArray(__spreadArrays(lateStatements, [ts.createEmptyExports(factory)]));
+ lateStatements = factory.createNodeArray(__spreadArray(__spreadArray([], lateStatements), [ts.createEmptyExports(factory)]));
}
else {
lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
}
}
case 252 /* ClassDeclaration */: {
+ errorNameNode = input.name;
+ errorFallbackNode = input;
var modifiers = factory.createNodeArray(ensureModifiers(input));
var typeParameters = ensureTypeParams(input, input.typeParameters);
var ctor = ts.getFirstConstructorWithBody(input);
getSymbolAccessibilityDiagnostic = oldDiag_1;
}
var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
+ // When the class has at least one private identifier, create a unique constant identifier to retain the nominal typing behavior
+ // Prevents other classes with the same public members from being used in place of the current class
var privateIdentifier = hasPrivateIdentifier ? [
factory.createPropertyDeclaration(
/*decorators*/ undefined,
if (node === input) {
return node;
}
+ errorFallbackNode = undefined;
+ errorNameNode = undefined;
return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
}
}
var transformed = [];
for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) {
var node = nodes_3[_a];
- ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end });
transformed.push((allowDtsFiles ? transformation : transformRoot)(node));
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
}
// prevent modification of the lexical environment.
state = 2 /* Completed */;
lexicalEnvironmentFunctionDeclarations ||
lexicalEnvironmentStatements) {
if (lexicalEnvironmentFunctionDeclarations) {
- statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations);
+ statements = __spreadArray([], lexicalEnvironmentFunctionDeclarations);
}
if (lexicalEnvironmentVariableDeclarations) {
var statement = factory.createVariableStatement(
}
if (lexicalEnvironmentStatements) {
if (!statements) {
- statements = __spreadArrays(lexicalEnvironmentStatements);
+ statements = __spreadArray([], lexicalEnvironmentStatements);
}
else {
- statements = __spreadArrays(statements, lexicalEnvironmentStatements);
+ statements = __spreadArray(__spreadArray([], statements), lexicalEnvironmentStatements);
}
}
}
return ".js" /* Js */;
}
ts.getOutputExtension = getOutputExtension;
- function rootDirOfOptions(configFile) {
- return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.checkDefined(configFile.options.configFilePath));
- }
- function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
+ function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir, getCommonSourceDirectory) {
return outputDir ?
- ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
+ ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(getCommonSourceDirectory ? getCommonSourceDirectory() : getCommonSourceDirectoryOfConfig(configFile, ignoreCase), inputFileName, ignoreCase)) :
inputFileName;
}
/* @internal */
- function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
+ function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory) {
ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
- return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
+ return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir, getCommonSourceDirectory), ".d.ts" /* Dts */);
}
ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
- function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
+ function getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory) {
if (configFile.options.emitDeclarationOnly)
return undefined;
var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
- var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
+ var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir, getCommonSourceDirectory), isJsonFile ?
".json" /* Json */ :
- ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
+ configFile.options.jsx === 1 /* Preserve */ && (ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) || ts.fileExtensionIs(inputFileName, ".jsx" /* Jsx */)) ?
".jsx" /* Jsx */ :
".js" /* Js */);
return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
addOutput(declarationMapPath);
addOutput(buildInfoPath);
}
- function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput) {
+ function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory) {
if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
return;
- var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ var js = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
addOutput(js);
if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
return;
addOutput(js + ".map");
}
if (ts.getEmitDeclarations(configFile.options)) {
- var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
+ var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
addOutput(dts);
if (configFile.options.declarationMap) {
addOutput(dts + ".map");
}
}
/*@internal*/
+ function getCommonSourceDirectory(options, emittedFiles, currentDirectory, getCanonicalFileName, checkSourceFilesBelongToPath) {
+ var commonSourceDirectory;
+ if (options.rootDir) {
+ // If a rootDir is specified use it as the commonSourceDirectory
+ commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
+ checkSourceFilesBelongToPath === null || checkSourceFilesBelongToPath === void 0 ? void 0 : checkSourceFilesBelongToPath(options.rootDir);
+ }
+ else if (options.composite && options.configFilePath) {
+ // Project compilations never infer their root from the input source paths
+ commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
+ checkSourceFilesBelongToPath === null || checkSourceFilesBelongToPath === void 0 ? void 0 : checkSourceFilesBelongToPath(commonSourceDirectory);
+ }
+ else {
+ commonSourceDirectory = ts.computeCommonSourceDirectoryOfFilenames(emittedFiles(), currentDirectory, getCanonicalFileName);
+ }
+ if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
+ // Make sure directory path ends with directory separator so this string can directly
+ // used to replace with "" to get the relative path of the source file and the relative path doesn't
+ // start with / making it rooted path
+ commonSourceDirectory += ts.directorySeparator;
+ }
+ return commonSourceDirectory;
+ }
+ ts.getCommonSourceDirectory = getCommonSourceDirectory;
+ /*@internal*/
+ function getCommonSourceDirectoryOfConfig(_a, ignoreCase) {
+ var options = _a.options, fileNames = _a.fileNames;
+ return getCommonSourceDirectory(options, function () { return ts.filter(fileNames, function (file) { return !(options.noEmitForJsFiles && ts.fileExtensionIsOneOf(file, ts.supportedJSExtensions)) && !ts.fileExtensionIs(file, ".d.ts" /* Dts */); }); }, ts.getDirectoryPath(ts.normalizeSlashes(ts.Debug.checkDefined(options.configFilePath))), ts.createGetCanonicalFileName(!ignoreCase));
+ }
+ ts.getCommonSourceDirectoryOfConfig = getCommonSourceDirectoryOfConfig;
+ /*@internal*/
function getAllProjectOutputs(configFile, ignoreCase) {
var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
if (ts.outFile(configFile.options)) {
getSingleOutputFileNames(configFile, addOutput);
}
else {
+ var getCommonSourceDirectory_1 = ts.memoize(function () { return getCommonSourceDirectoryOfConfig(configFile, ignoreCase); });
for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
var inputFileName = _c[_b];
- getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
+ getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory_1);
}
addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
}
var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
}
+ var getCommonSourceDirectory = ts.memoize(function () { return getCommonSourceDirectoryOfConfig(configFile, ignoreCase); });
for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
var inputFileName = _b[_a];
if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
continue;
- var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
if (jsFilePath)
return jsFilePath;
if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
continue;
if (ts.getEmitDeclarations(configFile.options)) {
- return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
+ return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
}
}
var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
};
}
- ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath });
emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
- ts.tracing.pop();
- ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath });
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
- ts.tracing.pop();
- ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath });
emitBuildInfo(bundleBuildInfo, buildInfoPath);
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ // Explicitly do not passthru either `inline` option
});
if (forceDtsEmit && declarationTransform.transformed[0].kind === 297 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
var emitHost = {
- getPrependNodes: ts.memoize(function () { return __spreadArrays(prependNodes, [ownPrependInput]); }),
+ getPrependNodes: ts.memoize(function () { return __spreadArray(__spreadArray([], prependNodes), [ownPrependInput]); }),
getCanonicalFileName: host.getCanonicalFileName,
getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
getCompilerOptions: function () { return config.options; },
useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
getProgramBuildInfo: ts.returnUndefined,
getSourceFileFromReference: ts.returnUndefined,
- redirectTargetsMap: ts.createMultiMap()
+ redirectTargetsMap: ts.createMultiMap(),
+ getFileIncludeReasons: ts.notImplemented,
};
emitFiles(ts.notImplementedResolver, emitHost,
/*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
}
function emitConstructorType(node) {
pushNameGenerationScope(node);
+ emitModifiers(node, node.modifiers);
writeKeyword("new");
writeSpace();
emitTypeParameters(node, node.typeParameters);
if (isSimilarNode && currentSourceFile) {
pos = ts.skipTrivia(currentSourceFile.text, pos);
}
- if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
+ if (isSimilarNode && contextNode.pos !== startPos) {
var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
if (needsIndent) {
increaseIndent();
}
}
pos = writeTokenText(token, writer, pos);
- if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
- emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
+ if (isSimilarNode && contextNode.end !== pos) {
+ var isJsxExprContext = contextNode.kind === 283 /* JsxExpression */;
+ emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ !isJsxExprContext, /*forceNoNewline*/ isJsxExprContext);
}
return pos;
}
emitModifiers(node, node.modifiers);
emitTokenWithComment(99 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
writeSpace();
+ if (node.isTypeOnly) {
+ emitTokenWithComment(149 /* TypeKeyword */, node.pos, writeKeyword, node);
+ writeSpace();
+ }
emit(node.name);
writeSpace();
emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
emitExpression(node.expression);
writePunctuation("}");
}
+ function hasTrailingCommentsAtPosition(pos) {
+ var result = false;
+ ts.forEachTrailingCommentRange((currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.text) || "", pos + 1, function () { return result = true; });
+ return result;
+ }
+ function hasLeadingCommentsAtPosition(pos) {
+ var result = false;
+ ts.forEachLeadingCommentRange((currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.text) || "", pos + 1, function () { return result = true; });
+ return result;
+ }
+ function hasCommentsAtPosition(pos) {
+ return hasTrailingCommentsAtPosition(pos) || hasLeadingCommentsAtPosition(pos);
+ }
function emitJsxExpression(node) {
- if (node.expression) {
- writePunctuation("{");
+ var _a;
+ if (node.expression || (!commentsDisabled && !ts.nodeIsSynthesized(node) && hasCommentsAtPosition(node.pos))) { // preserve empty expressions if they contain comments!
+ var isMultiline = currentSourceFile && !ts.nodeIsSynthesized(node) && ts.getLineAndCharacterOfPosition(currentSourceFile, node.pos).line !== ts.getLineAndCharacterOfPosition(currentSourceFile, node.end).line;
+ if (isMultiline) {
+ writer.increaseIndent();
+ }
+ var end = emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
emit(node.dotDotDotToken);
emitExpression(node.expression);
- writePunctuation("}");
+ emitTokenWithComment(19 /* CloseBraceToken */, ((_a = node.expression) === null || _a === void 0 ? void 0 : _a.end) || end, writePunctuation, node);
+ if (isMultiline) {
+ writer.decreaseIndent();
+ }
}
}
function emitJsxTagName(node) {
// "comment1" is not considered to be leading comment for node.initializer
// but rather a trailing comment on the previous node.
var initializer = node.initializer;
- if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
+ if ((ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
var commentRange = ts.getCommentRange(initializer);
emitTrailingCommentsOfPosition(commentRange.pos);
}
bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
- for (var _d = 0, types_23 = types; _d < types_23.length; _d++) {
- var directive = types_23[_d];
+ for (var _d = 0, types_25 = types; _d < types_25.length; _d++) {
+ var directive = types_25[_d];
var pos = writer.getTextPos();
writeComment("/// <reference types=\"" + directive.fileName + "\" />");
if (bundleFileInfo)
previousSibling = child;
}
// Write a trailing comma, if requested.
- var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
- if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
- writePunctuation(",");
+ var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0;
+ var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* NoTrailingComments */);
+ var hasTrailingComma = (children === null || children === void 0 ? void 0 : children.hasTrailingComma) && (format & 64 /* AllowTrailingComma */) && (format & 16 /* CommaDelimited */);
+ if (hasTrailingComma) {
+ if (previousSibling && !skipTrailingComments) {
+ emitTokenWithComment(27 /* CommaToken */, previousSibling.end, writePunctuation, previousSibling);
+ }
+ else {
+ writePunctuation(",");
+ }
}
// Emit any trailing comment of the last element in the list
// i.e
// 2
// /* end of element 2 */
// ];
- if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
- emitLeadingCommentsOfPosition(previousSibling.end);
+ if (previousSibling && parentNode.end !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) {
+ emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end);
}
// Decrease the indent, if requested.
if (format & 128 /* Indented */) {
}
if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) {
if (preserveSourceNewlines) {
- var end_2 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end;
- return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_2, parentNode.end, currentSourceFile, includeComments); });
+ var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end;
+ return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); });
}
return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1;
}
}
var flags = (neverAsciiEscape ? 1 /* NeverAsciiEscape */ : 0)
| (jsxAttributeEscape ? 2 /* JsxAttributeEscape */ : 0)
- | (printerOptions.terminateUnterminatedLiterals ? 4 /* TerminateUnterminatedLiterals */ : 0);
+ | (printerOptions.terminateUnterminatedLiterals ? 4 /* TerminateUnterminatedLiterals */ : 0)
+ | (printerOptions.target && printerOptions.target === 99 /* ESNext */ ? 8 /* AllowNumericSeparator */ : 0);
return ts.getLiteralText(node, currentSourceFile, flags);
}
/**
writer.writeLine();
}
}
- function emitTrailingCommentsOfPosition(pos, prefixSpace) {
+ function emitTrailingCommentsOfPosition(pos, prefixSpace, forceNoNewline) {
if (commentsDisabled) {
return;
}
enterComment();
- forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
+ forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : forceNoNewline ? emitTrailingCommentOfPositionNoNewline : emitTrailingCommentOfPosition);
exitComment();
}
+ function emitTrailingCommentOfPositionNoNewline(commentPos, commentEnd, kind) {
+ // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
+ emitPos(commentPos);
+ ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
+ emitPos(commentEnd);
+ if (kind === 2 /* SingleLineCommentTrivia */) {
+ writer.writeLine(); // still write a newline for single-line comments, so closing tokens aren't written on the same line
+ }
+ }
function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
// trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
emitPos(commentPos);
/** Reload completely by re-reading contents of config file from disk and updating program */
ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
})(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
+ /**
+ * Updates the map of shared extended config file watches with a new set of extended config files from a base config file of the project
+ */
+ function updateSharedExtendedConfigFileWatcher(projectPath, parsed, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) {
+ var _a;
+ var extendedConfigs = ts.arrayToMap(((_a = parsed === null || parsed === void 0 ? void 0 : parsed.options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath);
+ // remove project from all unrelated watchers
+ extendedConfigFilesMap.forEach(function (watcher, extendedConfigFilePath) {
+ if (!extendedConfigs.has(extendedConfigFilePath)) {
+ watcher.projects.delete(projectPath);
+ watcher.close();
+ }
+ });
+ // Update the extended config files watcher
+ extendedConfigs.forEach(function (extendedConfigFileName, extendedConfigFilePath) {
+ var existing = extendedConfigFilesMap.get(extendedConfigFilePath);
+ if (existing) {
+ existing.projects.add(projectPath);
+ }
+ else {
+ // start watching previously unseen extended config
+ extendedConfigFilesMap.set(extendedConfigFilePath, {
+ projects: new ts.Set([projectPath]),
+ fileWatcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath),
+ close: function () {
+ var existing = extendedConfigFilesMap.get(extendedConfigFilePath);
+ if (!existing || existing.projects.size !== 0)
+ return;
+ existing.fileWatcher.close();
+ extendedConfigFilesMap.delete(extendedConfigFilePath);
+ },
+ });
+ }
+ });
+ }
+ ts.updateSharedExtendedConfigFileWatcher = updateSharedExtendedConfigFileWatcher;
/**
* Updates the existing missing file watches with the new set of missing files after new program is created
*/
ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
/* @internal */
function isIgnoredFileFromWildCardWatching(_a) {
- var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, configFileSpecs = _a.configFileSpecs, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog;
+ var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog;
var newPath = ts.removeIgnoredPath(fileOrDirectoryPath);
if (!newPath) {
writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory);
writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
return true;
}
- if (ts.isExcludedFile(fileOrDirectory, configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) {
+ if (ts.isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) {
writeLog("Project: " + configFileName + " Detected excluded file: " + fileOrDirectory);
return true;
}
WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
})(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
- function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
- return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
- }
- ts.getWatchFactory = getWatchFactory;
- function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
- var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
- var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
- var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
- if (watchLogLevel === WatchLogLevel.Verbose && ts.sysLog === ts.noop) {
- ts.setSysLog(function (s) { return log(s); });
- }
- return {
- watchFile: function (host, file, callback, pollingInterval, options, detailInfo1, detailInfo2) {
- return createFileWatcher(host, file, callback, pollingInterval, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
- },
- watchFilePath: function (host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2) {
- return createFilePathWatcher(host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
- },
- watchDirectory: function (host, directory, callback, flags, options, detailInfo1, detailInfo2) {
- return createDirectoryWatcher(host, directory, callback, flags, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
- }
+ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo) {
+ ts.setSysLog(watchLogLevel === WatchLogLevel.Verbose ? log : ts.noop);
+ var plainInvokeFactory = {
+ watchFile: function (file, callback, pollingInterval, options) { return host.watchFile(file, callback, pollingInterval, options); },
+ watchDirectory: function (directory, callback, flags, options) { return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options); },
};
- }
- function watchFile(host, file, callback, pollingInterval, options) {
- return host.watchFile(file, callback, pollingInterval, options);
- }
- function watchFilePath(host, file, callback, pollingInterval, options, path) {
- return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options);
- }
- function watchDirectory(host, directory, callback, flags, options) {
- return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options);
- }
- function getCreateFileWatcher(watchLogLevel, addWatch) {
- switch (watchLogLevel) {
- case WatchLogLevel.None:
- return addWatch;
- case WatchLogLevel.TriggerOnly:
- return createFileWatcherWithTriggerLogging;
- case WatchLogLevel.Verbose:
- return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
- }
- }
- function createFileWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
- log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
- var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
- return {
- close: function () {
- log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
- watcher.close();
- }
- };
- }
- function createDirectoryWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
- var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
- log(watchInfo);
- var start = ts.timestamp();
- var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
- var elapsed = ts.timestamp() - start;
- log("Elapsed:: " + elapsed + "ms " + watchInfo);
+ var triggerInvokingFactory = watchLogLevel !== WatchLogLevel.None ?
+ {
+ watchFile: createTriggerLoggingAddWatch("watchFile"),
+ watchDirectory: createTriggerLoggingAddWatch("watchDirectory")
+ } :
+ undefined;
+ var factory = watchLogLevel === WatchLogLevel.Verbose ?
+ {
+ watchFile: createFileWatcherWithLogging,
+ watchDirectory: createDirectoryWatcherWithLogging
+ } :
+ triggerInvokingFactory || plainInvokeFactory;
+ var excludeWatcherFactory = watchLogLevel === WatchLogLevel.Verbose ?
+ createExcludeWatcherWithLogging :
+ ts.returnNoopFileWatcher;
return {
- close: function () {
- var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
- log(watchInfo);
- var start = ts.timestamp();
- watcher.close();
- var elapsed = ts.timestamp() - start;
- log("Elapsed:: " + elapsed + "ms " + watchInfo);
- }
+ watchFile: createExcludeHandlingAddWatch("watchFile"),
+ watchDirectory: createExcludeHandlingAddWatch("watchDirectory")
};
- }
- function createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
- return addWatch(host, file, function (fileName, cbOptional) {
- var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
- log(triggerredInfo);
+ function createExcludeHandlingAddWatch(key) {
+ return function (file, cb, flags, options, detailInfo1, detailInfo2) {
+ var _a;
+ return !ts.matchesExclude(file, key === "watchFile" ? options === null || options === void 0 ? void 0 : options.excludeFiles : options === null || options === void 0 ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames(), ((_a = host.getCurrentDirectory) === null || _a === void 0 ? void 0 : _a.call(host)) || "") ?
+ factory[key].call(/*thisArgs*/ undefined, file, cb, flags, options, detailInfo1, detailInfo2) :
+ excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2);
+ };
+ }
+ function useCaseSensitiveFileNames() {
+ return typeof host.useCaseSensitiveFileNames === "boolean" ?
+ host.useCaseSensitiveFileNames :
+ host.useCaseSensitiveFileNames();
+ }
+ function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) {
+ log("ExcludeWatcher:: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
+ return {
+ close: function () { return log("ExcludeWatcher:: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)); }
+ };
+ }
+ function createFileWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) {
+ log("FileWatcher:: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
+ var watcher = triggerInvokingFactory.watchFile(file, cb, flags, options, detailInfo1, detailInfo2);
+ return {
+ close: function () {
+ log("FileWatcher:: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
+ watcher.close();
+ }
+ };
+ }
+ function createDirectoryWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) {
+ var watchInfo = "DirectoryWatcher:: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
+ log(watchInfo);
var start = ts.timestamp();
- cb(fileName, cbOptional, passThrough);
+ var watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2);
var elapsed = ts.timestamp() - start;
- log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
- }, flags, options);
+ log("Elapsed:: " + elapsed + "ms " + watchInfo);
+ return {
+ close: function () {
+ var watchInfo = "DirectoryWatcher:: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
+ log(watchInfo);
+ var start = ts.timestamp();
+ watcher.close();
+ var elapsed = ts.timestamp() - start;
+ log("Elapsed:: " + elapsed + "ms " + watchInfo);
+ }
+ };
+ }
+ function createTriggerLoggingAddWatch(key) {
+ return function (file, cb, flags, options, detailInfo1, detailInfo2) { return plainInvokeFactory[key].call(/*thisArgs*/ undefined, file, function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var triggerredInfo = (key === "watchFile" ? "FileWatcher" : "DirectoryWatcher") + ":: Triggered with " + args[0] + " " + (args[1] !== undefined ? args[1] : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
+ log(triggerredInfo);
+ var start = ts.timestamp();
+ cb.call.apply(cb, __spreadArray([/*thisArg*/ undefined], args));
+ var elapsed = ts.timestamp() - start;
+ log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
+ }, flags, options, detailInfo1, detailInfo2); };
+ }
+ function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
+ return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
+ }
}
+ ts.getWatchFactory = getWatchFactory;
function getFallbackOptions(options) {
var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
return {
};
}
ts.getFallbackOptions = getFallbackOptions;
- function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
- return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
- }
function closeFileWatcherOf(objWithWatcher) {
objWithWatcher.watcher.close();
}
var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
var lineContent = file.text.slice(lineStart, lineEnd);
lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
- lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
+ lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces
// Output the gutter and the actual contents of the line.
context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
context += lineContent + host.getNewLine();
if (diagnostic.file) {
output += host.getNewLine();
output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
- if (diagnostic.relatedInformation) {
- output += host.getNewLine();
- for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
- var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText;
- if (file) {
- output += host.getNewLine();
- output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
- output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
- }
+ }
+ if (diagnostic.relatedInformation) {
+ output += host.getNewLine();
+ for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
+ var _c = _b[_a], file = _c.file, start = _c.start, length_9 = _c.length, messageText = _c.messageText;
+ if (file) {
output += host.getNewLine();
- output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
+ output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
+ output += formatCodeSpan(file, start, length_9, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
}
+ output += host.getNewLine();
+ output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
}
}
output += host.getNewLine();
}
/* @internal */
ts.inferredTypesContainingFile = "__inferred type names__.ts";
+ /*@internal*/
+ function isReferencedFile(reason) {
+ switch (reason === null || reason === void 0 ? void 0 : reason.kind) {
+ case ts.FileIncludeKind.Import:
+ case ts.FileIncludeKind.ReferenceFile:
+ case ts.FileIncludeKind.TypeReferenceDirective:
+ case ts.FileIncludeKind.LibReferenceDirective:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isReferencedFile = isReferencedFile;
+ /*@internal*/
+ function isReferenceFileLocation(location) {
+ return location.pos !== undefined;
+ }
+ ts.isReferenceFileLocation = isReferenceFileLocation;
+ /*@internal*/
+ function getReferencedFileLocation(getSourceFileByPath, ref) {
+ var _a, _b, _c;
+ var _d, _e, _f, _g;
+ var file = ts.Debug.checkDefined(getSourceFileByPath(ref.file));
+ var kind = ref.kind, index = ref.index;
+ var pos, end, packageId;
+ switch (kind) {
+ case ts.FileIncludeKind.Import:
+ var importLiteral = getModuleNameStringLiteralAt(file, index);
+ packageId = (_e = (_d = file.resolvedModules) === null || _d === void 0 ? void 0 : _d.get(importLiteral.text)) === null || _e === void 0 ? void 0 : _e.packageId;
+ if (importLiteral.pos === -1)
+ return { file: file, packageId: packageId, text: importLiteral.text };
+ pos = ts.skipTrivia(file.text, importLiteral.pos);
+ end = importLiteral.end;
+ break;
+ case ts.FileIncludeKind.ReferenceFile:
+ (_a = file.referencedFiles[index], pos = _a.pos, end = _a.end);
+ break;
+ case ts.FileIncludeKind.TypeReferenceDirective:
+ (_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
+ packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName))) === null || _g === void 0 ? void 0 : _g.packageId;
+ break;
+ case ts.FileIncludeKind.LibReferenceDirective:
+ (_c = file.libReferenceDirectives[index], pos = _c.pos, end = _c.end);
+ break;
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ return { file: file, pos: pos, end: end, packageId: packageId };
+ }
+ ts.getReferencedFileLocation = getReferencedFileLocation;
/**
* Determines if program structure is upto date or needs to be recreated
*/
}
ts.isProgramUptoDate = isProgramUptoDate;
function getConfigFileParsingDiagnostics(configFileParseResult) {
- return configFileParseResult.options.configFile ? __spreadArrays(configFileParseResult.options.configFile.parseDiagnostics, configFileParseResult.errors) :
+ return configFileParseResult.options.configFile ? __spreadArray(__spreadArray([], configFileParseResult.options.configFile.parseDiagnostics), configFileParseResult.errors) :
configFileParseResult.errors;
}
ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
};
}
function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
- var _a, _b;
+ var _a, _b, _c;
var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
var oldProgram = createProgramOptions.oldProgram;
var noDiagnosticsTypeChecker;
var classifiableNames;
var ambientModuleNameToUnmodifiedFileName = new ts.Map();
- // Todo:: Use this to report why file was included in --extendedDiagnostics
- var refFileMap;
+ var fileReasons = ts.createMultiMap();
var cachedBindAndCheckDiagnosticsForFile = {};
var cachedDeclarationDiagnosticsForFile = {};
var resolvedTypeReferenceDirectives = new ts.Map();
- var fileProcessingDiagnostics = ts.createDiagnosticCollection();
+ var fileProcessingDiagnostics;
// The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
// This works as imported modules are discovered recursively in a depth first manner, specifically:
// - For each root file, findSourceFile is called.
var modulesWithElidedImports = new ts.Map();
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
var sourceFilesFoundSearchingNodeModules = new ts.Map();
- var tracingData = ["program" /* Program */, "createProgram"];
- ts.tracing.begin.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true);
ts.performance.mark("beforeProgram");
var host = createProgramOptions.host || createCompilerHost(options);
var configParsingHost = parseConfigHostFromCompilerHostLike(host);
var mapFromToProjectReferenceRedirectSource;
var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) &&
!options.disableSourceOfProjectReferenceRedirect;
- var _c = updateHostForUseSourceOfProjectReferenceRedirect({
+ var _d = updateHostForUseSourceOfProjectReferenceRedirect({
compilerHost: host,
getSymlinkCache: getSymlinkCache,
useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
getResolvedProjectReferences: getResolvedProjectReferences,
getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
forEachResolvedProjectReference: forEachResolvedProjectReference
- }), onProgramCreateComplete = _c.onProgramCreateComplete, fileExists = _c.fileExists, directoryExists = _c.directoryExists;
- ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram });
+ }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists;
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram });
var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
// We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
// `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
var structureIsReused;
- ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {});
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {});
structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
if (structureIsReused !== 2 /* Completely */) {
processingDefaultLibFiles = [];
processingOtherFiles = [];
resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
}
if (rootNames.length) {
- for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
- var parsedRef = resolvedProjectReferences_1[_i];
+ resolvedProjectReferences === null || resolvedProjectReferences === void 0 ? void 0 : resolvedProjectReferences.forEach(function (parsedRef, index) {
if (!parsedRef)
- continue;
+ return;
var out = ts.outFile(parsedRef.commandLine.options);
if (useSourceOfProjectReferenceRedirect) {
if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
- for (var _d = 0, _e = parsedRef.commandLine.fileNames; _d < _e.length; _d++) {
- var fileName = _e[_d];
- processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ for (var _i = 0, _a = parsedRef.commandLine.fileNames; _i < _a.length; _i++) {
+ var fileName = _a[_i];
+ processProjectReferenceFile(fileName, { kind: ts.FileIncludeKind.SourceFromProjectReference, index: index });
}
}
}
else {
if (out) {
- processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ processProjectReferenceFile(ts.changeExtension(out, ".d.ts"), { kind: ts.FileIncludeKind.OutputFromProjectReference, index: index });
}
else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
- for (var _f = 0, _g = parsedRef.commandLine.fileNames; _f < _g.length; _f++) {
- var fileName = _g[_f];
+ var getCommonSourceDirectory_2 = ts.memoize(function () { return ts.getCommonSourceDirectoryOfConfig(parsedRef.commandLine, !host.useCaseSensitiveFileNames()); });
+ for (var _b = 0, _c = parsedRef.commandLine.fileNames; _b < _c.length; _b++) {
+ var fileName = _c[_b];
if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
- processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ processProjectReferenceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory_2), { kind: ts.FileIncludeKind.OutputFromProjectReference, index: index });
}
}
}
}
- }
+ });
}
}
- ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length });
- ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length });
+ ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
// load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
if (typeReferences.length) {
- ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length });
// This containingFilename needs to match with the one used in managed-side
var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
for (var i = 0; i < typeReferences.length; i++) {
- processTypeReferenceDirective(typeReferences[i], resolutions[i]);
+ processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId });
}
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
}
// Do not process the default library if:
// - The '--noLib' flag is used.
// otherwise, using options specified in '--lib' instead of '--target' default library file
var defaultLibraryFileName = getDefaultLibraryFileName();
if (!options.lib && defaultLibraryFileName) {
- processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
+ processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.LibFile });
}
else {
- ts.forEach(options.lib, function (libFileName) {
- processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
+ ts.forEach(options.lib, function (libFileName, index) {
+ processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.LibFile, index: index });
});
}
}
// not part of the new program.
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _h = 0, oldSourceFiles_1 = oldSourceFiles; _h < oldSourceFiles_1.length; _h++) {
- var oldSourceFile = oldSourceFiles_1[_h];
+ for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) {
+ var oldSourceFile = oldSourceFiles_1[_i];
var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
if (shouldCreateNewSourceFile || !newFile ||
- // old file wasnt redirect but new file is
+ // old file wasn't redirect but new file is
(oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
}
getSourceFileByPath: getSourceFileByPath,
getSourceFiles: function () { return files; },
getMissingFilePaths: function () { return missingFilePaths; },
- getRefFileMap: function () { return refFileMap; },
getFilesByNameMap: function () { return filesByName; },
getCompilerOptions: function () { return options; },
getSyntacticDiagnostics: getSyntacticDiagnostics,
fileExists: fileExists,
directoryExists: directoryExists,
getSymlinkCache: getSymlinkCache,
- realpath: (_b = host.realpath) === null || _b === void 0 ? void 0 : _b.bind(host),
+ realpath: (_c = host.realpath) === null || _c === void 0 ? void 0 : _c.bind(host),
useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getFileIncludeReasons: function () { return fileReasons; },
structureIsReused: structureIsReused,
};
onProgramCreateComplete();
+ // Add file processingDiagnostics
+ fileProcessingDiagnostics === null || fileProcessingDiagnostics === void 0 ? void 0 : fileProcessingDiagnostics.forEach(function (diagnostic) {
+ switch (diagnostic.kind) {
+ case 1 /* FilePreprocessingFileExplainingDiagnostic */:
+ return programDiagnostics.add(createDiagnosticExplainingFile(diagnostic.file && getSourceFileByPath(diagnostic.file), diagnostic.fileProcessingReason, diagnostic.diagnostic, diagnostic.args || ts.emptyArray));
+ case 0 /* FilePreprocessingReferencedDiagnostic */:
+ var _a = getReferencedFileLocation(getSourceFileByPath, diagnostic.reason), file = _a.file, pos = _a.pos, end = _a.end;
+ return programDiagnostics.add(ts.createFileDiagnostic.apply(void 0, __spreadArray([file, ts.Debug.checkDefined(pos), ts.Debug.checkDefined(end) - pos, diagnostic.diagnostic], diagnostic.args || ts.emptyArray)));
+ default:
+ ts.Debug.assertNever(diagnostic);
+ }
+ });
verifyCompilerOptions();
ts.performance.mark("afterProgram");
ts.performance.measure("Program", "beforeProgram", "afterProgram");
- ts.tracing.end.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
return program;
function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) {
if (!moduleNames.length)
return ts.emptyArray;
var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory);
var redirectedReference = getRedirectReferenceForResolution(containingFile);
- ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName });
ts.performance.mark("beforeResolveModule");
var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference);
ts.performance.mark("afterResolveModule");
ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
return result;
}
function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) {
return [];
var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile;
var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined;
- ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName });
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName });
ts.performance.mark("beforeResolveTypeReference");
var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference);
ts.performance.mark("afterResolveTypeReference");
ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
- ts.tracing.pop();
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
return result;
}
function getRedirectReferenceForResolution(file) {
}
function getCommonSourceDirectory() {
if (commonSourceDirectory === undefined) {
- var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
- if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
- // If a rootDir is specified use it as the commonSourceDirectory
- commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
- }
- else if (options.composite && options.configFilePath) {
- // Project compilations never infer their root from the input source paths
- commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
- checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
- }
- else {
- commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
- }
- if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
- // Make sure directory path ends with directory separator so this string can directly
- // used to replace with "" to get the relative path of the source file and the relative path doesn't
- // start with / making it rooted path
- commonSourceDirectory += ts.directorySeparator;
- }
+ var emittedFiles_1 = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
+ commonSourceDirectory = ts.getCommonSourceDirectory(options, function () { return ts.mapDefined(emittedFiles_1, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); }, currentDirectory, getCanonicalFileName, function (commonSourceDirectory) { return checkSourceFilesBelongToPath(emittedFiles_1, commonSourceDirectory); });
}
return commonSourceDirectory;
}
return 1 /* SafeModules */;
}
missingFilePaths = oldProgram.getMissingFilePaths();
- refFileMap = oldProgram.getRefFileMap();
// update fileName -> file mapping
ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) {
filesByName.set(path, filesByName.get(oldFile.path));
});
files = newSourceFiles;
+ fileReasons = oldProgram.getFileIncludeReasons();
fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
- for (var _h = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _h < modifiedSourceFiles_2.length; _h++) {
- var modifiedFile = modifiedSourceFiles_2[_h];
- fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
- }
resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
sourceFileToPackageName = oldProgram.sourceFileToPackageName;
redirectTargetsMap = oldProgram.redirectTargetsMap;
getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
redirectTargetsMap: redirectTargetsMap,
+ getFileIncludeReasons: program.getFileIncludeReasons,
};
}
function emitBuildInfo(writeFileCallback) {
ts.Debug.assert(!ts.outFile(options));
- var tracingData = ["emit" /* Emit */, "emitBuildInfo"];
- ts.tracing.begin.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true);
ts.performance.mark("beforeEmit");
var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
/*targetSourceFile*/ undefined,
/*onlyBuildInfo*/ true);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
- ts.tracing.end.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
return emitResult;
}
function getResolvedProjectReferences() {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
- var tracingData = ["emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }];
- ts.tracing.begin.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true);
var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
- ts.tracing.end.apply(ts.tracing, tracingData);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
return result;
}
function isEmitBlocked(emitFileName) {
function getCachedSemanticDiagnostics(sourceFile) {
var _a;
return sourceFile
- ? (_a = cachedBindAndCheckDiagnosticsForFile.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path) : cachedBindAndCheckDiagnosticsForFile.allDiagnostics;
+ ? (_a = cachedBindAndCheckDiagnosticsForFile.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path)
+ : cachedBindAndCheckDiagnosticsForFile.allDiagnostics;
}
function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
}
function getProgramDiagnostics(sourceFile) {
+ var _a;
if (ts.skipTypeChecking(sourceFile, options, program)) {
return ts.emptyArray;
}
- var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
- return getMergedProgramDiagnostics(sourceFile, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
- }
- function getMergedProgramDiagnostics(sourceFile) {
- var _a;
- var allDiagnostics = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- allDiagnostics[_i - 1] = arguments[_i];
- }
- var flatDiagnostics = ts.flatten(allDiagnostics);
if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
- return flatDiagnostics;
+ return programDiagnosticsInFile;
}
- return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics).diagnostics;
+ return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, programDiagnosticsInFile).diagnostics;
}
function getDeclarationDiagnostics(sourceFile, cancellationToken) {
var options = program.getCompilerOptions();
function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
var _a;
var cachedResult = sourceFile
- ? (_a = cache.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path) : cache.allDiagnostics;
+ ? (_a = cache.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path)
+ : cache.allDiagnostics;
if (cachedResult) {
return cachedResult;
}
return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
}
function getOptionsDiagnostics() {
- return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
+ return ts.sortAndDeduplicateDiagnostics(ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()));
}
function getOptionsDiagnosticsOfConfigFile() {
if (!options.configFile) {
function getConfigFileParsingDiagnostics() {
return configFileParsingDiagnostics || ts.emptyArray;
}
- function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
- processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
+ function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason) {
+ processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined, reason);
}
function fileReferenceIsEqualTo(a, b) {
return a.fileName === b.fileName;
}
/** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
function getSourceFileFromReference(referencingFile, ref) {
- return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
+ return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), getSourceFile);
}
- function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
+ function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, reason) {
if (ts.hasExtension(fileName)) {
var canonicalFileName_1 = host.getCanonicalFileName(fileName);
if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
fail(ts.Diagnostics.File_0_not_found, fileName);
}
}
- else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) {
+ else if (isReferencedFile(reason) && canonicalFileName_1 === host.getCanonicalFileName(getSourceFileByPath(reason.file).fileName)) {
fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
}
}
}
}
/** This has side effects through `findSourceFile`. */
- function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile) {
- getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, packageId); }, // TODO: GH#18217
+ function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, reason) {
+ getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, reason, packageId); }, // TODO: GH#18217
function (diagnostic) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
- return fileProcessingDiagnostics.add(createRefFileDiagnostic.apply(void 0, __spreadArrays([refFile, diagnostic], args)));
- }, refFile && refFile.file);
+ return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, diagnostic, args);
+ }, reason);
+ }
+ function processProjectReferenceFile(fileName, reason) {
+ return processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, reason);
}
- function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile) {
- var refs = !refFile ? refFileMap && refFileMap.get(existingFile.path) : undefined;
- var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile.fileName; });
- fileProcessingDiagnostics.add(refToReportErrorOn ?
- createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, existingFile.fileName, fileName) :
- createRefFileDiagnostic(refFile, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFile.fileName));
+ function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, reason) {
+ var hasExistingReasonToReportErrorOn = !isReferencedFile(reason) && ts.some(fileReasons.get(existingFile.path), isReferencedFile);
+ if (hasExistingReasonToReportErrorOn) {
+ addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, [existingFile.fileName, fileName]);
+ }
+ else {
+ addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]);
+ }
}
function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
var redirect = Object.create(redirectTarget);
return redirect;
}
// Get source file from normalized fileName
- function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
- ts.tracing.push("program" /* Program */, "findSourceFile", {
+ function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) {
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", {
fileName: fileName,
isDefaultLib: isDefaultLib || undefined,
- refKind: refFile ? ts.RefFileKind[refFile.kind] : undefined,
+ fileIncludeKind: ts.FileIncludeKind[reason.kind],
});
- var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId);
- ts.tracing.pop();
+ var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
return result;
}
- function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
+ function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) {
if (useSourceOfProjectReferenceRedirect) {
var source = getSourceOfProjectReferenceRedirect(fileName);
// If preserveSymlinks is true, module resolution wont jump the symlink
}
if (source) {
var file_1 = ts.isString(source) ?
- findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
+ findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, reason, packageId) :
undefined;
if (file_1)
addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
var originalFileName = fileName;
if (filesByName.has(path)) {
var file_2 = filesByName.get(path);
- addFileToRefFileMap(fileName, file_2 || undefined, refFile);
+ addFileIncludeReason(file_2 || undefined, reason);
// try to check if we've already seen this file but with a different casing in path
// NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
if (file_2 && options.forceConsistentCasingInFileNames) {
var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
if (checkedAbsolutePath !== inputAbsolutePath) {
- reportFileNamesDifferOnlyInCasingError(fileName, file_2, refFile);
+ reportFileNamesDifferOnlyInCasingError(fileName, file_2, reason);
}
}
// If the file was previously found via a node_modules search, but is now being processed as a root file,
return file_2 || undefined;
}
var redirectedPath;
- if (refFile && !useSourceOfProjectReferenceRedirect) {
+ if (isReferencedFile(reason) && !useSourceOfProjectReferenceRedirect) {
var redirectProject = getProjectReferenceRedirectProject(fileName);
if (redirectProject) {
if (ts.outFile(redirectProject.commandLine.options)) {
}
}
// We haven't looked for this file, do so now and cache result
- 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);
+ var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile);
if (packageId) {
var packageIdKey = ts.packageIdToString(packageId);
var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
redirectTargetsMap.add(fileFromPackageId.path, fileName);
addFileToFilesByName(dupFile, path, redirectedPath);
+ addFileIncludeReason(dupFile, reason);
sourceFileToPackageName.set(path, packageId.name);
processingOtherFiles.push(dupFile);
return dupFile;
file.path = path;
file.resolvedPath = toPath(fileName);
file.originalFileName = originalFileName;
- addFileToRefFileMap(fileName, file, refFile);
+ addFileIncludeReason(file, reason);
if (host.useCaseSensitiveFileNames()) {
var pathLowerCase = ts.toFileNameLowerCase(path);
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
if (existingFile) {
- reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile);
+ reportFileNamesDifferOnlyInCasingError(fileName, existingFile, reason);
}
else {
filesByNameIgnoreCase.set(pathLowerCase, file);
}
return file;
}
- function addFileToRefFileMap(referencedFileName, file, refFile) {
- if (refFile && file) {
- (refFileMap || (refFileMap = ts.createMultiMap())).add(file.path, {
- referencedFileName: referencedFileName,
- kind: refFile.kind,
- index: refFile.index,
- file: refFile.file.path
- });
- }
+ function addFileIncludeReason(file, reason) {
+ if (file)
+ fileReasons.add(file.path, reason);
}
function addFileToFilesByName(file, path, redirectedPath) {
if (redirectedPath) {
mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
}
else {
+ var getCommonSourceDirectory_3 = ts.memoize(function () { return ts.getCommonSourceDirectoryOfConfig(resolvedRef.commandLine, !host.useCaseSensitiveFileNames()); });
ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
- var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
+ var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory_3);
mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
}
});
}
function processReferencedFiles(file, isDefaultLib) {
ts.forEach(file.referencedFiles, function (ref, index) {
- var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
- processSourceFile(referencedFileName, isDefaultLib,
+ processSourceFile(resolveTripleslashReference(ref.fileName, file.fileName), isDefaultLib,
/*ignoreNoDefaultLib*/ false,
- /*packageId*/ undefined, {
- kind: ts.RefFileKind.ReferenceFile,
- index: index,
- file: file,
- pos: ref.pos,
- end: ref.end
- });
+ /*packageId*/ undefined, { kind: ts.FileIncludeKind.ReferenceFile, file: file.path, index: index, });
});
}
function processTypeReferenceDirectives(file) {
return;
}
var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file);
- for (var i = 0; i < typeDirectives.length; i++) {
- var ref = file.typeReferenceDirectives[i];
- var resolvedTypeReferenceDirective = resolutions[i];
+ for (var index = 0; index < typeDirectives.length; index++) {
+ var ref = file.typeReferenceDirectives[index];
+ var resolvedTypeReferenceDirective = resolutions[index];
// store resolved type directive on the file
var fileName = ts.toFileNameLowerCase(ref.fileName);
ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
- processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, {
- kind: ts.RefFileKind.TypeReferenceDirective,
- index: i,
- file: file,
- pos: ref.pos,
- end: ref.end
- });
+ processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, { kind: ts.FileIncludeKind.TypeReferenceDirective, file: file.path, index: index, });
}
}
- function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
- ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: refFile === null || refFile === void 0 ? void 0 : refFile.kind, refPath: refFile === null || refFile === void 0 ? void 0 : refFile.file.path });
- processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, refFile);
- ts.tracing.pop();
+ function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) {
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined });
+ processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason);
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
}
- function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
+ function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) {
// If we already found this library as a primary reference - nothing to do
var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
if (previousResolution && previousResolution.primary) {
currentNodeModulesDepth++;
if (resolvedTypeReferenceDirective.primary) {
// resolved from the primary path
- processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile); // TODO: GH#18217
+ processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, reason); // TODO: GH#18217
}
else {
// If we already resolved to this file, it must have been a secondary reference. Check file contents
// Don't bother reading the file again if it's the same file.
if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
- var existingFile_1 = getSourceFile(previousResolution.resolvedFileName);
- if (otherFileText !== existingFile_1.text) {
- // Try looking up ref for original file
- var refs = !refFile ? refFileMap && refFileMap.get(existingFile_1.path) : undefined;
- var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile_1.fileName; });
- fileProcessingDiagnostics.add(refToReportErrorOn ?
- 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) :
- 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));
+ var existingFile = getSourceFile(previousResolution.resolvedFileName);
+ if (otherFileText !== existingFile.text) {
+ addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, [typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName]);
}
}
// don't overwrite previous resolution result
}
else {
// First resolution of this library
- processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile);
+ processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, reason);
}
}
if (resolvedTypeReferenceDirective.isExternalLibraryImport)
currentNodeModulesDepth--;
}
else {
- fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
+ addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_find_type_definition_file_for_0, [typeReferenceDirective]);
}
if (saveResolution) {
resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
}
}
function processLibReferenceDirectives(file) {
- ts.forEach(file.libReferenceDirectives, function (libReference) {
+ ts.forEach(file.libReferenceDirectives, function (libReference, index) {
var libName = ts.toFileNameLowerCase(libReference.fileName);
var libFileName = ts.libMap.get(libName);
if (libFileName) {
// we ignore any 'no-default-lib' reference set on this file.
- processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
+ processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true, { kind: ts.FileIncludeKind.LibReferenceDirective, file: file.path, index: index, });
}
else {
var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
- var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
- fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, libReference.pos, libReference.end - libReference.pos, message, libName, suggestion));
+ var diagnostic = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
+ (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({
+ kind: 0 /* FilePreprocessingReferencedDiagnostic */,
+ reason: { kind: ts.FileIncludeKind.LibReferenceDirective, file: file.path, index: index, },
+ diagnostic: diagnostic,
+ args: [libName, suggestion]
+ });
}
});
}
- function createRefFileDiagnostic(refFile, message) {
- var args = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- args[_i - 2] = arguments[_i];
- }
- if (!refFile) {
- return ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args));
- }
- else {
- return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile.file, refFile.pos, refFile.end - refFile.pos, message], args));
- }
- }
function getCanonicalFileName(fileName) {
return host.getCanonicalFileName(fileName);
}
var moduleNames = getModuleNames(file);
var resolutions = resolveModuleNamesReusingOldState(moduleNames, file);
ts.Debug.assert(resolutions.length === moduleNames.length);
- for (var i = 0; i < moduleNames.length; i++) {
- var resolution = resolutions[i];
- ts.setResolvedModule(file, moduleNames[i], resolution);
+ for (var index = 0; index < moduleNames.length; index++) {
+ var resolution = resolutions[index];
+ ts.setResolvedModule(file, moduleNames[index], resolution);
if (!resolution) {
continue;
}
var shouldAddFile = resolvedFileName
&& !getResolutionDiagnostic(options, resolution)
&& !options.noResolve
- && i < file.imports.length
+ && index < file.imports.length
&& !elideImport
&& !(isJsFile && !ts.getAllowJSCompilerOption(options))
- && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 4194304 /* JSDoc */));
+ && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */));
if (elideImport) {
modulesWithElidedImports.set(file.path, true);
}
else if (shouldAddFile) {
var path = toPath(resolvedFileName);
- var pos = ts.skipTrivia(file.text, file.imports[i].pos);
findSourceFile(resolvedFileName, path,
/*isDefaultLib*/ false,
- /*ignoreNoDefaultLib*/ false, {
- kind: ts.RefFileKind.Import,
- index: i,
- file: file,
- pos: pos,
- end: file.imports[i].end
- }, resolution.packageId);
+ /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.Import, file: file.path, index: index, }, resolution.packageId);
}
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
file.resolvedModules = undefined;
}
}
- function computeCommonSourceDirectory(sourceFiles) {
- var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
- return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
- }
function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
var allFilesBelongToPath = true;
var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
- var rootPaths;
for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
var sourceFile = sourceFiles_2[_i];
if (!sourceFile.isDeclarationFile) {
var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
- if (!rootPaths)
- rootPaths = new ts.Set(rootNames.map(toPath));
- addProgramDiagnosticAtRefPath(sourceFile, rootPaths, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory);
+ addProgramDiagnosticExplainingFile(sourceFile, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, [sourceFile.fileName, rootDirectory]);
allFilesBelongToPath = false;
}
}
var file = files_3[_i];
// Ignore file that is not emitted
if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
- 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 || "");
+ addProgramDiagnosticExplainingFile(file, ts.Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, [file.fileName, options.configFilePath || ""]);
}
}
}
if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
}
+ if (options.preserveConstEnums === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules");
+ }
var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
if (firstNonExternalModuleSourceFile) {
var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
}
}
}
- function createFileDiagnosticAtReference(refPathToReportErrorOn, message) {
- var _a, _b;
- var args = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- args[_i - 2] = arguments[_i];
+ function createDiagnosticExplainingFile(file, fileProcessingReason, diagnostic, args) {
+ var _a;
+ var fileIncludeReasons;
+ var relatedInfo;
+ var locationReason = isReferencedFile(fileProcessingReason) ? fileProcessingReason : undefined;
+ if (file)
+ (_a = fileReasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(processReason);
+ if (fileProcessingReason)
+ processReason(fileProcessingReason);
+ // If we have location and there is only one reason file is in which is the location, dont add details for file include
+ if (locationReason && (fileIncludeReasons === null || fileIncludeReasons === void 0 ? void 0 : fileIncludeReasons.length) === 1)
+ fileIncludeReasons = undefined;
+ var location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason);
+ var fileIncludeReasonDetails = fileIncludeReasons && ts.chainDiagnosticMessages(fileIncludeReasons, ts.Diagnostics.The_file_is_in_the_program_because_Colon);
+ var redirectInfo = file && ts.explainIfFileIsRedirect(file);
+ var chain = ts.chainDiagnosticMessages.apply(void 0, __spreadArray([redirectInfo ? fileIncludeReasonDetails ? __spreadArray([fileIncludeReasonDetails], redirectInfo) : redirectInfo : fileIncludeReasonDetails, diagnostic], args || ts.emptyArray));
+ return location && isReferenceFileLocation(location) ?
+ ts.createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) :
+ ts.createCompilerDiagnosticFromMessageChain(chain, relatedInfo);
+ function processReason(reason) {
+ (fileIncludeReasons || (fileIncludeReasons = [])).push(ts.fileIncludeReasonToDiagnostics(program, reason));
+ if (!locationReason && isReferencedFile(reason)) {
+ // Report error at first reference file or file currently in processing and dont report in related information
+ locationReason = reason;
+ }
+ else if (locationReason !== reason) {
+ relatedInfo = ts.append(relatedInfo, fileIncludeReasonToRelatedInformation(reason));
+ }
+ // Remove fileProcessingReason if its already included in fileReasons of the program
+ if (reason === fileProcessingReason)
+ fileProcessingReason = undefined;
+ }
+ }
+ function addFilePreprocessingFileExplainingDiagnostic(file, fileProcessingReason, diagnostic, args) {
+ (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({
+ kind: 1 /* FilePreprocessingFileExplainingDiagnostic */,
+ file: file && file.path,
+ fileProcessingReason: fileProcessingReason,
+ diagnostic: diagnostic,
+ args: args
+ });
+ }
+ function addProgramDiagnosticExplainingFile(file, diagnostic, args) {
+ programDiagnostics.add(createDiagnosticExplainingFile(file, /*fileProcessingReason*/ undefined, diagnostic, args));
+ }
+ function fileIncludeReasonToRelatedInformation(reason) {
+ if (isReferencedFile(reason)) {
+ var referenceLocation = getReferencedFileLocation(getSourceFileByPath, reason);
+ var message_2;
+ switch (reason.kind) {
+ case ts.FileIncludeKind.Import:
+ message_2 = ts.Diagnostics.File_is_included_via_import_here;
+ break;
+ case ts.FileIncludeKind.ReferenceFile:
+ message_2 = ts.Diagnostics.File_is_included_via_reference_here;
+ break;
+ case ts.FileIncludeKind.TypeReferenceDirective:
+ message_2 = ts.Diagnostics.File_is_included_via_type_library_reference_here;
+ break;
+ case ts.FileIncludeKind.LibReferenceDirective:
+ message_2 = ts.Diagnostics.File_is_included_via_library_reference_here;
+ break;
+ default:
+ ts.Debug.assertNever(reason);
+ }
+ return isReferenceFileLocation(referenceLocation) ? ts.createFileDiagnostic(referenceLocation.file, referenceLocation.pos, referenceLocation.end - referenceLocation.pos, message_2) : undefined;
}
- var refFile = ts.Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
- var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index;
- var pos, end;
- switch (kind) {
- case ts.RefFileKind.Import:
- pos = ts.skipTrivia(refFile.text, refFile.imports[index].pos);
- end = refFile.imports[index].end;
+ if (!options.configFile)
+ return undefined;
+ var configFileNode;
+ var message;
+ switch (reason.kind) {
+ case ts.FileIncludeKind.RootFile:
+ if (!options.configFile.configFileSpecs)
+ return undefined;
+ var fileName = ts.getNormalizedAbsolutePath(rootNames[reason.index], currentDirectory);
+ var matchedByFiles = ts.getMatchedFileSpec(program, fileName);
+ if (matchedByFiles) {
+ configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "files", matchedByFiles);
+ message = ts.Diagnostics.File_is_matched_by_files_list_specified_here;
+ break;
+ }
+ var matchedByInclude = ts.getMatchedIncludeSpec(program, fileName);
+ // Could be additional files specified as roots
+ if (!matchedByInclude)
+ return undefined;
+ configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude);
+ message = ts.Diagnostics.File_is_matched_by_include_pattern_specified_here;
break;
- case ts.RefFileKind.ReferenceFile:
- (_a = refFile.referencedFiles[index], pos = _a.pos, end = _a.end);
+ case ts.FileIncludeKind.SourceFromProjectReference:
+ case ts.FileIncludeKind.OutputFromProjectReference:
+ var referencedResolvedRef_1 = ts.Debug.checkDefined(resolvedProjectReferences === null || resolvedProjectReferences === void 0 ? void 0 : resolvedProjectReferences[reason.index]);
+ var referenceInfo = forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, parent, index) {
+ return resolvedRef === referencedResolvedRef_1 ? { sourceFile: (parent === null || parent === void 0 ? void 0 : parent.sourceFile) || options.configFile, index: index } : undefined;
+ });
+ if (!referenceInfo)
+ return undefined;
+ var sourceFile = referenceInfo.sourceFile, index = referenceInfo.index;
+ var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
+ return referencesSyntax && referencesSyntax.elements.length > index ?
+ ts.createDiagnosticForNodeInSourceFile(sourceFile, referencesSyntax.elements[index], reason.kind === ts.FileIncludeKind.OutputFromProjectReference ?
+ ts.Diagnostics.File_is_output_from_referenced_project_specified_here :
+ ts.Diagnostics.File_is_source_from_referenced_project_specified_here) :
+ undefined;
+ case ts.FileIncludeKind.AutomaticTypeDirectiveFile:
+ if (!options.types)
+ return undefined;
+ configFileNode = getOptionsSyntaxByArrayElementValue("types", reason.typeReference);
+ message = ts.Diagnostics.File_is_entry_point_of_type_library_specified_here;
break;
- case ts.RefFileKind.TypeReferenceDirective:
- (_b = refFile.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
+ case ts.FileIncludeKind.LibFile:
+ if (reason.index !== undefined) {
+ configFileNode = getOptionsSyntaxByArrayElementValue("lib", options.lib[reason.index]);
+ message = ts.Diagnostics.File_is_library_specified_here;
+ break;
+ }
+ var target = ts.forEachEntry(ts.targetOptionDeclaration.type, function (value, key) { return value === options.target ? key : undefined; });
+ configFileNode = target ? getOptionsSyntaxByValue("target", target) : undefined;
+ message = ts.Diagnostics.File_is_default_library_for_target_specified_here;
break;
default:
- return ts.Debug.assertNever(kind);
- }
- return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile, pos, end - pos, message], args));
- }
- function addProgramDiagnosticAtRefPath(file, rootPaths, message) {
- var args = [];
- for (var _i = 3; _i < arguments.length; _i++) {
- args[_i - 3] = arguments[_i];
+ ts.Debug.assertNever(reason);
}
- var refPaths = refFileMap === null || refFileMap === void 0 ? void 0 : refFileMap.get(file.path);
- var refPathToReportErrorOn = ts.forEach(refPaths, function (refPath) { return rootPaths.has(refPath.file) ? refPath : undefined; }) ||
- ts.elementAt(refPaths, 0);
- programDiagnostics.add(refPathToReportErrorOn ? createFileDiagnosticAtReference.apply(void 0, __spreadArrays([refPathToReportErrorOn, message], args)) : ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
+ return configFileNode && ts.createDiagnosticForNodeInSourceFile(options.configFile, configFileNode, message);
}
function verifyProjectReferences() {
var buildInfoPath = !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
}
function getOptionsSyntaxByName(name) {
var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
- if (compilerOptionsObjectLiteralSyntax) {
- return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
- }
- return undefined;
+ return compilerOptionsObjectLiteralSyntax && ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
}
function getOptionPathsSyntax() {
return getOptionsSyntaxByName("paths") || ts.emptyArray;
}
+ function getOptionsSyntaxByValue(name, value) {
+ var syntaxByName = getOptionsSyntaxByName(name);
+ return syntaxByName && ts.firstDefined(syntaxByName, function (property) { return ts.isStringLiteral(property.initializer) && property.initializer.text === value ? property.initializer : undefined; });
+ }
+ function getOptionsSyntaxByArrayElementValue(name, value) {
+ var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
+ return compilerOptionsObjectLiteralSyntax && ts.getPropertyArrayElementValue(compilerOptionsObjectLiteralSyntax, name, value);
+ }
function createDiagnosticForOptionName(message, option1, option2, option3) {
createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
}
}
function getCompilerOptionsObjectLiteralSyntax() {
if (_compilerOptionsObjectLiteralSyntax === undefined) {
- _compilerOptionsObjectLiteralSyntax = null; // eslint-disable-line no-null/no-null
+ _compilerOptionsObjectLiteralSyntax = false;
var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
if (jsonObjectLiteral) {
for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
}
}
}
- return _compilerOptionsObjectLiteralSyntax;
+ return _compilerOptionsObjectLiteralSyntax || undefined;
}
function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
}
function handleDirectoryCouldBeSymlink(directory) {
var _a;
- if (!host.getResolvedProjectReferences())
+ if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory))
return;
// Because we already watch node_modules, handle symlinks in there
if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
symlinkCache.setSymlinkedDirectory(directoryPath, false);
return;
}
- symlinkCache.setSymlinkedDirectory(directoryPath, {
+ symlinkCache.setSymlinkedDirectory(directory, {
real: ts.ensureTrailingDirectorySeparator(real),
realPath: realPath
});
// get any preEmit diagnostics, not just the ones
if (!options.noEmitOnError)
return undefined;
- var diagnostics = __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
+ var diagnostics = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], program.getOptionsDiagnostics(cancellationToken)), program.getSyntacticDiagnostics(sourceFile, cancellationToken)), program.getGlobalDiagnostics(cancellationToken)), program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
}
if (!sourceFile && !ts.outFile(options)) {
var emitResult = program.emitBuildInfo(writeFile, cancellationToken);
if (emitResult.diagnostics)
- diagnostics = __spreadArrays(diagnostics, emitResult.diagnostics);
+ diagnostics = __spreadArray(__spreadArray([], diagnostics), emitResult.diagnostics);
emittedFiles = emitResult.emittedFiles;
}
return { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: emittedFiles, emitSkipped: true };
}
return res;
}
+ /* @internal */
+ function getModuleNameStringLiteralAt(_a, index) {
+ var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
+ if (index < imports.length)
+ return imports[index];
+ var augIndex = imports.length;
+ for (var _i = 0, moduleAugmentations_2 = moduleAugmentations; _i < moduleAugmentations_2.length; _i++) {
+ var aug = moduleAugmentations_2[_i];
+ if (aug.kind === 10 /* StringLiteral */) {
+ if (index === augIndex)
+ return aug;
+ augIndex++;
+ }
+ // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
+ }
+ ts.Debug.fail("should never ask for module name at index higher than possible module name");
+ }
+ ts.getModuleNameStringLiteralAt = getModuleNameStringLiteralAt;
})(ts || (ts = {}));
/*@internal*/
var ts;
var newReferences;
// if not using old state, every file is changed
if (!useOldState ||
- // File wasnt present in old state
+ // File wasn't present in old state
!(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
// versions dont match
oldInfo.version !== info.version ||
invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations,
setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
createHasInvalidatedResolution: createHasInvalidatedResolution,
+ isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports,
updateTypeRootsWatch: updateTypeRootsWatch,
closeTypeRootsWatch: closeTypeRootsWatch,
clear: clear
var resolvedModules = [];
var compilerOptions = resolutionHost.getCompilationSettings();
var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
- // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
+ // All the resolutions in this file are invalidated if this file wasn't resolved using same redirect
var program = resolutionHost.getCurrentProgram();
var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
var unmatchedRedirects = oldRedirect ?
(function (RelativePreference) {
RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
- RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
+ RelativePreference[RelativePreference["Shortest"] = 2] = "Shortest";
+ RelativePreference[RelativePreference["ExternalNonRelative"] = 3] = "ExternalNonRelative";
})(RelativePreference || (RelativePreference = {}));
// See UserPreferences#importPathEnding
var Ending;
function getPreferences(_a, compilerOptions, importingSourceFile) {
var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
return {
- relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
+ relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ :
+ importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ :
+ importModuleSpecifierPreference === "project-relative" ? 3 /* ExternalNonRelative */ :
+ 2 /* Shortest */,
ending: getEnding(),
};
function getEnding() {
getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences);
}
/** Returns an import for each symlink and for the realpath. */
- function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, userPreferences) {
- var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
+ function getModuleSpecifiers(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences) {
+ var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker);
if (ambient)
return [ambient];
var info = getInfo(importingSourceFile.path, host);
var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host);
var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
+ var existingSpecifier = ts.forEach(modulePaths, function (modulePath) { return ts.forEach(host.getFileIncludeReasons().get(ts.toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), function (reason) {
+ if (reason.kind !== ts.FileIncludeKind.Import || reason.file !== importingSourceFile.path)
+ return undefined;
+ var specifier = ts.getModuleNameStringLiteralAt(importingSourceFile, reason.index).text;
+ // If the preference is for non relative and the module specifier is relative, ignore it
+ return preferences.relativePreference !== 1 /* NonRelative */ || !ts.pathIsRelative(specifier) ?
+ specifier :
+ undefined;
+ }); });
+ if (existingSpecifier)
+ return [existingSpecifier];
var importedFileIsInNodeModules = ts.some(modulePaths, function (p) { return p.isInNodeModules; });
// Module specifier priority:
// 1. "Bare package specifiers" (e.g. "@foo/bar") resulting from a path through node_modules to a package.json's "types" entry
function getInfo(importingSourceFileName, host) {
var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
- return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
+ return { getCanonicalFileName: getCanonicalFileName, importingSourceFileName: importingSourceFileName, sourceDirectory: sourceDirectory };
}
- function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, host, _b) {
- var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
- var ending = _b.ending, relativePreference = _b.relativePreference;
+ function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, _a) {
+ var ending = _a.ending, relativePreference = _a.relativePreference;
var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
+ var sourceDirectory = info.sourceDirectory, getCanonicalFileName = info.getCanonicalFileName;
var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
if (!baseUrl && !paths || relativePreference === 0 /* Relative */) {
if (relativePreference === 1 /* NonRelative */) {
return nonRelative;
}
- if (relativePreference !== 2 /* Auto */)
+ if (relativePreference === 3 /* ExternalNonRelative */) {
+ var projectDirectory = host.getCurrentDirectory();
+ var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName);
+ var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory);
+ var targetIsInternal = ts.startsWith(modulePath, projectDirectory);
+ if (sourceIsInternal && !targetIsInternal || !sourceIsInternal && targetIsInternal) {
+ // 1. The import path crosses the boundary of the tsconfig.json-containing directory.
+ //
+ // src/
+ // tsconfig.json
+ // index.ts -------
+ // lib/ | (path crosses tsconfig.json)
+ // imported.ts <---
+ //
+ return nonRelative;
+ }
+ var nearestTargetPackageJson = getNearestAncestorDirectoryWithPackageJson(host, ts.getDirectoryPath(modulePath));
+ var nearestSourcePackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory);
+ if (nearestSourcePackageJson !== nearestTargetPackageJson) {
+ // 2. The importing and imported files are part of different packages.
+ //
+ // packages/a/
+ // package.json
+ // index.ts --------
+ // packages/b/ | (path crosses package.json)
+ // package.json |
+ // component.ts <---
+ //
+ return nonRelative;
+ }
+ return relativePath;
+ }
+ if (relativePreference !== 2 /* Shortest */)
ts.Debug.assertNever(relativePreference);
// Prefer a relative import over a baseUrl import if it has fewer components.
return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
}) || false;
}
- function numberOfDirectorySeparators(str) {
- var match = str.match(/\//g);
- return match ? match.length : 0;
- }
function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) {
- return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path));
+ return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path);
+ }
+ function getNearestAncestorDirectoryWithPackageJson(host, fileName) {
+ if (host.getNearestAncestorDirectoryWithPackageJson) {
+ return host.getNearestAncestorDirectoryWithPackageJson(fileName);
+ }
+ return !!ts.forEachAncestorDirectory(fileName, function (directory) {
+ return host.fileExists(ts.combinePaths(directory, "package.json")) ? true : undefined;
+ });
}
function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
var cwd = host.getCurrentDirectory();
var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
- var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray;
- var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects);
+ var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName);
+ var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray;
+ var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects);
var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
+ var shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath);
if (!preferSymlinks) {
- var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); });
+ // Symlinks inside ignored paths are already filtered out of the symlink cache,
+ // so we only need to remove them from the realpath filenames.
+ var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); });
if (result_15)
return result_15;
}
var links = host.getSymlinkCache
? host.getSymlinkCache()
: ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd);
- var symlinkedDirectories = links.getSymlinkedDirectories();
- var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames();
- var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) {
- if (resolved === false)
- return undefined;
- if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) {
- return undefined; // Don't want to a package to globally import from itself
+ var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath();
+ var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd);
+ var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) {
+ var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName)));
+ if (!symlinkDirectories)
+ return undefined; // Continue to ancestor directory
+ // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts)
+ if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) {
+ return false; // Stop search, each ancestor directory will also hit this condition
}
return ts.forEach(targets, function (target) {
- if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) {
+ if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) {
return;
}
- var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName);
- var option = ts.resolvePath(path, relative);
- if (!host.fileExists || host.fileExists(option)) {
+ var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName);
+ for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) {
+ var symlinkDirectory = symlinkDirectories_1[_i];
+ var option = ts.resolvePath(symlinkDirectory, relative);
var result_16 = cb(option, target === referenceRedirect);
+ shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths
if (result_16)
return result_16;
}
});
});
- return result ||
- (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined);
+ return result || (preferSymlinks
+ ? ts.forEach(targets, function (p) { return shouldFilterIgnoredPaths && ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); })
+ : undefined);
}
moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
/**
}
return sortedPaths;
}
- function tryGetModuleNameFromAmbientModule(moduleSymbol) {
+ function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) {
var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
if (decl) {
return decl.name.text;
}
+ // the module could be a namespace, which is export through "export=" from an ambient module.
+ /**
+ * declare module "m" {
+ * namespace ns {
+ * class c {}
+ * }
+ * export = ns;
+ * }
+ */
+ // `import {c} from "m";` is valid, in which case, `moduleSymbol` is "ns", but the module name should be "m"
+ var ambientModuleDeclareCandidates = ts.mapDefined(moduleSymbol.declarations, function (d) {
+ var _a, _b, _c, _d;
+ if (!ts.isModuleDeclaration(d))
+ return;
+ var topNamespace = getTopNamespace(d);
+ if (!(((_a = topNamespace === null || topNamespace === void 0 ? void 0 : topNamespace.parent) === null || _a === void 0 ? void 0 : _a.parent)
+ && ts.isModuleBlock(topNamespace.parent) && ts.isAmbientModule(topNamespace.parent.parent) && ts.isSourceFile(topNamespace.parent.parent.parent)))
+ return;
+ var exportAssignment = (_d = (_c = (_b = topNamespace.parent.parent.symbol.exports) === null || _b === void 0 ? void 0 : _b.get("export=")) === null || _c === void 0 ? void 0 : _c.valueDeclaration) === null || _d === void 0 ? void 0 : _d.expression;
+ if (!exportAssignment)
+ return;
+ var exportSymbol = checker.getSymbolAtLocation(exportAssignment);
+ if (!exportSymbol)
+ return;
+ var originalExportSymbol = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.flags) & 2097152 /* Alias */ ? checker.getAliasedSymbol(exportSymbol) : exportSymbol;
+ if (originalExportSymbol === d.symbol)
+ return topNamespace.parent.parent;
+ function getTopNamespace(namespaceDeclaration) {
+ while (namespaceDeclaration.flags & 4 /* NestedNamespace */) {
+ namespaceDeclaration = namespaceDeclaration.parent;
+ }
+ return namespaceDeclaration;
+ }
+ });
+ var ambientModuleDeclare = ambientModuleDeclareCandidates[0];
+ if (ambientModuleDeclare) {
+ return ambientModuleDeclare.name.text;
+ }
}
function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
for (var key in paths) {
return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
}
ts.getErrorSummaryText = getErrorSummaryText;
- function listFiles(program, writeFileName) {
- if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
+ function isBuilderProgram(program) {
+ return !!program.getState;
+ }
+ ts.isBuilderProgram = isBuilderProgram;
+ function listFiles(program, write) {
+ var options = program.getCompilerOptions();
+ if (options.explainFiles) {
+ explainFiles(isBuilderProgram(program) ? program.getProgram() : program, write);
+ }
+ else if (options.listFiles || options.listFilesOnly) {
ts.forEach(program.getSourceFiles(), function (file) {
- writeFileName(file.fileName);
+ write(file.fileName);
});
}
}
ts.listFiles = listFiles;
+ function explainFiles(program, write) {
+ var _a, _b;
+ var reasons = program.getFileIncludeReasons();
+ var getCanonicalFileName = ts.createGetCanonicalFileName(program.useCaseSensitiveFileNames());
+ var relativeFileName = function (fileName) { return ts.convertToRelativePath(fileName, program.getCurrentDirectory(), getCanonicalFileName); };
+ for (var _i = 0, _c = program.getSourceFiles(); _i < _c.length; _i++) {
+ var file = _c[_i];
+ write("" + toFileName(file, relativeFileName));
+ (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write(" " + fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText); });
+ (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" " + d.messageText); });
+ }
+ }
+ ts.explainFiles = explainFiles;
+ function explainIfFileIsRedirect(file, fileNameConvertor) {
+ var result;
+ if (file.path !== file.resolvedPath) {
+ (result || (result = [])).push(ts.chainDiagnosticMessages(
+ /*details*/ undefined, ts.Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor)));
+ }
+ if (file.redirectInfo) {
+ (result || (result = [])).push(ts.chainDiagnosticMessages(
+ /*details*/ undefined, ts.Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor)));
+ }
+ return result;
+ }
+ ts.explainIfFileIsRedirect = explainIfFileIsRedirect;
+ function getMatchedFileSpec(program, fileName) {
+ var _a;
+ var configFile = program.getCompilerOptions().configFile;
+ if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedFilesSpec))
+ return undefined;
+ var getCanonicalFileName = ts.createGetCanonicalFileName(program.useCaseSensitiveFileNames());
+ var filePath = getCanonicalFileName(fileName);
+ var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory()));
+ return ts.find(configFile.configFileSpecs.validatedFilesSpec, function (fileSpec) { return getCanonicalFileName(ts.getNormalizedAbsolutePath(fileSpec, basePath)) === filePath; });
+ }
+ ts.getMatchedFileSpec = getMatchedFileSpec;
+ function getMatchedIncludeSpec(program, fileName) {
+ var _a, _b;
+ var configFile = program.getCompilerOptions().configFile;
+ if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedIncludeSpecs))
+ return undefined;
+ var isJsonFile = ts.fileExtensionIs(fileName, ".json" /* Json */);
+ var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory()));
+ var useCaseSensitiveFileNames = program.useCaseSensitiveFileNames();
+ return ts.find((_b = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _b === void 0 ? void 0 : _b.validatedIncludeSpecs, function (includeSpec) {
+ if (isJsonFile && !ts.endsWith(includeSpec, ".json" /* Json */))
+ return false;
+ var pattern = ts.getPatternFromSpec(includeSpec, basePath, "files");
+ return !!pattern && ts.getRegexFromPattern("(" + pattern + ")$", useCaseSensitiveFileNames).test(fileName);
+ });
+ }
+ ts.getMatchedIncludeSpec = getMatchedIncludeSpec;
+ function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) {
+ var _a, _b;
+ var options = program.getCompilerOptions();
+ if (ts.isReferencedFile(reason)) {
+ var referenceLocation = ts.getReferencedFileLocation(function (path) { return program.getSourceFileByPath(path); }, reason);
+ var referenceText = ts.isReferenceFileLocation(referenceLocation) ? referenceLocation.file.text.substring(referenceLocation.pos, referenceLocation.end) : "\"" + referenceLocation.text + "\"";
+ var message = void 0;
+ ts.Debug.assert(ts.isReferenceFileLocation(referenceLocation) || reason.kind === ts.FileIncludeKind.Import, "Only synthetic references are imports");
+ switch (reason.kind) {
+ case ts.FileIncludeKind.Import:
+ if (ts.isReferenceFileLocation(referenceLocation)) {
+ message = referenceLocation.packageId ?
+ ts.Diagnostics.Imported_via_0_from_file_1_with_packageId_2 :
+ ts.Diagnostics.Imported_via_0_from_file_1;
+ }
+ else if (referenceLocation.text === ts.externalHelpersModuleNameText) {
+ message = referenceLocation.packageId ?
+ ts.Diagnostics.Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions :
+ ts.Diagnostics.Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions;
+ }
+ else {
+ message = referenceLocation.packageId ?
+ ts.Diagnostics.Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions :
+ ts.Diagnostics.Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions;
+ }
+ break;
+ case ts.FileIncludeKind.ReferenceFile:
+ ts.Debug.assert(!referenceLocation.packageId);
+ message = ts.Diagnostics.Referenced_via_0_from_file_1;
+ break;
+ case ts.FileIncludeKind.TypeReferenceDirective:
+ message = referenceLocation.packageId ?
+ ts.Diagnostics.Type_library_referenced_via_0_from_file_1_with_packageId_2 :
+ ts.Diagnostics.Type_library_referenced_via_0_from_file_1;
+ break;
+ case ts.FileIncludeKind.LibReferenceDirective:
+ ts.Debug.assert(!referenceLocation.packageId);
+ message = ts.Diagnostics.Library_referenced_via_0_from_file_1;
+ break;
+ default:
+ ts.Debug.assertNever(reason);
+ }
+ return ts.chainDiagnosticMessages(
+ /*details*/ undefined, message, referenceText, toFileName(referenceLocation.file, fileNameConvertor), referenceLocation.packageId && ts.packageIdToString(referenceLocation.packageId));
+ }
+ switch (reason.kind) {
+ case ts.FileIncludeKind.RootFile:
+ if (!((_a = options.configFile) === null || _a === void 0 ? void 0 : _a.configFileSpecs))
+ return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation);
+ var fileName = ts.getNormalizedAbsolutePath(program.getRootFileNames()[reason.index], program.getCurrentDirectory());
+ var matchedByFiles = getMatchedFileSpec(program, fileName);
+ if (matchedByFiles)
+ return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Part_of_files_list_in_tsconfig_json);
+ var matchedByInclude = getMatchedIncludeSpec(program, fileName);
+ return matchedByInclude ?
+ ts.chainDiagnosticMessages(
+ /*details*/ undefined, ts.Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, toFileName(options.configFile, fileNameConvertor)) :
+ // Could be additional files specified as roots
+ ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation);
+ case ts.FileIncludeKind.SourceFromProjectReference:
+ case ts.FileIncludeKind.OutputFromProjectReference:
+ var isOutput = reason.kind === ts.FileIncludeKind.OutputFromProjectReference;
+ var referencedResolvedRef = ts.Debug.checkDefined((_b = program.getResolvedProjectReferences()) === null || _b === void 0 ? void 0 : _b[reason.index]);
+ return ts.chainDiagnosticMessages(
+ /*details*/ undefined, ts.outFile(options) ?
+ isOutput ?
+ ts.Diagnostics.Output_from_referenced_project_0_included_because_1_specified :
+ ts.Diagnostics.Source_from_referenced_project_0_included_because_1_specified :
+ isOutput ?
+ ts.Diagnostics.Output_from_referenced_project_0_included_because_module_is_specified_as_none :
+ ts.Diagnostics.Source_from_referenced_project_0_included_because_module_is_specified_as_none, toFileName(referencedResolvedRef.sourceFile.fileName, fileNameConvertor), options.outFile ? "--outFile" : "--out");
+ case ts.FileIncludeKind.AutomaticTypeDirectiveFile:
+ return ts.chainDiagnosticMessages(
+ /*details*/ undefined, options.types ?
+ reason.packageId ?
+ ts.Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1 :
+ ts.Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions :
+ reason.packageId ?
+ ts.Diagnostics.Entry_point_for_implicit_type_library_0_with_packageId_1 :
+ ts.Diagnostics.Entry_point_for_implicit_type_library_0, reason.typeReference, reason.packageId && ts.packageIdToString(reason.packageId));
+ case ts.FileIncludeKind.LibFile:
+ if (reason.index !== undefined)
+ return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Library_0_specified_in_compilerOptions, options.lib[reason.index]);
+ var target = ts.forEachEntry(ts.targetOptionDeclaration.type, function (value, key) { return value === options.target ? key : undefined; });
+ return ts.chainDiagnosticMessages(
+ /*details*/ undefined, target ?
+ ts.Diagnostics.Default_library_for_target_0 :
+ ts.Diagnostics.Default_library, target);
+ default:
+ ts.Debug.assertNever(reason);
+ }
+ }
+ ts.fileIncludeReasonToDiagnostics = fileIncludeReasonToDiagnostics;
+ function toFileName(file, fileNameConvertor) {
+ var fileName = ts.isString(file) ? file : file.fileName;
+ return fileNameConvertor ? fileNameConvertor(fileName) : fileName;
+ }
/**
* Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
*/
- function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
+ function emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
// First get and report any syntactic errors.
var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
ts.addRange(allDiagnostics, emitDiagnostics);
var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
diagnostics.forEach(reportDiagnostic);
- if (writeFileName) {
+ if (write) {
var currentDir_1 = program.getCurrentDirectory();
ts.forEach(emittedFiles, function (file) {
var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
- writeFileName("TSFILE: " + filepath);
+ write("TSFILE: " + filepath);
});
- listFiles(program, writeFileName);
+ listFiles(program, write);
}
if (reportSummary) {
reportSummary(getErrorCountForSummary(diagnostics));
};
}
ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
- function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
- var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
+ function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, write, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
+ var _a = emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
if (emitResult.emitSkipped && diagnostics.length > 0) {
// If the emitter didn't emit anything, then pass that value along.
return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
ts.createWatchHost = createWatchHost;
ts.WatchType = {
ConfigFile: "Config file",
+ ExtendedConfigFile: "Extended config file",
SourceFile: "Source file",
MissingFile: "Missing file",
WildcardDirectory: "Wild card directory",
function createWatchFactory(host, options) {
var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
- var result = ts.getWatchFactory(watchLogLevel, writeLog);
+ var result = ts.getWatchFactory(host, watchLogLevel, writeLog);
result.writeLog = writeLog;
return result;
}
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArray([compilerHost], args));
if (result) {
result.version = computeHash(result.text);
}
*/
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var writeFileName = function (s) { return system.write(s + system.newLine); };
+ var write = function (s) { return system.write(s + system.newLine); };
var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
- emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
+ emitFilesAndReportErrors(builderProgram, reportDiagnostic, write, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
};
return result;
}
function createWatchProgram(host) {
var builderProgram;
var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
+ var extendedConfigFilesMap; // Map of file watchers for the extended config files
var missingFilesMap; // Map of file watchers for the missing files
var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
var timerToUpdateProgram; // timer callback to recompile the program
var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations
var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info
- 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
+ var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files
var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
var currentDirectory = host.getCurrentDirectory();
var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
- var configFileSpecs;
+ var wildcardDirectories;
var configFileParsingDiagnostics;
var canConfigFileJsonReportNoInputFiles = false;
var hasChangedConfigFileParsingErrors = false;
parseConfigFile();
newLine = updateNewLine();
}
- var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
+ var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
var configFileWatcher;
if (configFileName) {
- configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
+ configFileWatcher = watchFile(configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
}
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
ts.setGetSourceFileAsHashVersioned(compilerHost, host);
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
- return getVersionedSourceFileByPath.apply(void 0, __spreadArrays([fileName, toPath(fileName)], args));
+ return getVersionedSourceFileByPath.apply(void 0, __spreadArray([fileName, toPath(fileName)], args));
};
compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
compilerHost.getNewLine = function () { return newLine; };
compilerHost.toPath = toPath;
compilerHost.getCompilationSettings = function () { return compilerOptions; };
compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
- compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
- compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
+ compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
+ compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations;
compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
synchronizeProgram();
// Update the wild card directory watch
watchConfigFileWildCardDirectories();
+ // Update extended config file watch
+ watchExtendedConfigFiles();
return configFileName ?
{ getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
{ getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
configFileWatcher.close();
configFileWatcher = undefined;
}
+ if (extendedConfigFilesMap) {
+ ts.clearMap(extendedConfigFilesMap, ts.closeFileWatcher);
+ extendedConfigFilesMap = undefined;
+ }
if (watchedWildcardDirectories) {
ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
watchedWildcardDirectories = undefined;
hostSourceFile.sourceFile = sourceFile;
hostSourceFile.version = sourceFile.version;
if (!hostSourceFile.fileWatcher) {
- hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
+ hostSourceFile.fileWatcher = watchFilePath(path, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, ts.WatchType.SourceFile);
}
}
else {
}
else {
if (sourceFile) {
- var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
+ var fileWatcher = watchFilePath(path, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, ts.WatchType.SourceFile);
sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
}
else {
}
function reloadFileNamesFromConfigFile() {
writeLog("Reloading new file names and options");
- var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions);
- if (ts.updateErrorForNoInputFiles(result, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
+ rootFileNames = ts.getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions);
+ if (ts.updateErrorForNoInputFiles(rootFileNames, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
hasChangedConfigFileParsingErrors = true;
}
- rootFileNames = result.fileNames;
// Update the program
synchronizeProgram();
}
synchronizeProgram();
// Update the wild card directory watch
watchConfigFileWildCardDirectories();
+ // Update extended config file watch
+ watchExtendedConfigFiles();
}
function parseConfigFile() {
setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
rootFileNames = configFileParseResult.fileNames;
compilerOptions = configFileParseResult.options;
watchOptions = configFileParseResult.watchOptions;
- configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
projectReferences = configFileParseResult.projectReferences;
+ wildcardDirectories = configFileParseResult.wildcardDirectories;
configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw);
hasChangedConfigFileParsingErrors = true;
}
+ function watchFilePath(path, file, callback, pollingInterval, options, watchType) {
+ return watchFile(file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options, watchType);
+ }
function onSourceFileChange(fileName, eventKind, path) {
updateCachedSystemWithFile(fileName, path, eventKind);
// Update the source file cache
}
}
function watchMissingFilePath(missingFilePath) {
- return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, missingFilePath, ts.WatchType.MissingFile);
+ return watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile);
}
function onMissingFileChange(fileName, eventKind, missingFilePath) {
updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
}
}
function watchConfigFileWildCardDirectories() {
- if (configFileSpecs) {
- ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = new ts.Map()), new ts.Map(ts.getEntries(configFileSpecs.wildcardDirectories)), watchWildcardDirectory);
+ if (wildcardDirectories) {
+ ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = new ts.Map()), new ts.Map(ts.getEntries(wildcardDirectories)), watchWildcardDirectory);
}
else if (watchedWildcardDirectories) {
ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
}
}
function watchWildcardDirectory(directory, flags) {
- return watchDirectory(host, directory, function (fileOrDirectory) {
+ return watchDirectory(directory, function (fileOrDirectory) {
ts.Debug.assert(!!configFileName);
var fileOrDirectoryPath = toPath(fileOrDirectory);
// Since the file existence changed, update the sourceFiles cache
fileOrDirectory: fileOrDirectory,
fileOrDirectoryPath: fileOrDirectoryPath,
configFileName: configFileName,
- configFileSpecs: configFileSpecs,
extraFileExtensions: extraFileExtensions,
options: compilerOptions,
program: getCurrentBuilderProgram(),
}
}, flags, watchOptions, ts.WatchType.WildcardDirectory);
}
+ function watchExtendedConfigFiles() {
+ var _a;
+ // Update the extended config files watcher
+ ts.mutateMap(extendedConfigFilesMap || (extendedConfigFilesMap = new ts.Map()), ts.arrayToMap(((_a = compilerOptions.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath), {
+ // Watch the extended config files
+ createNewValue: watchExtendedConfigFile,
+ // Config files that are no longer extended should no longer be watched.
+ onDeleteValue: ts.closeFileWatcher
+ });
+ }
+ function watchExtendedConfigFile(extendedConfigFile) {
+ return watchFile(extendedConfigFile, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ExtendedConfigFile);
+ }
}
ts.createWatchProgram = createWatchProgram;
})(ts || (ts = {}));
return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
};
}
- var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
+ var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
var state = {
host: host,
hostWithWatch: hostWithWatch,
currentDirectory: currentDirectory,
getCanonicalFileName: getCanonicalFileName,
parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
- writeFileName: host.trace ? function (s) { return host.trace(s); } : undefined,
+ write: ts.maybeBind(host, host.trace),
// State of solution
options: options,
baseCompilerOptions: baseCompilerOptions,
allWatchedWildcardDirectories: new ts.Map(),
allWatchedInputFiles: new ts.Map(),
allWatchedConfigFiles: new ts.Map(),
+ allWatchedExtendedConfigFiles: new ts.Map(),
timerToBuildInvalidatedProject: undefined,
reportFileChangeDetected: false,
watchFile: watchFile,
- watchFilePath: watchFilePath,
watchDirectory: watchDirectory,
writeLog: writeLog,
};
// Remove watches for the program no longer in the solution
if (state.watch) {
ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
+ state.allWatchedExtendedConfigFiles.forEach(function (watcher) {
+ watcher.projects.forEach(function (project) {
+ if (!currentProjects.has(project)) {
+ watcher.projects.delete(project);
+ }
+ });
+ watcher.close();
+ });
ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
}
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
- return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
+ return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArray([compilerHost], args));
}), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
state.readFileWithCache = readFileWithCache;
compilerHost.getSourceFile = getSourceFileWithCache;
}
function getSyntaxDiagnostics(cancellationToken) {
ts.Debug.assertIsDefined(program);
- handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
+ handleDiagnostics(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], program.getConfigFileParsingDiagnostics()), program.getOptionsDiagnostics(cancellationToken)), program.getGlobalDiagnostics(cancellationToken)), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
}
function getSemanticDiagnostics(cancellationToken) {
handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
var outputFiles = [];
var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics,
- /*writeFileName*/ undefined,
+ /*write*/ undefined,
/*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken,
/*emitOnlyDts*/ false, customTransformers).emitResult;
// Don't emit .d.ts if there are decl file errors
var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken);
if (emitResult.diagnostics.length) {
reportErrors(state, emitResult.diagnostics);
- state.diagnostics.set(projectPath, __spreadArrays(state.diagnostics.get(projectPath), emitResult.diagnostics));
+ state.diagnostics.set(projectPath, __spreadArray(__spreadArray([], state.diagnostics.get(projectPath)), emitResult.diagnostics));
buildResult = BuildResultFlags.EmitErrors & buildResult;
}
- if (emitResult.emittedFiles && state.writeFileName) {
+ if (emitResult.emittedFiles && state.write) {
emitResult.emittedFiles.forEach(function (name) { return listEmittedFile(state, config, name); });
}
afterProgramDone(state, program, config);
(_a = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"), buildResult = _a.buildResult, step = _a.step);
return emitDiagnostics;
}
- if (state.writeFileName) {
+ if (state.write) {
emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
}
// Update time stamps for rest of the outputs
}
if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
watchConfigFile(state, project, projectPath, config);
+ watchExtendedConfigFiles(state, projectPath, config);
watchWildCardDirectories(state, project, projectPath, config);
watchInputFiles(state, project, projectPath, config);
}
else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
// Update file names
- var result = ts.getFileNamesFromConfigSpecs(config.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
- ts.updateErrorForNoInputFiles(result, project, config.configFileSpecs, config.errors, ts.canJsonReportNoInputFiles(config.raw));
- config.fileNames = result.fileNames;
+ config.fileNames = ts.getFileNamesFromConfigSpecs(config.options.configFile.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
+ ts.updateErrorForNoInputFiles(config.fileNames, project, config.options.configFile.configFileSpecs, config.errors, ts.canJsonReportNoInputFiles(config.raw));
watchInputFiles(state, project, projectPath, config);
}
var status = getUpToDateStatus(state, config, projectPath);
return undefined;
}
function listEmittedFile(_a, proj, file) {
- var writeFileName = _a.writeFileName;
- if (writeFileName && proj.options.listEmittedFiles) {
- writeFileName("TSFILE: " + file);
+ var write = _a.write;
+ if (write && proj.options.listEmittedFiles) {
+ write("TSFILE: " + file);
}
}
function getOldProgram(_a, proj, parsed) {
}
function afterProgramDone(state, program, config) {
if (program) {
- if (program && state.writeFileName)
- ts.listFiles(program, state.writeFileName);
+ if (program && state.write)
+ ts.listFiles(program, state.write);
if (state.host.afterProgramEmitAndDiagnostics) {
state.host.afterProgramEmitAndDiagnostics(program);
}
function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) {
var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions());
reportAndStoreErrors(state, resolvedPath, diagnostics);
- // List files if any other build error using program (emit errors already report files)
state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
if (canEmitBuildInfo)
return { buildResult: buildResult, step: BuildStep.EmitBuildInfo };
function watchConfigFile(state, resolved, resolvedPath, parsed) {
if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
return;
- state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(state.hostWithWatch, resolved, function () {
+ state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(resolved, function () {
invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
}, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
}
+ function watchExtendedConfigFiles(state, resolvedPath, parsed) {
+ ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () {
+ var _a;
+ return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) {
+ return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full);
+ });
+ }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ExtendedConfigFile); }, function (fileName) { return toPath(state, fileName); });
+ }
function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
if (!state.watch)
return;
- ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.configFileSpecs.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(state.hostWithWatch, dir, function (fileOrDirectory) {
+ ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(dir, function (fileOrDirectory) {
if (ts.isIgnoredFileFromWildCardWatching({
watchedDirPath: toPath(state, dir),
fileOrDirectory: fileOrDirectory,
fileOrDirectoryPath: toPath(state, fileOrDirectory),
configFileName: resolved,
- configFileSpecs: parsed.configFileSpecs,
currentDirectory: state.currentDirectory,
options: parsed.options,
program: state.builderPrograms.get(resolvedPath),
if (!state.watch)
return;
ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
- 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); },
+ createNewValue: function (_path, input) { return state.watchFile(input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); },
onDeleteValue: ts.closeFileWatcher,
});
}
var cfg = parseConfigFile(state, resolved, resolvedPath);
// Watch this file
watchConfigFile(state, resolved, resolvedPath, cfg);
+ watchExtendedConfigFiles(state, resolvedPath, cfg);
if (cfg) {
// Update watchers for wildcard directories
watchWildCardDirectories(state, resolved, resolvedPath, cfg);
}
function stopWatching(state) {
ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
+ ts.clearMap(state.allWatchedExtendedConfigFiles, function (watcher) {
+ watcher.projects.clear();
+ watcher.close();
+ });
ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
}
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
- state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
+ state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArray([message], args)));
}
function reportWatchStatus(state, message) {
+ var _a, _b;
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
- if (state.hostWithWatch.onWatchStatusChange) {
- state.hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
- }
+ (_b = (_a = state.hostWithWatch).onWatchStatusChange) === null || _b === void 0 ? void 0 : _b.call(_a, ts.createCompilerDiagnostic.apply(void 0, __spreadArray([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
}
function reportErrors(_a, errors) {
var host = _a.host;
return functionKeyword;
}
}
+ function getAncestorTypeNode(node) {
+ var lastTypeNode;
+ ts.findAncestor(node, function (a) {
+ if (ts.isTypeNode(a)) {
+ lastTypeNode = a;
+ }
+ return !ts.isQualifiedName(a.parent) && !ts.isTypeNode(a.parent) && !ts.isTypeElement(a.parent);
+ });
+ return lastTypeNode;
+ }
+ function getContextualTypeOrAncestorTypeNodeType(node, checker) {
+ var contextualType = checker.getContextualType(node);
+ if (contextualType) {
+ return contextualType;
+ }
+ var ancestorTypeNode = getAncestorTypeNode(node);
+ return ancestorTypeNode && checker.getTypeAtLocation(ancestorTypeNode);
+ }
+ ts.getContextualTypeOrAncestorTypeNodeType = getContextualTypeOrAncestorTypeNodeType;
function getAdjustedLocationForDeclaration(node, forRename) {
if (!forRename) {
switch (node.kind) {
}
ts.isInsideJsxElement = isInsideJsxElement;
function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) {
+ var closeTokenText = ts.tokenToString(token.kind);
+ var matchingTokenText = ts.tokenToString(matchingTokenKind);
+ var tokenFullStart = token.getFullStart();
+ // Text-scan based fast path - can be bamboozled by comments and other trivia, but often provides
+ // a good, fast approximation without too much extra work in the cases where it fails.
+ var bestGuessIndex = sourceFile.text.lastIndexOf(matchingTokenText, tokenFullStart);
+ if (bestGuessIndex === -1) {
+ return undefined; // if the token text doesn't appear in the file, there can't be a match - super fast bail
+ }
+ // we can only use the textual result directly if we didn't have to count any close tokens within the range
+ if (sourceFile.text.lastIndexOf(closeTokenText, tokenFullStart - 1) < bestGuessIndex) {
+ var nodeAtGuess = findPrecedingToken(bestGuessIndex + 1, sourceFile);
+ if (nodeAtGuess && nodeAtGuess.kind === matchingTokenKind) {
+ return nodeAtGuess;
+ }
+ }
var tokenKind = token.kind;
var remainingMatchingTokens = 0;
while (true) {
ts.getPossibleGenericSignatures = getPossibleGenericSignatures;
// Get info for an expression like `f <` that may be the start of type arguments.
function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) {
+ // This is a rare case, but one that saves on a _lot_ of work if true - if the source file has _no_ `<` character,
+ // then there obviously can't be any type arguments - no expensive brace-matching backwards scanning required
+ if (sourceFile.text.lastIndexOf("<", tokenIn ? tokenIn.pos : sourceFile.text.length) === -1) {
+ return undefined;
+ }
var token = tokenIn;
// This function determines if the node could be type argument position
// Since during editing, when type argument list is not complete,
// Note: getWidth() does not take trivia into account.
return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0;
}
- function getNodeModifiers(node) {
- var flags = ts.isDeclaration(node) ? ts.getCombinedNodeFlagsAlwaysIncludeJSDoc(node) : 0 /* None */;
+ function getNodeModifiers(node, excludeFlags) {
+ if (excludeFlags === void 0) { excludeFlags = 0 /* None */; }
var result = [];
+ var flags = ts.isDeclaration(node)
+ ? ts.getCombinedNodeFlagsAlwaysIncludeJSDoc(node) & ~excludeFlags
+ : 0 /* None */;
if (flags & 8 /* Private */)
result.push("private" /* privateMemberModifier */);
if (flags & 16 /* Protected */)
155 /* BigIntKeyword */,
131 /* BooleanKeyword */,
94 /* FalseKeyword */,
+ 135 /* InferKeyword */,
138 /* KeyOfKeyword */,
141 /* NeverKeyword */,
103 /* NullKeyword */,
getSourceFiles: function () { return program.getSourceFiles(); },
redirectTargetsMap: program.redirectTargetsMap,
getProjectReferenceRedirect: function (fileName) { return program.getProjectReferenceRedirect(fileName); },
- isSourceOfProjectReferenceRedirect: function (fileName) { return program.isSourceOfProjectReferenceRedirect(fileName); }
+ isSourceOfProjectReferenceRedirect: function (fileName) { return program.isSourceOfProjectReferenceRedirect(fileName); },
+ getNearestAncestorDirectoryWithPackageJson: ts.maybeBind(host, host.getNearestAncestorDirectoryWithPackageJson),
+ getFileIncludeReasons: function () { return program.getFileIncludeReasons(); },
};
}
ts.createModuleSpecifierResolutionHost = createModuleSpecifierResolutionHost;
return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
}
ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement;
- /**
- * Find symbol of the given property-name and add the symbol to the given result array
- * @param symbol a symbol to start searching for the given propertyName
- * @param propertyName a name of property to search for
- * @param result an array of symbol of found property symbols
- * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol.
- * The value of previousIterationSymbol is undefined when the function is first called.
- */
- function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) {
- var seen = new ts.Map();
- return recur(symbol);
- function recur(symbol) {
- // Use `addToSeen` to ensure we don't infinitely recurse in this situation:
- // interface C extends C {
- // /*findRef*/propName: string;
- // }
- if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol)))
- return;
- return ts.firstDefined(symbol.declarations, function (declaration) { return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) {
- var type = checker.getTypeAtLocation(typeReference);
- var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName);
- // Visit the typeReference as well to see if it directly or indirectly uses that property
- return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol));
- }); });
- }
- }
- ts.getPropertySymbolsFromBaseTypes = getPropertySymbolsFromBaseTypes;
- function isMemberSymbolInBaseType(memberSymbol, checker) {
- return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false;
- }
- ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType;
function getParentNodeInSpan(node, file, span) {
if (!node)
return undefined;
*/
function getNewLineOrDefaultFromHost(host, formatSettings) {
var _a;
- return (formatSettings === null || formatSettings === void 0 ? void 0 : formatSettings.newLineCharacter) || ((_a = host.getNewLine) === null || _a === void 0 ? void 0 : _a.call(host)) ||
+ return (formatSettings === null || formatSettings === void 0 ? void 0 : formatSettings.newLineCharacter) ||
+ ((_a = host.getNewLine) === null || _a === void 0 ? void 0 : _a.call(host)) ||
carriageReturnLineFeed;
}
ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost;
// Editors can pass in undefined or empty string - we want to infer the preference in those cases.
var quotePreference = getQuotePreference(sourceFile, preferences);
var quoted = JSON.stringify(text);
- return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'" : quoted;
+ return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"') + "'" : quoted;
}
ts.quote = quote;
function isEqualityOperatorKind(kind) {
}
ts.firstOrOnly = firstOrOnly;
function getNameForExportedSymbol(symbol, scriptTarget) {
- if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) {
+ if (!(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */)) {
// Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase.
- return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; })
+ return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; })
|| ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget);
}
return symbol.name;
// foo({
// '/*completion position*/'
// });
- return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent));
+ return stringLiteralCompletionsForObjectLiteral(typeChecker, parent.parent);
}
return fromContextualType();
case 202 /* ElementAccessExpression */: {
hasIndexSignature: ts.hasIndexSignature(type)
};
}
+ function stringLiteralCompletionsForObjectLiteral(checker, objectLiteralExpression) {
+ var contextualType = checker.getContextualType(objectLiteralExpression);
+ if (!contextualType)
+ return undefined;
+ var completionsType = checker.getContextualType(objectLiteralExpression, 4 /* Completions */);
+ var symbols = Completions.getPropertiesForObjectExpression(contextualType, completionsType, objectLiteralExpression, checker);
+ return {
+ kind: 1 /* Properties */,
+ symbols: symbols,
+ hasIndexSignature: ts.hasIndexSignature(contextualType)
+ };
+ }
function getStringLiteralTypes(type, uniques) {
if (uniques === void 0) { uniques = new ts.Map(); }
if (!type)
}
function addReplacementSpans(text, textStart, names) {
var span = getDirectoryFragmentTextSpan(text, textStart);
+ var wholeSpan = text.length === 0 ? undefined : ts.createTextSpan(textStart, text.length);
return names.map(function (_a) {
var name = _a.name, kind = _a.kind, extension = _a.extension;
- return ({ name: name, kind: kind, extension: extension, span: span });
+ return Math.max(name.indexOf(ts.directorySeparator), name.indexOf(ts.altDirectorySeparator)) !== -1 ? { name: name, kind: kind, extension: extension, span: wholeSpan } : { name: name, kind: kind, extension: extension, span: span };
});
}
function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) {
return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined;
}); // TODO: GH#18217
// Now find a path for each potential directory that is to be merged with the one containing the script
- return ts.deduplicate(__spreadArrays(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), [scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
+ return ts.deduplicate(__spreadArray(__spreadArray([], rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })), [scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
}
function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) {
var basePath = compilerOptions.project || host.getCurrentDirectory();
var name = trimPrefixAndSuffix(dir);
return name === undefined ? undefined : directoryResult(name);
});
- return __spreadArrays(matches, directories);
+ return __spreadArray(__spreadArray([], matches), directories);
function trimPrefixAndSuffix(path) {
var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix);
return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner);
}
// Replace everything after the last directory separator that appears
function getDirectoryFragmentTextSpan(text, textStart) {
- var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\"));
+ var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf(ts.altDirectorySeparator));
var offset = index !== -1 ? index + 1 : 0;
// If the range is an identifier, span is unnecessary.
var length = text.length - offset;
// cache invalidation in synchronizeHostData).
if ((_a = suggestion.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) {
suggestion.symbol = checker.getMergedSymbol(suggestion.origin.isDefaultExport
- ? (_b = suggestion.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : suggestion.symbol.declarations[0].symbol : suggestion.symbol.declarations[0].symbol);
+ ? (_b = suggestion.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : suggestion.symbol.declarations[0].symbol
+ : suggestion.symbol.declarations[0].symbol);
}
if ((_c = suggestion.origin.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) {
suggestion.origin.moduleSymbol = checker.getMergedSymbol(suggestion.origin.moduleSymbol.declarations[0].symbol);
return {
name: name,
kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location),
- kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
+ kindModifiers: ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol),
sortText: sortText,
source: getSourceFromOrigin(origin),
hasAction: origin && originIsExport(origin) || undefined,
var _a = checker.runWithCancellationToken(cancellationToken, function (checker) {
return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */);
}), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags;
- return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay);
+ return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(checker, symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay);
}
Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol;
function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) {
}
function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) {
var typeChecker = program.getTypeChecker();
+ var compilerOptions = program.getCompilerOptions();
var start = ts.timestamp();
var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853
// We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.)
var semanticStart = ts.timestamp();
var completionKind = 5 /* None */;
var isNewIdentifierLocation = false;
+ var isNonContextualObjectLiteral = false;
var keywordFilters = 0 /* None */;
// This also gets mutated in nested-functions after the return
var symbols = [];
keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */;
// Get all entities in the current scope.
completionKind = 1 /* Global */;
- isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
+ isNewIdentifierLocation = isNewIdentifierDefinitionLocation();
if (previousToken !== contextToken) {
ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
}
filterGlobalCompletion(symbols);
}
function shouldOfferImportCompletions() {
+ // If current completion is for non-contextual Object literal shortahands, ignore auto-import symbols
+ if (isNonContextualObjectLiteral)
+ return false;
// If not already a module, must have modules enabled.
if (!preferences.includeCompletionsForModuleExports)
return false;
? 6 /* TypeAssertionKeywords */
: 7 /* TypeKeywords */;
}
+ var variableDeclaration = getVariableDeclaration(location);
ts.filterMutate(symbols, function (symbol) {
if (!ts.isSourceFile(location)) {
// export = /**/ here we want to get all meanings, so any symbol is ok
if (ts.isExportAssignment(location.parent)) {
return true;
}
- symbol = ts.skipAlias(symbol, typeChecker);
+ // Filter out variables from their own initializers
+ // `const a = /* no 'a' here */`
+ if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) {
+ return false;
+ }
+ // External modules can have global export declarations that will be
+ // available as global keywords in all scopes. But if the external module
+ // already has an explicit export and user only wants to user explicit
+ // module imports then the global keywords will be filtered out so auto
+ // import suggestions will win in the completion
+ var symbolOrigin = ts.skipAlias(symbol, typeChecker);
+ // We only want to filter out the global keywords
+ // Auto Imports are not available for scripts so this conditional is always false
+ if (!!sourceFile.externalModuleIndicator
+ && !compilerOptions.allowUmdGlobalAccess
+ && symbolToSortTextMap[ts.getSymbolId(symbol)] === SortText.GlobalsOrKeywords
+ && symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions) {
+ return false;
+ }
+ // Continue with origin symbol
+ symbol = symbolOrigin;
// import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace)
if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) {
return !!(symbol.flags & 1920 /* Namespace */);
return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */);
});
}
+ function getVariableDeclaration(property) {
+ var variableDeclaration = ts.findAncestor(property, function (node) {
+ return ts.isFunctionBlock(node) || isArrowFunctionBody(node) || ts.isBindingPattern(node)
+ ? "quit"
+ : ts.isVariableDeclaration(node);
+ });
+ return variableDeclaration;
+ }
+ function isArrowFunctionBody(node) {
+ return node.parent && ts.isArrowFunction(node.parent) && node.parent.body === node;
+ }
+ ;
function isTypeOnlyCompletion() {
return insideJsDocTagTypeExpression
|| !isContextTokenValueLocation(contextToken) &&
}
return false;
}
- function isNewIdentifierDefinitionLocation(previousToken) {
- if (previousToken) {
- var containingNodeKind = previousToken.parent.kind;
+ function isNewIdentifierDefinitionLocation() {
+ if (contextToken) {
+ var containingNodeKind = contextToken.parent.kind;
// Previous token may have been a keyword that was converted to an identifier.
- switch (keywordForNode(previousToken)) {
+ switch (keywordForNode(contextToken)) {
case 27 /* CommaToken */:
return containingNodeKind === 203 /* CallExpression */ // func( a, |
|| containingNodeKind === 166 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */
|| containingNodeKind === 204 /* NewExpression */ // new C(a, |
|| containingNodeKind === 199 /* ArrayLiteralExpression */ // [a, |
|| containingNodeKind === 216 /* BinaryExpression */ // const x = (a, |
- || containingNodeKind === 174 /* FunctionType */; // var x: (s: string, list|
+ || containingNodeKind === 174 /* FunctionType */ // var x: (s: string, list|
+ || containingNodeKind === 200 /* ObjectLiteralExpression */; // const obj = { x, |
case 20 /* OpenParenToken */:
return containingNodeKind === 203 /* CallExpression */ // func( |
|| containingNodeKind === 166 /* Constructor */ // constructor( |
case 24 /* DotToken */:
return containingNodeKind === 256 /* ModuleDeclaration */; // module A.|
case 18 /* OpenBraceToken */:
- return containingNodeKind === 252 /* ClassDeclaration */; // class A{ |
+ return containingNodeKind === 252 /* ClassDeclaration */ // class A { |
+ || containingNodeKind === 200 /* ObjectLiteralExpression */; // const obj = { |
case 62 /* EqualsToken */:
return containingNodeKind === 249 /* VariableDeclaration */ // const x = a|
|| containingNodeKind === 216 /* BinaryExpression */; // x = a|
var existingMembers;
if (objectLikeContainer.kind === 200 /* ObjectLiteralExpression */) {
var instantiatedType = tryGetObjectLiteralContextualType(objectLikeContainer, typeChecker);
+ // Check completions for Object property value shorthand
if (instantiatedType === undefined) {
- return 2 /* Fail */;
+ if (objectLikeContainer.flags & 16777216 /* InWithStatement */) {
+ return 2 /* Fail */;
+ }
+ isNonContextualObjectLiteral = true;
+ return 0 /* Continue */;
}
var completionsType = typeChecker.getContextualType(objectLikeContainer, 4 /* Completions */);
- isNewIdentifierLocation = ts.hasIndexSignature(completionsType || instantiatedType);
+ var hasStringIndexType = (completionsType || instantiatedType).getStringIndexType();
+ var hasNumberIndextype = (completionsType || instantiatedType).getNumberIndexType();
+ isNewIdentifierLocation = !!hasStringIndexType || !!hasNumberIndextype;
typeMembers = getPropertiesForObjectExpression(instantiatedType, completionsType, objectLikeContainer, typeChecker);
existingMembers = objectLikeContainer.properties;
+ if (typeMembers.length === 0) {
+ // Edge case: If NumberIndexType exists
+ if (!hasNumberIndextype) {
+ isNonContextualObjectLiteral = true;
+ return 0 /* Continue */;
+ }
+ }
}
else {
ts.Debug.assert(objectLikeContainer.kind === 196 /* ObjectBindingPattern */);
case 99 /* ImportKeyword */:
case 118 /* LetKeyword */:
case 84 /* ConstKeyword */:
+ case 135 /* InferKeyword */:
case 149 /* TypeKeyword */: // type htm|
return true;
case 41 /* AsteriskToken */:
return ts.isPropertyDeclaration(contextToken.parent);
}
return ts.isDeclarationName(contextToken)
+ && !ts.isShorthandPropertyAssignment(contextToken.parent)
&& !ts.isJsxAttribute(contextToken.parent)
// Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`.
// If `contextToken !== previousToken`, this is `class C ex/**/`.
return ts.some(member.declarations, function (decl) { return decl.parent !== obj; });
}
}
+ Completions.getPropertiesForObjectExpression = getPropertiesForObjectExpression;
/**
* Gets all properties on a type, but if that type is a union of several types,
* excludes array-like types or callable/constructable types.
case 285 /* DefaultClause */:
// Container is either a class declaration or the declaration is a classDeclaration
if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) {
- return __spreadArrays(declaration.members, [declaration]);
+ return __spreadArray(__spreadArray([], declaration.members), [declaration]);
}
else {
return container.statements;
case 166 /* Constructor */:
case 165 /* MethodDeclaration */:
case 251 /* FunctionDeclaration */:
- return __spreadArrays(container.parameters, (ts.isClassLike(container.parent) ? container.parent.members : []));
+ return __spreadArray(__spreadArray([], container.parameters), (ts.isClassLike(container.parent) ? container.parent.members : []));
case 252 /* ClassDeclaration */:
case 221 /* ClassExpression */:
case 253 /* InterfaceDeclaration */:
if (modifierFlag & (28 /* AccessibilityModifier */ | 64 /* Readonly */)) {
var constructor = ts.find(container.members, ts.isConstructorDeclaration);
if (constructor) {
- return __spreadArrays(nodes, constructor.parameters);
+ return __spreadArray(__spreadArray([], nodes), constructor.parameters);
}
}
else if (modifierFlag & 128 /* Abstract */) {
- return __spreadArrays(nodes, [container]);
+ return __spreadArray(__spreadArray([], nodes), [container]);
}
return nodes;
// Syntactically invalid positions that the parser might produce anyway
cancellationToken.throwIfCancellationRequested();
switch (direct.kind) {
case 203 /* CallExpression */:
+ if (ts.isImportCall(direct)) {
+ handleImportCall(direct);
+ break;
+ }
if (!isAvailableThroughGlobal) {
var parent = direct.parent;
if (exportKind === 2 /* ExportEquals */ && parent.kind === 249 /* VariableDeclaration */) {
}
else if (direct.exportClause.kind === 269 /* NamespaceExport */) {
// `export * as foo from "foo"` add to indirect uses
- addIndirectUsers(getSourceFileLikeForImportDeclaration(direct));
+ addIndirectUser(getSourceFileLikeForImportDeclaration(direct), /** addTransitiveDependencies */ true);
}
else {
// This is `export { foo } from "foo"` and creates an alias symbol, so recursive search will get handle re-exports.
}
break;
case 195 /* ImportType */:
+ // Only check for typeof import('xyz')
+ if (direct.isTypeOf && !direct.qualifier && isExported(direct)) {
+ addIndirectUser(direct.getSourceFile(), /** addTransitiveDependencies */ true);
+ }
directImports.push(direct);
break;
default:
}
}
}
+ function handleImportCall(importCall) {
+ var top = ts.findAncestor(importCall, isAmbientModuleDeclaration) || importCall.getSourceFile();
+ addIndirectUser(top, /** addTransitiveDependencies */ !!isExported(importCall, /** stopAtAmbientModule */ true));
+ }
+ function isExported(node, stopAtAmbientModule) {
+ if (stopAtAmbientModule === void 0) { stopAtAmbientModule = false; }
+ return ts.findAncestor(node, function (node) {
+ if (stopAtAmbientModule && isAmbientModuleDeclaration(node))
+ return "quit";
+ return ts.some(node.modifiers, function (mod) { return mod.kind === 92 /* ExportKeyword */; });
+ });
+ }
function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) {
if (exportKind === 2 /* ExportEquals */) {
// This is a direct import, not import-as-namespace.
var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
ts.Debug.assert(sourceFileLike.kind === 297 /* SourceFile */ || sourceFileLike.kind === 256 /* ModuleDeclaration */);
if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
- addIndirectUsers(sourceFileLike);
+ addIndirectUser(sourceFileLike, /** addTransitiveDependencies */ true);
}
else {
addIndirectUser(sourceFileLike);
}
}
}
- function addIndirectUser(sourceFileLike) {
+ /** Adds a module and all of its transitive dependencies as possible indirect users. */
+ function addIndirectUser(sourceFileLike, addTransitiveDependencies) {
+ if (addTransitiveDependencies === void 0) { addTransitiveDependencies = false; }
ts.Debug.assert(!isAvailableThroughGlobal);
var isNew = markSeenIndirectUser(sourceFileLike);
- if (isNew) {
- indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217
- }
- return isNew;
- }
- /** Adds a module and all of its transitive dependencies as possible indirect users. */
- function addIndirectUsers(sourceFileLike) {
- if (!addIndirectUser(sourceFileLike)) {
+ if (!isNew)
+ return;
+ indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217
+ if (!addTransitiveDependencies)
return;
- }
var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol);
+ if (!moduleSymbol)
+ return;
ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */));
var directImports = getDirectImports(moduleSymbol);
if (directImports) {
for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) {
var directImport = directImports_1[_i];
if (!ts.isImportTypeNode(directImport)) {
- addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport));
+ addIndirectUser(getSourceFileLikeForImportDeclaration(directImport), /** addTransitiveDependencies */ true);
}
}
}
DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword";
DefinitionKind[DefinitionKind["This"] = 3] = "This";
DefinitionKind[DefinitionKind["String"] = 4] = "String";
+ DefinitionKind[DefinitionKind["TripleSlashReference"] = 5] = "TripleSlashReference";
})(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {}));
var EntryKind;
(function (EntryKind) {
|| node.parent.kind === 198 /* BindingElement */
|| node.parent.kind === 202 /* ElementAccessExpression */
|| node.kind === 105 /* SuperKeyword */) {
- referenceEntries = entries && __spreadArrays(entries);
+ referenceEntries = entries && __spreadArray([], entries);
}
else {
- var queue = entries && __spreadArrays(entries);
+ var queue = entries && __spreadArray([], entries);
var seenNodes = new ts.Map();
while (queue && queue.length) {
var entry = queue.shift();
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
var name_1 = displayParts_1.map(function (p) { return p.text; }).join("");
var declaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations);
- return {
- node: declaration ?
- ts.getNameOfDeclaration(declaration) || declaration :
- originalNode,
- name: name_1,
+ var node = declaration ? (ts.getNameOfDeclaration(declaration) || declaration) : originalNode;
+ return __assign(__assign({}, getFileAndTextSpanFromNode(node)), { name: name_1,
kind: kind_1,
- displayParts: displayParts_1,
- context: getContextNode(declaration)
- };
+ displayParts: displayParts_1, context: getContextNode(declaration) });
}
case 1 /* Label */: {
- var node_1 = def.node;
- return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] };
+ var node = def.node;
+ return __assign(__assign({}, getFileAndTextSpanFromNode(node)), { name: node.text, kind: "label" /* label */, displayParts: [ts.displayPart(node.text, ts.SymbolDisplayPartKind.text)] });
}
case 2 /* Keyword */: {
- var node_2 = def.node;
- var name_2 = ts.tokenToString(node_2.kind);
- return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] };
+ var node = def.node;
+ var name_2 = ts.tokenToString(node.kind);
+ return __assign(__assign({}, getFileAndTextSpanFromNode(node)), { name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] });
}
case 3 /* This */: {
- var node_3 = def.node;
- var symbol = checker.getSymbolAtLocation(node_3);
- var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")];
- return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
+ var node = def.node;
+ var symbol = checker.getSymbolAtLocation(node);
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), ts.getContainerNode(node), node).displayParts || [ts.textPart("this")];
+ return __assign(__assign({}, getFileAndTextSpanFromNode(node)), { name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 });
}
case 4 /* String */: {
- var node_4 = def.node;
- return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] };
+ var node = def.node;
+ return __assign(__assign({}, getFileAndTextSpanFromNode(node)), { name: node.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node), ts.SymbolDisplayPartKind.stringLiteral)] });
+ }
+ case 5 /* TripleSlashReference */: {
+ return {
+ textSpan: ts.createTextSpanFromRange(def.reference),
+ sourceFile: def.file,
+ name: def.reference.fileName,
+ kind: "string" /* string */,
+ displayParts: [ts.displayPart("\"" + def.reference.fileName + "\"", ts.SymbolDisplayPartKind.stringLiteral)]
+ };
}
default:
return ts.Debug.assertNever(def);
}
})();
- var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts, context = info.context;
- var sourceFile = node.getSourceFile();
- var textSpan = getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile);
+ var sourceFile = info.sourceFile, textSpan = info.textSpan, name = info.name, kind = info.kind, displayParts = info.displayParts, context = info.context;
return __assign({ containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind,
name: name,
textSpan: textSpan,
displayParts: displayParts }, toContextSpan(textSpan, sourceFile, context));
}
+ function getFileAndTextSpanFromNode(node) {
+ var sourceFile = node.getSourceFile();
+ return {
+ sourceFile: sourceFile,
+ textSpan: getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile)
+ };
+ }
function getDefinitionKindAndDisplayParts(symbol, checker, node) {
var meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol);
var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node;
(function (Core) {
/** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
+ var _a, _b;
if (options === void 0) { options = {}; }
if (sourceFilesSet === void 0) { sourceFilesSet = new ts.Set(sourceFiles.map(function (f) { return f.fileName; })); }
if (options.use === 1 /* References */) {
node = ts.getAdjustedRenameLocation(node);
}
if (ts.isSourceFile(node)) {
- var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program);
- var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol);
- return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
+ var resolvedRef = ts.GoToDefinition.getReferenceAtPosition(node, position, program);
+ if (!resolvedRef) {
+ return undefined;
+ }
+ var moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol);
+ if (moduleSymbol) {
+ return getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
+ }
+ var fileIncludeReasons = program.getFileIncludeReasons();
+ if (!fileIncludeReasons) {
+ return undefined;
+ }
+ return [{
+ definition: { type: 5 /* TripleSlashReference */, reference: resolvedRef.reference, file: node },
+ references: getReferencesForNonModule(resolvedRef.file, fileIncludeReasons, program) || ts.emptyArray
+ }];
}
if (!options.implementations) {
var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
}
}
var checker = program.getTypeChecker();
- var symbol = checker.getSymbolAtLocation(node);
+ // constructors should use the class symbol, detected by name, if present
+ var symbol = checker.getSymbolAtLocation(ts.isConstructorDeclaration(node) && node.parent.name || node);
// Could not find a symbol e.g. unknown identifier
if (!symbol) {
// String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial.
- return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined;
+ if (!options.implementations && ts.isStringLiteralLike(node)) {
+ if (ts.isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ true) || ts.isExternalModuleReference(node.parent) || ts.isImportDeclaration(node.parent) || ts.isImportCall(node.parent)) {
+ var fileIncludeReasons = program.getFileIncludeReasons();
+ var referencedFileName = (_b = (_a = node.getSourceFile().resolvedModules) === null || _a === void 0 ? void 0 : _a.get(node.text)) === null || _b === void 0 ? void 0 : _b.resolvedFileName;
+ var referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : undefined;
+ if (referencedFile) {
+ return [{ definition: { type: 4 /* String */, node: node }, references: getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || ts.emptyArray }];
+ }
+ // Fall through to string literal references. This is not very likely to return
+ // anything useful, but I guess it's better than nothing, and there's an existing
+ // test that expects this to happen (fourslash/cases/untypedModuleImport.ts).
+ }
+ return getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken);
+ }
+ return undefined;
}
if (symbol.escapedName === "export=" /* ExportEquals */) {
return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
return mergeReferences(program, moduleReferences, references, moduleReferencesOfExportTarget);
}
Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
+ function getReferencesForFileName(fileName, program, sourceFiles, sourceFilesSet) {
+ var _a, _b;
+ if (sourceFilesSet === void 0) { sourceFilesSet = new ts.Set(sourceFiles.map(function (f) { return f.fileName; })); }
+ var moduleSymbol = (_a = program.getSourceFile(fileName)) === null || _a === void 0 ? void 0 : _a.symbol;
+ if (moduleSymbol) {
+ return ((_b = getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet)[0]) === null || _b === void 0 ? void 0 : _b.references) || ts.emptyArray;
+ }
+ var fileIncludeReasons = program.getFileIncludeReasons();
+ var referencedFile = program.getSourceFile(fileName);
+ return referencedFile && fileIncludeReasons && getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || ts.emptyArray;
+ }
+ Core.getReferencesForFileName = getReferencesForFileName;
+ function getReferencesForNonModule(referencedFile, refFileMap, program) {
+ var entries;
+ var references = refFileMap.get(referencedFile.path) || ts.emptyArray;
+ for (var _i = 0, references_1 = references; _i < references_1.length; _i++) {
+ var ref = references_1[_i];
+ if (ts.isReferencedFile(ref)) {
+ var referencingFile = program.getSourceFileByPath(ref.file);
+ var location = ts.getReferencedFileLocation(program.getSourceFileByPath, ref);
+ if (ts.isReferenceFileLocation(location)) {
+ entries = ts.append(entries, {
+ kind: 0 /* Span */,
+ fileName: referencingFile.fileName,
+ textSpan: ts.createTextSpanFromRange(location)
+ });
+ }
+ }
+ }
+ return entries;
+ }
function getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker) {
if (node.parent && ts.isNamespaceExportDeclaration(node.parent)) {
var aliasedSymbol = checker.getAliasedSymbol(symbol);
})
};
};
- for (var _b = 0, references_1 = references; _b < references_1.length; _b++) {
- var entry = references_1[_b];
+ for (var _b = 0, references_2 = references; _b < references_2.length; _b++) {
+ var entry = references_2[_b];
_loop_3(entry);
}
}
}
function getSpecialSearchKind(node) {
switch (node.kind) {
+ case 166 /* Constructor */:
case 132 /* ConstructorKeyword */:
return 1 /* Constructor */;
case 78 /* Identifier */:
// within this scope is visible outside the file
return undefined;
}
- // The search scope is the container node
scope = container;
+ if (ts.isFunctionExpression(scope)) {
+ var next = void 0;
+ while (next = ts.getNextJSDocCommentLocation(scope)) {
+ scope = next;
+ }
+ }
}
// If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.)
// For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.:
}
}
Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile;
- function eachSignatureCall(signature, sourceFiles, checker, cb) {
+ function someSignatureUsage(signature, sourceFiles, checker, cb) {
if (!signature.name || !ts.isIdentifier(signature.name))
- return;
+ return false;
var symbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(signature.name));
for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
var sourceFile = sourceFiles_3[_i];
if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText)
continue;
var called = ts.climbPastPropertyAccess(name);
- var call = called.parent;
- if (!ts.isCallExpression(call) || call.expression !== called)
- continue;
+ var call = ts.isCallExpression(called.parent) && called.parent.expression === called ? called.parent : undefined;
var referenceSymbol = checker.getSymbolAtLocation(name);
if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) {
- cb(call);
+ if (cb(name, call)) {
+ return true;
+ }
}
}
}
+ return false;
}
- Core.eachSignatureCall = eachSignatureCall;
+ Core.someSignatureUsage = someSignatureUsage;
function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) {
if (container === void 0) { container = sourceFile; }
return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); });
references: references
}];
}
- function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) {
+ function getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken) {
+ var type = ts.getContextualTypeOrAncestorTypeNodeType(node, checker);
var references = ts.flatMap(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) {
- return ts.isStringLiteral(ref) && ref.text === node.text ? nodeEntry(ref, 2 /* StringLiteral */) : undefined;
+ if (ts.isStringLiteralLike(ref) && ref.text === node.text) {
+ if (type) {
+ var refType = ts.getContextualTypeOrAncestorTypeNodeType(ref, checker);
+ if (type !== checker.getStringType() && type === refType) {
+ return nodeEntry(ref, 2 /* StringLiteral */);
+ }
+ }
+ else {
+ return nodeEntry(ref, 2 /* StringLiteral */);
+ }
+ }
});
});
return [{
return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind)
// Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions
|| (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol)
- ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); })
+ ? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); })
: undefined);
});
}
}
}
}
+ /**
+ * Find symbol of the given property-name and add the symbol to the given result array
+ * @param symbol a symbol to start searching for the given propertyName
+ * @param propertyName a name of property to search for
+ * @param result an array of symbol of found property symbols
+ * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol.
+ * The value of previousIterationSymbol is undefined when the function is first called.
+ */
+ function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) {
+ var seen = new ts.Map();
+ return recur(symbol);
+ function recur(symbol) {
+ // Use `addToSeen` to ensure we don't infinitely recurse in this situation:
+ // interface C extends C {
+ // /*findRef*/propName: string;
+ // }
+ if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol)))
+ return;
+ return ts.firstDefined(symbol.declarations, function (declaration) { return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) {
+ var type = checker.getTypeAtLocation(typeReference);
+ var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName);
+ // Visit the typeReference as well to see if it directly or indirectly uses that property
+ return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol));
+ }); });
+ }
+ }
function isStatic(symbol) {
if (!symbol.valueDeclaration) {
return false;
var toImport = oldFromNew !== undefined
// If we're at the new location (file was already renamed), need to redo module resolution starting from the old location.
// TODO:GH#18217
- ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, allFiles)
+ ? getSourceFileToImportFromResolved(importLiteral, ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, allFiles)
: getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew);
// Need an update if the imported file moved, or the importing file moved and was using a relative path.
return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text)))
var resolved = host.resolveModuleNames
? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName)
: program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName);
- return getSourceFileToImportFromResolved(resolved, oldToNew, program.getSourceFiles());
+ return getSourceFileToImportFromResolved(importLiteral, resolved, oldToNew, program.getSourceFiles());
}
}
- function getSourceFileToImportFromResolved(resolved, oldToNew, sourceFiles) {
+ function getSourceFileToImportFromResolved(importLiteral, resolved, oldToNew, sourceFiles) {
// Search through all locations looking for a moved file, and only then test already existing files.
// This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location.
if (!resolved)
}
// Then failed lookups that are in the list of sources
var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJsonExisting)
- // Then failed lookups except package.json since we dont want to touch them (only included ts/js files)
- || ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
+ // Then failed lookups except package.json since we dont want to touch them (only included ts/js files).
+ // At this point, the confidence level of this fix being correct is too low to change bare specifiers or absolute paths.
+ || ts.pathIsRelative(importLiteral.text) && ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
if (result)
return result;
// If nothing changed, then result is resolved module file thats not updated
var GoToDefinition;
(function (GoToDefinition) {
function getDefinitionAtPosition(program, sourceFile, position) {
- var reference = getReferenceAtPosition(sourceFile, position, program);
- if (reference) {
- return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)];
+ var resolvedRef = getReferenceAtPosition(sourceFile, position, program);
+ if (resolvedRef) {
+ return [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.file.fileName)];
}
var node = ts.getTouchingPropertyName(sourceFile, position);
if (node === sourceFile) {
else {
var defs = getDefinitionFromSymbol(typeChecker, symbol, node, calledDeclaration) || ts.emptyArray;
// For a 'super()' call, put the signature first, else put the variable first.
- return node.kind === 105 /* SuperKeyword */ ? __spreadArrays([sigInfo], defs) : __spreadArrays(defs, [sigInfo]);
+ return node.kind === 105 /* SuperKeyword */ ? __spreadArray([sigInfo], defs) : __spreadArray(__spreadArray([], defs), [sigInfo]);
}
}
// Because name in short-hand property assignment has two different meanings: property name and property value,
return getDefinitionFromSymbol(typeChecker, symbol, node);
}
GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition;
- function isShorthandPropertyAssignmentOfModuleExports(symbol) {
- var shorthandProperty = ts.tryCast(symbol.valueDeclaration, ts.isShorthandPropertyAssignment);
- var binaryExpression = ts.tryCast(shorthandProperty === null || shorthandProperty === void 0 ? void 0 : shorthandProperty.parent.parent, ts.isAssignmentExpression);
- return !!binaryExpression && ts.getAssignmentDeclarationKind(binaryExpression) === 2 /* ModuleExports */;
- }
/**
* True if we should not add definitions for both the signature symbol and the definition symbol.
* True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`.
var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
if (referencePath) {
var file = program.getSourceFileFromReference(sourceFile, referencePath);
- return file && { fileName: referencePath.fileName, file: file };
+ return file && { reference: referencePath, file: file };
}
var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217
- return file && { fileName: typeReferenceDirective.fileName, file: file };
+ return file && { reference: typeReferenceDirective, file: file };
}
var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position);
if (libReferenceDirective) {
var file = program.getLibFileFromReference(libReferenceDirective);
- return file && { fileName: libReferenceDirective.fileName, file: file };
+ return file && { reference: libReferenceDirective, file: file };
}
return undefined;
}
// get the aliased symbol instead. This allows for goto def on an import e.g.
// import {A, B} from "mod";
// to jump to the implementation directly.
- while (symbol) {
- if (symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) {
- var aliased = checker.getAliasedSymbol(symbol);
- if (!aliased.declarations) {
- break;
- }
- symbol = aliased;
- }
- else if (isShorthandPropertyAssignmentOfModuleExports(symbol)) {
- // Skip past `module.exports = { Foo }` even though 'Foo' is not a real alias
- var shorthandTarget = checker.resolveName(symbol.name, symbol.valueDeclaration, 111551 /* Value */, /*excludeGlobals*/ false);
- if (!ts.some(shorthandTarget === null || shorthandTarget === void 0 ? void 0 : shorthandTarget.declarations)) {
- break;
- }
- symbol = shorthandTarget;
- }
- else {
- break;
+ if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) {
+ var aliased = checker.getAliasedSymbol(symbol);
+ if (aliased.declarations) {
+ return aliased;
}
}
return symbol;
kind: "script" /* scriptElement */,
name: name,
containerName: undefined,
- containerKind: undefined,
+ containerKind: undefined, // TODO: GH#18217
};
}
/** Returns a CallLikeExpression where `node` is the target being invoked. */
* @param position The (character-indexed) position in the file where the check should
* be performed.
*/
- function getDocCommentTemplateAtPosition(newLine, sourceFile, position) {
+ function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) {
var tokenAtPos = ts.getTokenAtPosition(sourceFile, position);
var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc);
if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) {
if (!existingDocComment && tokenStart < position) {
return undefined;
}
- var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos);
+ var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options);
if (!commentOwnerInfo) {
return undefined;
}
- var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters;
+ var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters, hasReturn = commentOwnerInfo.hasReturn;
if (commentOwner.getStart(sourceFile) < position) {
return undefined;
}
- if (!parameters || parameters.length === 0) {
- // if there are no parameters, just complete to a single line JSDoc comment
- var singleLineResult = "/** */";
- return { newText: singleLineResult, caretOffset: 3 };
- }
var indentationStr = getIndentationStringAtPosition(sourceFile, position);
+ var isJavaScriptFile = ts.hasJSFileExtension(sourceFile.fileName);
+ var tags = (parameters ? parameterDocComments(parameters || [], isJavaScriptFile, indentationStr, newLine) : "") +
+ (hasReturn ? returnsDocComment(indentationStr, newLine) : "");
// A doc comment consists of the following
// * The opening comment line
// * the first line (without a param) for the object's untagged info (this is also where the caret ends up)
// * the '@param'-tagged lines
+ // * the '@returns'-tag
// * TODO: other tags.
// * the closing comment line
// * if the caret was directly in front of the object, then we add an extra line and indentation.
- var preamble = "/**" + newLine + indentationStr + " * ";
- var result = preamble + newLine +
- parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) +
- indentationStr + " */" +
- (tokenStart === position ? newLine + indentationStr : "");
- return { newText: result, caretOffset: preamble.length };
+ var openComment = "/**";
+ var closeComment = " */";
+ if (tags) {
+ var preamble = openComment + newLine + indentationStr + " * ";
+ var endLine = tokenStart === position ? newLine + indentationStr : "";
+ var result = preamble + newLine + tags + indentationStr + closeComment + endLine;
+ return { newText: result, caretOffset: preamble.length };
+ }
+ return { newText: openComment + closeComment, caretOffset: 3 };
}
JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition;
function getIndentationStringAtPosition(sourceFile, position) {
return indentationStr + " * @param " + type + paramName + newLine;
}).join("");
}
- function getCommentOwnerInfo(tokenAtPos) {
- return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker);
+ function returnsDocComment(indentationStr, newLine) {
+ return indentationStr + " * @returns" + newLine;
+ }
+ function getCommentOwnerInfo(tokenAtPos, options) {
+ return ts.forEachAncestor(tokenAtPos, function (n) { return getCommentOwnerInfoWorker(n, options); });
}
- function getCommentOwnerInfoWorker(commentOwner) {
+ function getCommentOwnerInfoWorker(commentOwner, options) {
switch (commentOwner.kind) {
case 251 /* FunctionDeclaration */:
case 208 /* FunctionExpression */:
case 166 /* Constructor */:
case 164 /* MethodSignature */:
case 209 /* ArrowFunction */:
- var parameters = commentOwner.parameters;
- return { commentOwner: commentOwner, parameters: parameters };
+ var host = commentOwner;
+ return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) };
case 288 /* PropertyAssignment */:
- return getCommentOwnerInfoWorker(commentOwner.initializer);
+ return getCommentOwnerInfoWorker(commentOwner.initializer, options);
case 252 /* ClassDeclaration */:
case 253 /* InterfaceDeclaration */:
case 162 /* PropertySignature */:
case 232 /* VariableStatement */: {
var varStatement = commentOwner;
var varDeclarations = varStatement.declarationList.declarations;
- var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer
- ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer)
+ var host_1 = varDeclarations.length === 1 && varDeclarations[0].initializer
+ ? getRightHandSideOfAssignment(varDeclarations[0].initializer)
: undefined;
- return { commentOwner: commentOwner, parameters: parameters_1 };
+ return host_1
+ ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) }
+ : { commentOwner: commentOwner };
}
case 297 /* SourceFile */:
return "quit";
// want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'.
return commentOwner.parent.kind === 256 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner };
case 233 /* ExpressionStatement */:
- return getCommentOwnerInfoWorker(commentOwner.expression);
+ return getCommentOwnerInfoWorker(commentOwner.expression, options);
case 216 /* BinaryExpression */: {
var be = commentOwner;
if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) {
return "quit";
}
- var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray;
- return { commentOwner: commentOwner, parameters: parameters_2 };
+ return ts.isFunctionLike(be.right)
+ ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) }
+ : { commentOwner: commentOwner };
}
case 163 /* PropertyDeclaration */:
var init = commentOwner.initializer;
if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) {
- return { commentOwner: commentOwner, parameters: init.parameters };
+ return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) };
}
}
}
- /**
- * Digs into an an initializer or RHS operand of an assignment operation
- * to get the parameters of an apt signature corresponding to a
- * function expression or a class expression.
- *
- * @param rightHandSide the expression which may contain an appropriate set of parameters
- * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.
- */
- function getParametersFromRightHandSideOfAssignment(rightHandSide) {
+ function hasReturn(node, options) {
+ return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) &&
+ (ts.isArrowFunction(node) && ts.isExpression(node.body)
+ || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; }));
+ }
+ function getRightHandSideOfAssignment(rightHandSide) {
while (rightHandSide.kind === 207 /* ParenthesizedExpression */) {
rightHandSide = rightHandSide.expression;
}
switch (rightHandSide.kind) {
case 208 /* FunctionExpression */:
case 209 /* ArrowFunction */:
- return rightHandSide.parameters;
- case 221 /* ClassExpression */: {
- var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration);
- return ctr ? ctr.parameters : ts.emptyArray;
- }
+ return rightHandSide;
+ case 221 /* ClassExpression */:
+ return ts.find(rightHandSide.members, ts.isConstructorDeclaration);
}
- return ts.emptyArray;
}
})(JsDoc = ts.JsDoc || (ts.JsDoc = {}));
})(ts || (ts = {}));
textSpan: ts.createTextSpanFromNode(declaration),
// TODO(jfreeman): What should be the containerName when the container has a computed name?
containerName: containerName ? containerName.text : "",
- containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */,
+ containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, // TODO: GH#18217 Just use `container ? ...`
};
}
})(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {}));
addChildrenRecursively(child);
endNode();
}
+ function addNodeWithRecursiveInitializer(node) {
+ if (node.initializer && isFunctionOrClassExpression(node.initializer)) {
+ startNode(node);
+ ts.forEachChild(node.initializer, addChildrenRecursively);
+ endNode();
+ }
+ else {
+ addNodeWithRecursiveChild(node, node.initializer);
+ }
+ }
/** Look for navigation bar items in node's subtree, adding them to the current `parent`. */
function addChildrenRecursively(node) {
var _a;
}
break;
case 163 /* PropertyDeclaration */:
+ if (!ts.hasDynamicName(node)) {
+ addNodeWithRecursiveInitializer(node);
+ }
+ break;
case 162 /* PropertySignature */:
if (!ts.hasDynamicName(node)) {
addLeafNode(node);
break;
case 198 /* BindingElement */:
case 288 /* PropertyAssignment */:
- case 249 /* VariableDeclaration */:
- var _e = node, name = _e.name, initializer = _e.initializer;
- if (ts.isBindingPattern(name)) {
- addChildrenRecursively(name);
- }
- else if (initializer && isFunctionOrClassExpression(initializer)) {
- // Add a node for the VariableDeclaration, but not for the initializer.
- startNode(node);
- ts.forEachChild(initializer, addChildrenRecursively);
- endNode();
+ case 249 /* VariableDeclaration */: {
+ var child = node;
+ if (ts.isBindingPattern(child.name)) {
+ addChildrenRecursively(child.name);
}
else {
- addNodeWithRecursiveChild(node, initializer);
+ addNodeWithRecursiveInitializer(child);
}
break;
+ }
case 251 /* FunctionDeclaration */:
var nameNode = node.name;
// If we see a function declaration track as a possible ES5 class
break;
case 255 /* EnumDeclaration */:
startNode(node);
- for (var _f = 0, _g = node.members; _f < _g.length; _f++) {
- var member = _g[_f];
+ for (var _e = 0, _f = node.members; _e < _f.length; _e++) {
+ var member = _f[_e];
if (!isComputedProperty(member)) {
addLeafNode(member);
}
case 221 /* ClassExpression */:
case 253 /* InterfaceDeclaration */:
startNode(node);
- for (var _h = 0, _j = node.members; _h < _j.length; _h++) {
- var member = _j[_h];
+ for (var _g = 0, _h = node.members; _g < _h.length; _g++) {
+ var member = _h[_g];
addChildrenRecursively(member);
}
endNode();
defineCall.arguments[0] :
defineCall.arguments[0].expression;
var memberName = defineCall.arguments[1];
- var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1];
+ var _j = startNestedNodes(node, className), depth = _j[0], classNameIdentifier = _j[1];
startNode(node, classNameIdentifier);
startNode(node, ts.setTextRange(ts.factory.createIdentifier(memberName.text), memberName));
addChildrenRecursively(node.arguments[2]);
if ((isEs5ClassMember[bAssignmentDeclarationKind] && isEs5ClassMember[aAssignmentDeclarationKind]) // merge two class elements
|| (isPossibleConstructor(a.node) && isEs5ClassMember[bAssignmentDeclarationKind]) // ctor function & member
|| (isPossibleConstructor(b.node) && isEs5ClassMember[aAssignmentDeclarationKind]) // member & ctor function
- || (ts.isClassDeclaration(a.node) && isEs5ClassMember[bAssignmentDeclarationKind]) // class (generated) & member
+ || (ts.isClassDeclaration(a.node) && isSynthesized(a.node) && isEs5ClassMember[bAssignmentDeclarationKind]) // class (generated) & member
|| (ts.isClassDeclaration(b.node) && isEs5ClassMember[aAssignmentDeclarationKind]) // member & class (generated)
- || (ts.isClassDeclaration(a.node) && isPossibleConstructor(b.node)) // class (generated) & ctor
- || (ts.isClassDeclaration(b.node) && isPossibleConstructor(a.node)) // ctor & class (generated)
+ || (ts.isClassDeclaration(a.node) && isSynthesized(a.node) && isPossibleConstructor(b.node)) // class (generated) & ctor
+ || (ts.isClassDeclaration(b.node) && isPossibleConstructor(a.node) && isSynthesized(a.node)) // ctor & class (generated)
) {
var lastANode = a.additionalNodes && ts.lastOrUndefined(a.additionalNodes) || a.node;
if ((!ts.isClassDeclaration(a.node) && !ts.isClassDeclaration(b.node)) // If neither outline node is a class
var ctor = emptyNavigationBarNode(ctorNode);
ctor.indent = a.indent + 1;
ctor.children = a.node === ctorFunction ? a.children : b.children;
- a.children = a.node === ctorFunction ? ts.concatenate([ctor], b.children || [b]) : ts.concatenate(a.children || [a], [ctor]);
+ a.children = a.node === ctorFunction ? ts.concatenate([ctor], b.children || [b]) : ts.concatenate(a.children || [__assign({}, a)], [ctor]);
}
else {
if (a.children || b.children) {
- a.children = ts.concatenate(a.children || [a], b.children || [b]);
+ a.children = ts.concatenate(a.children || [__assign({}, a)], b.children || [b]);
if (a.children) {
mergeChildren(a.children, a);
sortChildren(a.children);
return true;
}
}
+ function isSynthesized(node) {
+ return !!(node.flags & 8 /* Synthesized */);
+ }
// We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }`
// We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };`
function isOwnChild(n, parent) {
return "default";
}
// We may get a string with newlines or other whitespace in the case of an object dereference
- // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the
+ // (eg: "app\n.onactivated"), so we should remove the whitespace for readability in the
// navigation bar.
return getFunctionOrClassName(node);
case 166 /* Constructor */:
function removeUnusedImports(oldImports, sourceFile, program) {
var typeChecker = program.getTypeChecker();
var jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
+ var jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile);
var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
var usedImports = [];
for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
return usedImports;
function isDeclarationUsed(identifier) {
// The JSX factory symbol is always used if JSX elements are present - even if they are not allowed.
- return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
+ return jsxElementsPresent && (identifier.text === jsxNamespace || jsxFragmentFactory && identifier.text === jsxFragmentFactory) ||
+ ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
}
}
function hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier) {
var depthRemaining = 40;
var current = 0;
// Includes the EOF Token so that comments which aren't attached to statements are included
- var statements = __spreadArrays(sourceFile.statements, [sourceFile.endOfFileToken]);
+ var statements = __spreadArray(__spreadArray([], sourceFile.statements), [sourceFile.endOfFileToken]);
var n = statements.length;
while (current < n) {
while (current < n && !ts.isAnyImportSyntax(statements[current])) {
function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) {
var symbol = typeChecker.getSymbolAtLocation(node);
if (!symbol) {
- if (ts.isLabelName(node)) {
+ if (ts.isStringLiteralLike(node)) {
+ var type = ts.getContextualTypeOrAncestorTypeNodeType(node, typeChecker);
+ if (type && ((type.flags & 128 /* StringLiteral */) || ((type.flags & 1048576 /* Union */) && ts.every(type.types, function (type) { return !!(type.flags & 128 /* StringLiteral */); })))) {
+ return getRenameInfoSuccess(node.text, node.text, "string" /* string */, "", node, sourceFile);
+ }
+ }
+ else if (ts.isLabelName(node)) {
var name = ts.getTextOfNode(node);
return getRenameInfoSuccess(name, name, "label" /* label */, "" /* none */, node, sourceFile);
}
: undefined;
var displayName = specifierName || typeChecker.symbolToString(symbol);
var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol);
- return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile);
+ return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), node, sourceFile);
}
function getRenameInfoForModule(node, sourceFile, moduleSymbol) {
if (!ts.isExternalModuleNameRelative(node.text)) {
itemsSeen += item.length;
}
ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function.
- return { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount };
+ var help = { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount };
+ var selected = help.items[selectedItemIndex];
+ if (selected.isVariadic) {
+ var firstRest = ts.findIndex(selected.parameters, function (p) { return !!p.isRest; });
+ if (-1 < firstRest && firstRest < selected.parameters.length - 1) {
+ // We don't have any code to get this correct; instead, don't highlight a current parameter AT ALL
+ help.argumentIndex = selected.parameters.length;
+ }
+ else {
+ help.argumentIndex = Math.min(help.argumentIndex, selected.parameters.length - 1);
+ }
+ }
+ return help;
}
function createTypeHelpItems(symbol, _a, sourceFile, checker) {
var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
var documentation = symbol.getDocumentationComment(checker);
var tags = symbol.getJsDocTags();
- var prefixDisplayParts = __spreadArrays(typeSymbolDisplay, [ts.punctuationPart(29 /* LessThanToken */)]);
+ var prefixDisplayParts = __spreadArray(__spreadArray([], typeSymbolDisplay), [ts.punctuationPart(29 /* LessThanToken */)]);
return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(31 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
}
var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()];
var infos = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile);
return ts.map(infos, function (_a) {
var isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix;
- var prefixDisplayParts = __spreadArrays(callTargetDisplayParts, prefix);
- var suffixDisplayParts = __spreadArrays(suffix, returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker));
+ var prefixDisplayParts = __spreadArray(__spreadArray([], callTargetDisplayParts), prefix);
+ var suffixDisplayParts = __spreadArray(__spreadArray([], suffix), returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker));
var documentation = candidateSignature.getDocumentationComment(checker);
var tags = candidateSignature.getJsDocTags();
return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : [];
return checker.getExpandedParameters(candidateSignature).map(function (paramList) {
- var params = ts.factory.createNodeArray(__spreadArrays(thisParameter, ts.map(paramList, function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
+ var params = ts.factory.createNodeArray(__spreadArray(__spreadArray([], thisParameter), ts.map(paramList, function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
var parameterParts = ts.mapToDisplayParts(function (writer) {
printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer);
});
- return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(29 /* LessThanToken */)], suffix: __spreadArrays([ts.punctuationPart(31 /* GreaterThanToken */)], parameterParts) };
+ return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(29 /* LessThanToken */)], suffix: __spreadArray([ts.punctuationPart(31 /* GreaterThanToken */)], parameterParts) };
});
}
function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
return {
isVariadic: isVariadic && (lists.length === 1 || !!(parameterList[parameterList.length - 1].checkFlags & 32768 /* RestParameter */)),
parameters: parameterList.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }),
- prefix: __spreadArrays(typeParameterParts, [ts.punctuationPart(20 /* OpenParenToken */)]),
+ prefix: __spreadArray(__spreadArray([], typeParameterParts), [ts.punctuationPart(20 /* OpenParenToken */)]),
suffix: [ts.punctuationPart(21 /* CloseParenToken */)]
};
});
printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
});
var isOptional = checker.isOptionalParameter(parameter.valueDeclaration);
- return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional };
+ var isRest = !!(parameter.checkFlags & 32768 /* RestParameter */);
+ return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional, isRest: isRest };
}
function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) {
var displayParts = ts.mapToDisplayParts(function (writer) {
var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags);
printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
});
- return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false };
+ return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false, isRest: false };
}
})(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {}));
})(ts || (ts = {}));
return !ts.isAsyncFunction(node) &&
node.body &&
ts.isBlock(node.body) &&
- hasReturnStatementWithPromiseHandler(node.body) &&
+ hasReturnStatementWithPromiseHandler(node.body, checker) &&
returnsPromise(node, checker);
}
function returnsPromise(node, checker) {
function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) {
return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator;
}
- function hasReturnStatementWithPromiseHandler(body) {
- return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler);
+ function hasReturnStatementWithPromiseHandler(body, checker) {
+ return !!ts.forEachReturnStatement(body, function (statement) { return isReturnStatementWithFixablePromiseHandler(statement, checker); });
}
- function isReturnStatementWithFixablePromiseHandler(node) {
- return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression);
+ function isReturnStatementWithFixablePromiseHandler(node, checker) {
+ return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker);
}
ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler;
// Should be kept up to date with transformExpression in convertToAsyncFunction.ts
- function isFixablePromiseHandler(node) {
+ function isFixablePromiseHandler(node, checker) {
// ensure outermost call exists and is a promise handler
- if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) {
+ if (!isPromiseHandler(node) || !node.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) {
return false;
}
// ensure all chained calls are valid
var currentNode = node.expression;
while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) {
- if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) {
+ if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) {
return false;
}
currentNode = currentNode.expression;
});
}
// should be kept up to date with getTransformationBody in convertToAsyncFunction.ts
- function isFixablePromiseArgument(arg) {
+ function isFixablePromiseArgument(arg, checker) {
switch (arg.kind) {
case 251 /* FunctionDeclaration */:
case 208 /* FunctionExpression */:
visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true);
// falls through
case 103 /* NullKeyword */:
- case 78 /* Identifier */: // identifier includes undefined
return true;
+ case 78 /* Identifier */:
+ case 201 /* PropertyAccessExpression */: {
+ var symbol = checker.getSymbolAtLocation(arg);
+ if (!symbol) {
+ return false;
+ }
+ return checker.isUndefinedSymbol(symbol) ||
+ ts.some(ts.skipAlias(symbol, checker).declarations, function (d) { return ts.isFunctionLike(d) || ts.hasInitializer(d) && !!d.initializer && ts.isFunctionLike(d.initializer); });
+ }
default:
return false;
}
if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) {
return "property" /* memberVariableElement */;
}
- // May be a Function if this was from `typeof N` with `namespace N { function f();. }`.
- ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */)));
});
if (!unionPropertyKind) {
// If this was union of all methods,
}
return "" /* unknown */;
}
- function getSymbolModifiers(symbol) {
- var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0
- ? ts.getNodeModifiers(symbol.declarations[0])
- : "" /* none */;
- var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ?
- "optional" /* optionalModifier */
- : "" /* none */;
- return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers;
+ function isDeprecatedDeclaration(decl) {
+ return !!(ts.getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & 8192 /* Deprecated */);
+ }
+ function getNormalizedSymbolModifiers(symbol) {
+ if (symbol.declarations && symbol.declarations.length) {
+ var _a = symbol.declarations, declaration = _a[0], declarations = _a.slice(1);
+ // omit deprecated flag if some declarations are not deprecated
+ var excludeFlags = ts.length(declarations) && isDeprecatedDeclaration(declaration) && ts.some(declarations, function (d) { return !isDeprecatedDeclaration(d); })
+ ? 8192 /* Deprecated */
+ : 0 /* None */;
+ var modifiers = ts.getNodeModifiers(declaration, excludeFlags);
+ if (modifiers) {
+ return modifiers.split(",");
+ }
+ }
+ return [];
+ }
+ function getSymbolModifiers(typeChecker, symbol) {
+ if (!symbol) {
+ return "" /* none */;
+ }
+ var modifiers = new ts.Set(getNormalizedSymbolModifiers(symbol));
+ if (symbol.flags & 2097152 /* Alias */) {
+ var resolvedSymbol = typeChecker.getAliasedSymbol(symbol);
+ if (resolvedSymbol !== symbol) {
+ ts.forEach(getNormalizedSymbolModifiers(resolvedSymbol), function (modifier) {
+ modifiers.add(modifier);
+ });
+ }
+ }
+ if (symbol.flags & 16777216 /* Optional */) {
+ modifiers.add("optional" /* optionalModifier */);
+ }
+ return modifiers.size > 0 ? ts.arrayFrom(modifiers.values()).join(",") : "" /* none */;
}
SymbolDisplay.getSymbolModifiers = getSymbolModifiers;
// TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location
pushSymbolKind(symbolKind);
displayParts.push(ts.spacePart());
if (useConstructSignatures) {
+ if (signature.flags & 4 /* Abstract */) {
+ displayParts.push(ts.keywordPart(125 /* AbstractKeyword */));
+ displayParts.push(ts.spacePart());
+ }
displayParts.push(ts.keywordPart(102 /* NewKeyword */));
displayParts.push(ts.spacePart());
}
displayParts.push(ts.lineBreakPart());
}
if (useConstructSignatures) {
+ if (signature.flags & 4 /* Abstract */) {
+ displayParts.push(ts.keywordPart(125 /* AbstractKeyword */));
+ displayParts.push(ts.spacePart());
+ }
displayParts.push(ts.keywordPart(102 /* NewKeyword */));
displayParts.push(ts.spacePart());
}
documentationFromAlias = resolvedInfo.documentation;
tagsFromAlias = resolvedInfo.tags;
}
+ else {
+ documentationFromAlias = resolvedSymbol.getContextualDocumentationComment(resolvedNode, typeChecker);
+ tagsFromAlias = resolvedSymbol.getJsDocTags();
+ }
}
}
switch (symbol.declarations[0].kind) {
return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false };
}
var anyToken = { tokens: allTokens, isSpecific: false };
- var anyTokenIncludingMultilineComments = tokenRangeFrom(__spreadArrays(allTokens, [3 /* MultiLineCommentTrivia */]));
- var anyTokenIncludingEOF = tokenRangeFrom(__spreadArrays(allTokens, [1 /* EndOfFileToken */]));
+ var anyTokenIncludingMultilineComments = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens), [3 /* MultiLineCommentTrivia */]));
+ var anyTokenIncludingEOF = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens), [1 /* EndOfFileToken */]));
var keywords = tokenRangeFromRange(80 /* FirstKeyword */, 156 /* LastKeyword */);
var binaryOperators = tokenRangeFromRange(29 /* FirstBinaryOperator */, 77 /* LastBinaryOperator */);
var binaryKeywordOperators = [100 /* InKeyword */, 101 /* InstanceOfKeyword */, 156 /* OfKeyword */, 126 /* AsKeyword */, 137 /* IsKeyword */];
var unaryPredecrementExpressions = [78 /* Identifier */, 20 /* OpenParenToken */, 107 /* ThisKeyword */, 102 /* NewKeyword */];
var unaryPostdecrementExpressions = [78 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 102 /* NewKeyword */];
var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */];
- var typeNames = __spreadArrays([78 /* Identifier */], ts.typeKeywords);
+ var typeNames = __spreadArray([78 /* Identifier */], ts.typeKeywords);
// Place a space before open brace in a function declaration
// TypeScript: Function can have return types, which can be made of tons of different token kinds
var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments;
// This low-pri rule takes care of "try {", "catch {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter.
rule("SpaceAfterTryCatchFinally", [110 /* TryKeyword */, 82 /* CatchKeyword */, 95 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
];
- return __spreadArrays(highPriorityCommonRules, userConfigurableRules, lowPriorityCommonRules);
+ return __spreadArray(__spreadArray(__spreadArray([], highPriorityCommonRules), userConfigurableRules), lowPriorityCommonRules);
}
formatting.getAllRules = getAllRules;
/**
processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
}
if (!formattingScanner.isOnToken()) {
+ var indentation = formatting.SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ undefined, sourceFile, /*indentByDefault*/ false)
+ ? initialIndentation + options.indentSize
+ : initialIndentation;
var leadingTrivia = formattingScanner.getCurrentLeadingTrivia();
if (leadingTrivia) {
- indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); });
- if (options.trimTrailingWhitespace !== false) {
- trimTrailingWhitespacesForRemainingRange();
- }
+ indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); });
}
}
+ if (options.trimTrailingWhitespace !== false) {
+ trimTrailingWhitespacesForRemainingRange();
+ }
return edits;
// local functions
/** Tries to compute the indentation for a list element.
// - we need to get the indentation on last line and the delta of parent
return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) };
}
- else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
- return { indentation: parentDynamicIndentation.getIndentation(), delta: delta };
- }
- else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) {
+ else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile) ||
+ formatting.SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent, node, startLine, sourceFile) ||
+ formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) {
return { indentation: parentDynamicIndentation.getIndentation(), delta: delta };
}
else {
case 275 /* JsxOpeningElement */:
case 276 /* JsxClosingElement */:
case 274 /* JsxSelfClosingElement */:
+ case 223 /* ExpressionWithTypeArguments */:
return false;
}
break;
}
SmartIndenter.getBaseIndentation = getBaseIndentation;
function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) {
+ var _a;
var parent = current.parent;
// Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if
// * parent and child nodes start on the same line, or
childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile);
if (useActualIndentation) {
// check if current node is a list item - if yes, take indentation from it
- var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine);
+ var firstListChild = (_a = getContainingList(current, sourceFile)) === null || _a === void 0 ? void 0 : _a[0];
+ // A list indents its children if the children begin on a later line than the list itself:
+ //
+ // f1( L0 - List start
+ // { L1 - First child start: indented, along with all other children
+ // prop: 0
+ // },
+ // {
+ // prop: 1
+ // }
+ // )
+ //
+ // f2({ L0 - List start and first child start: children are not indented.
+ // prop: 0 Object properties are indented only one level, because the list
+ // }, { itself contributes nothing.
+ // prop: 1 L3 - The indentation of the second object literal is best understood by
+ // }) looking at the relationship between the list and *first* list item.
+ var listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line;
+ var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild);
if (actualIndentation !== -1 /* Unknown */) {
return actualIndentation + indentationDelta;
}
return false;
}
SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement;
+ // A multiline conditional typically increases the indentation of its whenTrue and whenFalse children:
+ //
+ // condition
+ // ? whenTrue
+ // : whenFalse;
+ //
+ // However, that indentation does not apply if the subexpressions themselves span multiple lines,
+ // applying their own indentation:
+ //
+ // (() => {
+ // return complexCalculationForCondition();
+ // })() ? {
+ // whenTrue: 'multiline object literal'
+ // } : (
+ // whenFalse('multiline parenthesized expression')
+ // );
+ //
+ // In these cases, we must discard the indentation increase that would otherwise be applied to the
+ // whenTrue and whenFalse children to avoid double-indenting their contents. To identify this scenario,
+ // we check for the whenTrue branch beginning on the line that the condition ends, and the whenFalse
+ // branch beginning on the line that the whenTrue branch ends.
+ function childIsUnindentedBranchOfConditionalExpression(parent, child, childStartLine, sourceFile) {
+ if (ts.isConditionalExpression(parent) && (child === parent.whenTrue || child === parent.whenFalse)) {
+ var conditionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.condition.end).line;
+ if (child === parent.whenTrue) {
+ return childStartLine === conditionEndLine;
+ }
+ else {
+ // On the whenFalse side, we have to look at the whenTrue side, because if that one was
+ // indented, whenFalse must also be indented:
+ //
+ // const y = true
+ // ? 1 : ( L1: whenTrue indented because it's on a new line
+ // 0 L2: indented two stops, one because whenTrue was indented
+ // ); and one because of the parentheses spanning multiple lines
+ var trueStartLine = getStartLineAndCharacterForNode(parent.whenTrue, sourceFile).line;
+ var trueEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.whenTrue.end).line;
+ return conditionEndLine === trueStartLine && trueEndLine === childStartLine;
+ }
+ }
+ return false;
+ }
+ SmartIndenter.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression;
function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) {
if (ts.isCallOrNewExpression(parent)) {
if (!parent.arguments)
if (childKind === 177 /* TypeLiteral */ || childKind === 179 /* TupleType */) {
return false;
}
- // falls through
+ break;
}
// No explicit rule for given nodes so the result will follow the default value argument
return indentByDefault;
if (options === void 0) { options = {}; }
this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween));
};
- ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
- var pos = before.getStart(sourceFile);
- this.insertNodeAt(sourceFile, pos, ts.factory.createToken(modifier), { suffix: " " });
+ ChangeTracker.prototype.insertModifierAt = function (sourceFile, pos, modifier, options) {
+ if (options === void 0) { options = {}; }
+ this.insertNodeAt(sourceFile, pos, ts.factory.createToken(modifier), options);
};
- ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) {
- if (!before.modifiers) {
- this.insertModifierBefore(sourceFile, modifier, before);
- return;
- }
- var pos = before.modifiers.end;
- this.insertNodeAt(sourceFile, pos, ts.factory.createToken(modifier), { prefix: " " });
+ ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
+ return this.insertModifierAt(sourceFile, before.getStart(sourceFile), modifier, { suffix: " " });
};
ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) {
var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile);
ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) {
var firstStatement = ts.firstOrUndefined(ctr.body.statements);
if (!firstStatement || !ctr.body.multiLine) {
- this.replaceConstructorBody(sourceFile, ctr, __spreadArrays([newStatement], ctr.body.statements));
+ this.replaceConstructorBody(sourceFile, ctr, __spreadArray([newStatement], ctr.body.statements));
}
else {
this.insertNodeBefore(sourceFile, firstStatement, newStatement);
ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) {
var lastStatement = ts.lastOrUndefined(ctr.body.statements);
if (!lastStatement || !ctr.body.multiLine) {
- this.replaceConstructorBody(sourceFile, ctr, __spreadArrays(ctr.body.statements, [newStatement]));
+ this.replaceConstructorBody(sourceFile, ctr, __spreadArray(__spreadArray([], ctr.body.statements), [newStatement]));
}
else {
this.insertNodeAfter(sourceFile, lastStatement, newStatement);
var _loop_9 = function (sourceFile, node) {
if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) {
if (ts.isArray(node)) {
- this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node));
+ this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node));
}
else {
deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node);
codefix.eachDiagnostic = eachDiagnostic;
function getDiagnostics(_a) {
var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken;
- return __spreadArrays(program.getSemanticDiagnostics(sourceFile, cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken));
+ return __spreadArray(__spreadArray(__spreadArray([], program.getSemanticDiagnostics(sourceFile, cancellationToken)), program.getSyntacticDiagnostics(sourceFile, cancellationToken)), ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken));
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
refactor_1.registerRefactor = registerRefactor;
function getApplicableRefactors(context) {
return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) {
- return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context);
+ var _a;
+ return context.cancellationToken && context.cancellationToken.isCancellationRequested() ||
+ !((_a = refactor.kinds) === null || _a === void 0 ? void 0 : _a.some(function (kind) { return refactor_1.refactorKindBeginsWith(kind, context.kind); })) ? undefined :
+ refactor.getAvailableActions(context);
}));
}
refactor_1.getApplicableRefactors = getApplicableRefactors;
var codefix;
(function (codefix) {
codefix.registerCodeFix({
- errorCodes: [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.code],
+ errorCodes: [
+ 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.code,
+ ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code,
+ ],
getCodeActions: function (context) {
var sourceFile = context.sourceFile;
var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
ts.Diagnostics.This_expression_is_not_callable.code,
ts.Diagnostics.This_expression_is_not_constructable.code,
];
- var errorCodes = __spreadArrays([
+ var errorCodes = __spreadArray([
ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type.code,
ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
codefix.registerCodeFix({
errorCodes: errorCodes,
getCodeActions: function (context) {
- var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); });
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
+ return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions());
+ });
return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)];
},
fixIds: [fixId],
- getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); },
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) {
+ return doChange(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions());
+ }); },
});
- function doChange(changes, sourceFile, position, checker) {
+ function doChange(changes, sourceFile, position, checker, preferences, compilerOptions) {
var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position));
if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
// Bad input
// Right now the only thing we can convert are function expressions, get/set accessors and methods
// other values like normal value fields ({a: 1}) shouldn't get transformed.
// We can update this once ES public class properties are available.
- if (ts.isPropertyAccessExpression(_target)) {
- if (isConstructorAssignment(_target))
+ if (ts.isAccessExpression(_target)) {
+ if (ts.isPropertyAccessExpression(_target) && isConstructorAssignment(_target))
return true;
return ts.isFunctionLike(source);
}
return members;
}
// f.x = expr
- if (ts.isPropertyAccessExpression(memberDeclaration) && (ts.isFunctionExpression(assignmentExpr) || ts.isArrowFunction(assignmentExpr))) {
- return createFunctionLikeExpressionMember(members, assignmentExpr, memberDeclaration.name);
+ if (ts.isAccessExpression(memberDeclaration) && (ts.isFunctionExpression(assignmentExpr) || ts.isArrowFunction(assignmentExpr))) {
+ var quotePreference = ts.getQuotePreference(sourceFile, preferences);
+ var name = tryGetPropertyName(memberDeclaration, compilerOptions, quotePreference);
+ if (name) {
+ return createFunctionLikeExpressionMember(members, assignmentExpr, name);
+ }
+ return members;
}
// f.prototype = { ... }
else if (ts.isObjectLiteralExpression(assignmentExpr)) {
return true;
return false;
}
+ function tryGetPropertyName(node, compilerOptions, quotePreference) {
+ if (ts.isPropertyAccessExpression(node)) {
+ return node.name;
+ }
+ var propName = node.argumentExpression;
+ if (ts.isNumericLiteral(propName)) {
+ return propName;
+ }
+ if (ts.isStringLiteralLike(propName)) {
+ return ts.isIdentifierText(propName.text, compilerOptions.target) ? ts.factory.createIdentifier(propName.text)
+ : ts.isNoSubstitutionTemplateLiteral(propName) ? ts.factory.createStringLiteral(propName.text, quotePreference === 0 /* Single */)
+ : propName;
+ }
+ return undefined;
+ }
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
errorCodes: errorCodes,
getCodeActions: function (context) {
codeActionSucceeded = true;
- var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); });
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); });
return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : [];
},
fixIds: [fixId],
- getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); },
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker()); }); },
});
var SynthBindingNameKind;
(function (SynthBindingNameKind) {
SynthBindingNameKind[SynthBindingNameKind["Identifier"] = 0] = "Identifier";
SynthBindingNameKind[SynthBindingNameKind["BindingPattern"] = 1] = "BindingPattern";
})(SynthBindingNameKind || (SynthBindingNameKind = {}));
- function convertToAsyncFunction(changes, sourceFile, position, checker, context) {
+ function convertToAsyncFunction(changes, sourceFile, position, checker) {
// get the function declaration - returns a promise
var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position);
var functionToConvert;
var synthNamesMap = new ts.Map();
var isInJavascript = ts.isInJSFile(functionToConvert);
var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker);
- var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context.sourceFile);
- var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray;
+ var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap);
+ var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray;
var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript };
if (!returnStatements.length) {
return;
}
- // add the async keyword
- changes.insertLastModifierBefore(sourceFile, 129 /* AsyncKeyword */, functionToConvert);
+ var pos = functionToConvert.modifiers ? functionToConvert.modifiers.end :
+ functionToConvert.decorators ? ts.skipTrivia(sourceFile.text, functionToConvert.decorators.end) :
+ functionToConvert.getStart(sourceFile);
+ var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " };
+ changes.insertModifierAt(sourceFile, pos, 129 /* AsyncKeyword */, options);
var _loop_12 = function (returnStatement) {
ts.forEachChild(returnStatement, function visit(node) {
if (ts.isCallExpression(node)) {
_loop_12(returnStatement);
}
}
- function getReturnStatementsWithPromiseHandlers(body) {
+ function getReturnStatementsWithPromiseHandlers(body, checker) {
var res = [];
ts.forEachReturnStatement(body, function (ret) {
- if (ts.isReturnStatementWithFixablePromiseHandler(ret))
+ if (ts.isReturnStatementWithFixablePromiseHandler(ret, checker))
res.push(ret);
});
return res;
return false;
return !!checker.getPromisedTypeOfPromise(checker.getTypeAtLocation(node));
}
- function declaredInFile(symbol, sourceFile) {
- return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile;
- }
/*
- Renaming of identifiers may be neccesary as the refactor changes scopes -
+ Renaming of identifiers may be necessary as the refactor changes scopes -
This function collects all existing identifier names and names of identifiers that will be created in the refactor.
It then checks for any collisions and renames them through getSynthesizedDeepClone
*/
- function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, sourceFile) {
+ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap) {
var identsToRenameMap = new ts.Map(); // key is the symbol id
var collidingSymbolMap = ts.createMultiMap();
ts.forEachChild(nodeToRename, function visit(node) {
return;
}
var symbol = checker.getSymbolAtLocation(node);
- var isDefinedInFile = symbol && declaredInFile(symbol, sourceFile);
- if (symbol && isDefinedInFile) {
+ if (symbol) {
var type = checker.getTypeAtLocation(node);
// Note - the choice of the last call signature is arbitrary
var lastCallSignature = getLastCallSignature(type, checker);
return transformThen(node, transformer, prevArgName);
}
if (isPromiseReturningCallExpression(node, transformer.checker, "catch")) {
- if (node.arguments.length === 0)
- return silentFail();
return transformCatch(node, transformer, prevArgName);
}
if (ts.isPropertyAccessExpression(node)) {
return silentFail();
}
function transformCatch(node, transformer, prevArgName) {
- var func = node.arguments[0];
- var argName = getArgBindingName(func, transformer);
+ var func = ts.singleOrUndefined(node.arguments);
+ var argName = func ? getArgBindingName(func, transformer) : undefined;
var possibleNameForVarDecl;
- /*
- If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block)
- To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap
- We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step
- */
+ // If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block)
+ // To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap
+ // We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step
if (prevArgName && !shouldReturn(node, transformer)) {
if (isSynthIdentifier(prevArgName)) {
possibleNameForVarDecl = prevArgName;
possibleNameForVarDecl.hasBeenDeclared = true;
}
var tryBlock = ts.factory.createBlock(transformExpression(node.expression, transformer, possibleNameForVarDecl));
- var transformationBody = getTransformationBody(func, possibleNameForVarDecl, argName, node, transformer);
+ var transformationBody = func ? getTransformationBody(func, possibleNameForVarDecl, argName, node, transformer) : ts.emptyArray;
var catchArg = argName ? isSynthIdentifier(argName) ? argName.identifier.text : argName.bindingPattern : "e";
var catchVariableDeclaration = ts.factory.createVariableDeclaration(catchArg);
var catchClause = ts.factory.createCatchClause(catchVariableDeclaration, ts.factory.createBlock(transformationBody));
- /*
- In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block)
- */
+ // In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block)
var varDeclList;
var varDeclIdentifier;
if (possibleNameForVarDecl && !shouldReturn(node, transformer)) {
function maybeAnnotateAndReturn(expressionToReturn, typeAnnotation) {
if (typeAnnotation && expressionToReturn) {
var name = ts.factory.createUniqueName("result", 16 /* Optimistic */);
- return __spreadArrays(createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation), [
+ return __spreadArray(__spreadArray([], createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation)), [
ts.factory.createReturnStatement(name)
]);
}
case 103 /* NullKeyword */:
// do not produce a transformed statement for a null argument
break;
+ case 201 /* PropertyAccessExpression */:
case 78 /* Identifier */: // identifier includes undefined
if (!argName) {
// undefined was argument passed to promise handler
var statement = _f[_i];
if (ts.isReturnStatement(statement)) {
seenReturnStatement = true;
- if (ts.isReturnStatementWithFixablePromiseHandler(statement)) {
+ if (ts.isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) {
refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName));
}
else {
: removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement);
}
else {
- var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray;
+ var innerRetStmts = ts.isFixablePromiseHandler(funcBody, transformer.checker) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray;
var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName);
if (innerCbBody.length > 0) {
return innerCbBody;
else if (ts.isIdentifier(funcNode)) {
name = getMapEntryOrDefault(funcNode);
}
+ else if (ts.isPropertyAccessExpression(funcNode) && ts.isIdentifier(funcNode.name)) {
+ name = getMapEntryOrDefault(funcNode.name);
+ }
// return undefined argName when arg is null or undefined
// eslint-disable-next-line no-in-operator
if (!name || "identifier" in name && name.identifier.text === "undefined") {
(function (ts) {
var codefix;
(function (codefix) {
- var errorCodes = [ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error.code];
+ var errorCodes = [ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error.code];
var fixId = "convertToTypeOnlyImport";
codefix.registerCodeFix({
errorCodes: errorCodes,
})(ImportKind || (ImportKind = {}));
function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) {
var compilerOptions = program.getCompilerOptions();
- var exportInfos = getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true);
+ var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name))
+ ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, sourceFile, program, host)]
+ : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true);
var useRequire = shouldUseRequire(sourceFile, program);
var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position));
- var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier;
+ var moduleSpecifier = getBestFix(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences), sourceFile, program, host).moduleSpecifier;
var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences);
return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) };
}
function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) {
ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol");
// We sort the best codefixes first, so taking `first` is best.
- return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences));
+ return getBestFix(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences), sourceFile, program, host);
}
function codeFixActionToCodeAction(_a) {
var description = _a.description, changes = _a.changes, commands = _a.commands;
return { description: description, changes: changes, commands: commands };
}
+ function getSymbolExportInfoForSymbol(symbol, moduleSymbol, importingFile, program, host) {
+ var _a, _b;
+ var compilerOptions = program.getCompilerOptions();
+ var mainProgramInfo = getInfoWithChecker(program.getTypeChecker());
+ if (mainProgramInfo) {
+ return mainProgramInfo;
+ }
+ var autoImportProvider = (_b = (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getTypeChecker();
+ return ts.Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider), "Could not find symbol in specified module for code actions");
+ function getInfoWithChecker(checker) {
+ var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions);
+ if (defaultInfo && ts.skipAlias(defaultInfo.symbol, checker) === symbol) {
+ return { moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) };
+ }
+ var named = checker.tryGetMemberInModuleExportsAndProperties(symbol.name, moduleSymbol);
+ if (named && ts.skipAlias(named, checker) === symbol) {
+ return { moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) };
+ }
+ }
+ }
function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, host, program, useAutoImportProvider) {
var result = [];
var compilerOptions = program.getCompilerOptions();
var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position));
// Don't bother providing an action to add a new import if we can add to an existing one.
var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences);
- return __spreadArrays((useNamespace ? [useNamespace] : ts.emptyArray), addImport);
+ return __spreadArray(__spreadArray([], (useNamespace ? [useNamespace] : ts.emptyArray)), addImport);
}
function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) {
// It is possible that multiple import statements with the same specifier exist in the file.
function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) {
var isJs = ts.isSourceFileJS(sourceFile);
var compilerOptions = program.getCompilerOptions();
- var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier;
- var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) {
+ return ts.flatMap(moduleSymbols, function (_a) {
var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly;
- return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences)
+ return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences)
.map(function (moduleSpecifier) {
// `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types.
return exportedSymbolIsTypeOnly && isJs
: { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport };
});
});
- // Sort by presence in package.json, then shortest paths first
- return ts.sort(choicesForEachExportingModule, function (a, b) {
- var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier);
- var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier);
- if (allowsImportingA && !allowsImportingB) {
- return -1;
- }
- if (allowsImportingB && !allowsImportingA) {
- return 1;
- }
- return a.moduleSpecifier.length - b.moduleSpecifier.length;
- });
}
function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) {
var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); });
var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code
? getFixesInfoForUMDImport(context, symbolToken)
: ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined;
- return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) });
+ return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, context.host) });
+ }
+ function sortFixes(fixes, sourceFile, program, host) {
+ var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier;
+ return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, allowsImportingSpecifier); });
+ }
+ function getBestFix(fixes, sourceFile, program, host) {
+ // These will always be placed first if available, and are better than other kinds
+ if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) {
+ return fixes[0];
+ }
+ var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier;
+ return fixes.reduce(function (best, fix) {
+ return compareModuleSpecifiers(fix, best, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best;
+ });
+ }
+ function compareModuleSpecifiers(a, b, allowsImportingSpecifier) {
+ if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) {
+ return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier))
+ || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier);
+ }
+ return 0 /* EqualTo */;
}
function getFixesInfoForUMDImport(_a, token) {
var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences;
if (!exported)
return undefined;
var symbol = exported.symbol, kind = exported.kind;
- var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions);
+ var info = getDefaultExportInfoWorker(symbol, checker, compilerOptions);
return info && __assign({ symbol: symbol, kind: kind }, info);
}
function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) {
// allowSyntheticDefaultImports/esModuleInterop is enabled.
return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */;
}
- function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) {
+ function getDefaultExportInfoWorker(defaultExport, checker, compilerOptions) {
var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport);
if (localSymbol)
return { symbolForMeaning: localSymbol, name: localSymbol.name };
// but we can still offer completions for it.
// - `aliased.parent` will be undefined if the module is exporting `globalThis.something`,
// or another expression that resolves to a global.
- return getDefaultExportInfoWorker(aliased, aliased.parent, checker, compilerOptions);
+ return getDefaultExportInfoWorker(aliased, checker, compilerOptions);
}
}
if (defaultExport.escapedName !== "default" /* Default */ &&
defaultExport.escapedName !== "export=" /* ExportEquals */) {
return { symbolForMeaning: defaultExport, name: defaultExport.getName() };
}
- return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) };
+ return { symbolForMeaning: defaultExport, name: ts.getNameForExportedSymbol(defaultExport, compilerOptions.target) };
}
function getNameForExportDefault(symbol) {
return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) {
+ var _a;
if (ts.isExportAssignment(declaration)) {
- if (ts.isIdentifier(declaration.expression)) {
- return declaration.expression.text;
- }
+ return (_a = ts.tryCast(ts.skipOuterExpressions(declaration.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text;
}
else if (ts.isExportSpecifier(declaration)) {
ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export");
var declaration = namespaceLikeImport.importKind === 3 /* CommonJS */
? ts.factory.createImportEqualsDeclaration(
/*decorators*/ undefined,
- /*modifiers*/ undefined, ts.factory.createIdentifier(namespaceLikeImport.name), ts.factory.createExternalModuleReference(quotedModuleSpecifier))
+ /*modifiers*/ undefined, typeOnly, ts.factory.createIdentifier(namespaceLikeImport.name), ts.factory.createExternalModuleReference(quotedModuleSpecifier))
: ts.factory.createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined, ts.factory.createImportClause(typeOnly,
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "fixNoPropertyAccessFromIndexSignature";
+ var errorCodes = [
+ ts.Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code
+ ];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ fixIds: [fixId],
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, span = context.span, preferences = context.preferences;
+ var property = getPropertyAccessExpression(sourceFile, span.start);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, property, preferences); });
+ return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Use_element_access_for_0, property.name.text], fixId, ts.Diagnostics.Use_element_access_for_all_undeclared_properties)];
+ },
+ getAllCodeActions: function (context) {
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, getPropertyAccessExpression(diag.file, diag.start), context.preferences); });
+ }
+ });
+ function doChange(changes, sourceFile, node, preferences) {
+ var quotePreference = ts.getQuotePreference(sourceFile, preferences);
+ var argumentsExpression = ts.factory.createStringLiteral(node.name.text, quotePreference === 0 /* Single */);
+ changes.replaceNode(sourceFile, node, ts.isPropertyAccessChain(node) ?
+ ts.factory.createElementAccessChain(node.expression, node.questionDotToken, argumentsExpression) :
+ ts.factory.createElementAccessExpression(node.expression, argumentsExpression));
+ }
+ function getPropertyAccessExpression(sourceFile, pos) {
+ return ts.cast(ts.getTokenAtPosition(sourceFile, pos).parent, ts.isPropertyAccessExpression);
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var codefix;
(function (codefix) {
(function (ts) {
var codefix;
(function (codefix) {
- var fixName = "addMissingMember";
+ var fixMissingMember = "fixMissingMember";
+ var fixMissingFunctionDeclaration = "fixMissingFunctionDeclaration";
var errorCodes = [
ts.Diagnostics.Property_0_does_not_exist_on_type_1.code,
ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code,
ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code,
- ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code
+ ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code,
+ ts.Diagnostics.Cannot_find_name_0.code
];
- var fixId = "addMissingMember";
codefix.registerCodeFix({
errorCodes: errorCodes,
getCodeActions: function (context) {
- var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker(), context.program);
+ var typeChecker = context.program.getTypeChecker();
+ var info = getInfo(context.sourceFile, context.span.start, typeChecker, context.program);
if (!info) {
return undefined;
}
+ if (info.kind === 2 /* Function */) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addFunctionDeclaration(t, context, info); });
+ return [codefix.createCodeFixAction(fixMissingFunctionDeclaration, changes, [ts.Diagnostics.Add_missing_function_declaration_0, info.token.text], fixMissingFunctionDeclaration, ts.Diagnostics.Add_all_missing_function_declarations)];
+ }
if (info.kind === 0 /* Enum */) {
- var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration;
- var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); });
- return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)];
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), info); });
+ return [codefix.createCodeFixAction(fixMissingMember, changes, [ts.Diagnostics.Add_missing_enum_member_0, info.token.text], fixMissingMember, ts.Diagnostics.Add_all_missing_members)];
}
return ts.concatenate(getActionsForMissingMethodDeclaration(context, info), getActionsForMissingMemberDeclaration(context, info));
},
- fixIds: [fixId],
+ fixIds: [fixMissingMember, fixMissingFunctionDeclaration],
getAllCodeActions: function (context) {
- var program = context.program;
+ var program = context.program, fixId = context.fixId;
var checker = program.getTypeChecker();
var seen = new ts.Map();
var typeDeclToMembers = new ts.Map();
if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) {
return;
}
- if (info.kind === 0 /* Enum */) {
- var token = info.token, parentDeclaration = info.parentDeclaration;
- addEnumMemberDeclaration(changes, checker, token, parentDeclaration);
+ if (fixId === fixMissingFunctionDeclaration) {
+ if (info.kind === 2 /* Function */) {
+ addFunctionDeclaration(changes, context, info);
+ }
}
else {
- var parentDeclaration = info.parentDeclaration, token_2 = info.token;
- var infos = ts.getOrUpdate(typeDeclToMembers, parentDeclaration, function () { return []; });
- if (!infos.some(function (i) { return i.token.text === token_2.text; }))
- infos.push(info);
+ if (info.kind === 0 /* Enum */) {
+ addEnumMemberDeclaration(changes, checker, info);
+ }
+ if (info.kind === 1 /* ClassOrInterface */) {
+ var parentDeclaration = info.parentDeclaration, token_1 = info.token;
+ var infos = ts.getOrUpdate(typeDeclToMembers, parentDeclaration, function () { return []; });
+ if (!infos.some(function (i) { return i.token.text === token_1.text; })) {
+ infos.push(info);
+ }
+ }
}
});
typeDeclToMembers.forEach(function (infos, classDeclaration) {
var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, modifierFlags = info.modifierFlags, token = info.token, call = info.call, isJSFile = info.isJSFile;
// Always prefer to add a method declaration if possible.
if (call && !ts.isPrivateIdentifier(token)) {
- addMethodDeclaration(context, changes, call, token.text, modifierFlags & 32 /* Static */, parentDeclaration, declSourceFile, isJSFile);
+ addMethodDeclaration(context, changes, call, token, modifierFlags & 32 /* Static */, parentDeclaration, declSourceFile);
}
else {
if (isJSFile && !ts.isInterfaceDeclaration(parentDeclaration)) {
(function (InfoKind) {
InfoKind[InfoKind["Enum"] = 0] = "Enum";
InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface";
+ InfoKind[InfoKind["Function"] = 2] = "Function";
})(InfoKind || (InfoKind = {}));
- function getInfo(tokenSourceFile, tokenPos, checker, program) {
+ function getInfo(sourceFile, tokenPos, checker, program) {
// The identifier of the missing property. eg:
// this.missing = 1;
// ^^^^^^^
- var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos);
+ var token = ts.getTokenAtPosition(sourceFile, tokenPos);
if (!ts.isIdentifier(token) && !ts.isPrivateIdentifier(token)) {
return undefined;
}
var parent = token.parent;
- if (!ts.isPropertyAccessExpression(parent))
+ if (ts.isIdentifier(token) && ts.isCallExpression(parent)) {
+ return { kind: 2 /* Function */, token: token, call: parent, sourceFile: sourceFile, modifierFlags: 0 /* None */, parentDeclaration: sourceFile };
+ }
+ if (!ts.isPropertyAccessExpression(parent)) {
return undefined;
+ }
var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression));
var symbol = leftExpressionType.symbol;
- if (!symbol || !symbol.declarations)
+ if (!symbol || !symbol.declarations) {
return undefined;
+ }
+ if (ts.isIdentifier(token) && ts.isCallExpression(parent.parent)) {
+ var moduleDeclaration = ts.find(symbol.declarations, ts.isModuleDeclaration);
+ var moduleDeclarationSourceFile = moduleDeclaration === null || moduleDeclaration === void 0 ? void 0 : moduleDeclaration.getSourceFile();
+ if (moduleDeclaration && moduleDeclarationSourceFile && !program.isSourceFileFromExternalLibrary(moduleDeclarationSourceFile)) {
+ return { kind: 2 /* Function */, token: token, call: parent.parent, sourceFile: sourceFile, modifierFlags: 1 /* Export */, parentDeclaration: moduleDeclaration };
+ }
+ var moduleSourceFile = ts.find(symbol.declarations, ts.isSourceFile);
+ if (sourceFile.commonJsModuleIndicator) {
+ return;
+ }
+ if (moduleSourceFile && !program.isSourceFileFromExternalLibrary(moduleSourceFile)) {
+ return { kind: 2 /* Function */, token: token, call: parent.parent, sourceFile: moduleSourceFile, modifierFlags: 1 /* Export */, parentDeclaration: moduleSourceFile };
+ }
+ }
var classDeclaration = ts.find(symbol.declarations, ts.isClassLike);
// Don't suggest adding private identifiers to anything other than a class.
if (!classDeclaration && ts.isPrivateIdentifier(token)) {
}
var diagnostic = modifierFlags & 32 /* Static */ ? ts.Diagnostics.Initialize_static_property_0 :
ts.isPrivateIdentifier(token) ? ts.Diagnostics.Declare_a_private_field_named_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor;
- return codefix.createCodeFixAction(fixName, changes, [diagnostic, token.text], fixId, ts.Diagnostics.Add_all_missing_members);
+ return codefix.createCodeFixAction(fixMissingMember, changes, [diagnostic, token.text], fixMissingMember, ts.Diagnostics.Add_all_missing_members);
}
function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, token, makeStatic) {
var tokenName = token.text;
var isStatic = modifierFlags & 32 /* Static */;
var typeNode = getTypeNode(context.program.getTypeChecker(), parentDeclaration, token);
var addPropertyDeclarationChanges = function (modifierFlags) { return ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, parentDeclaration, memberName, typeNode, modifierFlags); }); };
- var actions = [codefix.createCodeFixAction(fixName, addPropertyDeclarationChanges(modifierFlags & 32 /* Static */), [isStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, memberName], fixId, ts.Diagnostics.Add_all_missing_members)];
+ var actions = [codefix.createCodeFixAction(fixMissingMember, addPropertyDeclarationChanges(modifierFlags & 32 /* Static */), [isStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, memberName], fixMissingMember, ts.Diagnostics.Add_all_missing_members)];
if (isStatic || ts.isPrivateIdentifier(token)) {
return actions;
}
if (modifierFlags & 8 /* Private */) {
- actions.unshift(codefix.createCodeFixActionWithoutFixAll(fixName, addPropertyDeclarationChanges(8 /* Private */), [ts.Diagnostics.Declare_private_property_0, memberName]));
+ actions.unshift(codefix.createCodeFixActionWithoutFixAll(fixMissingMember, addPropertyDeclarationChanges(8 /* Private */), [ts.Diagnostics.Declare_private_property_0, memberName]));
}
actions.push(createAddIndexSignatureAction(context, declSourceFile, parentDeclaration, token.text, typeNode));
return actions;
/*modifiers*/ undefined, [indexingParameter], typeNode);
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); });
// No fixId here because code-fix-all currently only works on adding individual named properties.
- return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]);
+ return codefix.createCodeFixActionWithoutFixAll(fixMissingMember, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]);
}
function getActionsForMissingMethodDeclaration(context, info) {
- var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, modifierFlags = info.modifierFlags, token = info.token, call = info.call, isJSFile = info.isJSFile;
+ var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, modifierFlags = info.modifierFlags, token = info.token, call = info.call;
if (call === undefined) {
return undefined;
}
return undefined;
}
var methodName = token.text;
- var addMethodDeclarationChanges = function (modifierFlags) { return ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, call, methodName, modifierFlags, parentDeclaration, declSourceFile, isJSFile); }); };
- var actions = [codefix.createCodeFixAction(fixName, addMethodDeclarationChanges(modifierFlags & 32 /* Static */), [modifierFlags & 32 /* Static */ ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, methodName], fixId, ts.Diagnostics.Add_all_missing_members)];
+ var addMethodDeclarationChanges = function (modifierFlags) { return ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, call, token, modifierFlags, parentDeclaration, declSourceFile); }); };
+ var actions = [codefix.createCodeFixAction(fixMissingMember, addMethodDeclarationChanges(modifierFlags & 32 /* Static */), [modifierFlags & 32 /* Static */ ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, methodName], fixMissingMember, ts.Diagnostics.Add_all_missing_members)];
if (modifierFlags & 8 /* Private */) {
- actions.unshift(codefix.createCodeFixActionWithoutFixAll(fixName, addMethodDeclarationChanges(8 /* Private */), [ts.Diagnostics.Declare_private_method_0, methodName]));
+ actions.unshift(codefix.createCodeFixActionWithoutFixAll(fixMissingMember, addMethodDeclarationChanges(8 /* Private */), [ts.Diagnostics.Declare_private_method_0, methodName]));
}
return actions;
}
- function addMethodDeclaration(context, changes, callExpression, methodName, modifierFlags, parentDeclaration, sourceFile, isJSFile) {
+ function addMethodDeclaration(context, changes, callExpression, name, modifierFlags, parentDeclaration, sourceFile) {
var importAdder = codefix.createImportAdder(sourceFile, context.program, context.preferences, context.host);
- var methodDeclaration = codefix.createMethodFromCallExpression(context, importAdder, callExpression, methodName, modifierFlags, parentDeclaration, isJSFile);
+ var methodDeclaration = codefix.createSignatureDeclarationFromCallExpression(165 /* MethodDeclaration */, context, importAdder, callExpression, name, modifierFlags, parentDeclaration);
var containingMethodDeclaration = ts.findAncestor(callExpression, function (n) { return ts.isMethodDeclaration(n) || ts.isConstructorDeclaration(n); });
if (containingMethodDeclaration && containingMethodDeclaration.parent === parentDeclaration) {
changes.insertNodeAfter(sourceFile, containingMethodDeclaration, methodDeclaration);
}
importAdder.writeFixes(changes);
}
- function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) {
+ function addEnumMemberDeclaration(changes, checker, _a) {
+ var token = _a.token, parentDeclaration = _a.parentDeclaration;
/**
* create initializer only literal enum that has string initializer.
* value of initializer is a string literal that equal to name of enum member.
* numeric enum or empty enum will not create initializer.
*/
- var hasStringInitializer = ts.some(enumDeclaration.members, function (member) {
+ var hasStringInitializer = ts.some(parentDeclaration.members, function (member) {
var type = checker.getTypeAtLocation(member);
return !!(type && type.flags & 402653316 /* StringLike */);
});
var enumMember = ts.factory.createEnumMember(token, hasStringInitializer ? ts.factory.createStringLiteral(token.text) : undefined);
- changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.factory.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember))), {
+ changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, ts.factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.decorators, parentDeclaration.modifiers, parentDeclaration.name, ts.concatenate(parentDeclaration.members, ts.singleElementArray(enumMember))), {
leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude
});
}
+ function addFunctionDeclaration(changes, context, info) {
+ var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host);
+ var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(251 /* FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration);
+ changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration);
+ }
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName;
}
function getTypesPackageNameToInstall(packageName, host, diagCode) {
+ var _a;
return diagCode === errorCodeCannotFindModule
? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined)
- : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217
+ : (((_a = host.isKnownTypesPackageName) === null || _a === void 0 ? void 0 : _a.call(host, packageName)) ? ts.getTypesPackageName(packageName) : undefined);
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
var codefix;
(function (codefix) {
codefix.registerCodeFix({
- errorCodes: [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.code],
+ errorCodes: [
+ 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.code,
+ ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code,
+ ],
getCodeActions: function (context) {
var compilerOptions = context.program.getCompilerOptions();
var configFile = compilerOptions.configFile;
var fixName = "unusedIdentifier";
var fixIdPrefix = "unusedIdentifier_prefix";
var fixIdDelete = "unusedIdentifier_delete";
+ var fixIdDeleteImports = "unusedIdentifier_deleteImports";
var fixIdInfer = "unusedIdentifier_infer";
var errorCodes = [
ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code,
codefix.registerCodeFix({
errorCodes: errorCodes,
getCodeActions: function (context) {
- var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program;
+ var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
var checker = program.getTypeChecker();
var sourceFiles = program.getSourceFiles();
var token = ts.getTokenAtPosition(sourceFile, context.span.start);
var importDecl = tryGetFullImport(token);
if (importDecl) {
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); });
- return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])];
+ return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDeleteImports, ts.Diagnostics.Delete_all_unused_imports)];
}
- if (ts.isObjectBindingPattern(token.parent)) {
+ else if (isImport(token)) {
+ var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ false); });
+ if (deletion.length) {
+ return [codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_unused_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDeleteImports, ts.Diagnostics.Delete_all_unused_imports)];
+ }
+ }
+ if (ts.isObjectBindingPattern(token.parent) || ts.isArrayBindingPattern(token.parent)) {
if (ts.isParameter(token.parent.parent)) {
var elements = token.parent.elements;
var diagnostic = [
}
else {
var deletion = ts.textChanges.ChangeTracker.with(context, function (t) {
- return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false);
+ return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ false);
});
if (deletion.length) {
var name = ts.isComputedPropertyName(token.parent) ? token.parent : token;
}
return result;
},
- fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer],
+ fixIds: [fixIdPrefix, fixIdDelete, fixIdDeleteImports, fixIdInfer],
getAllCodeActions: function (context) {
- var sourceFile = context.sourceFile, program = context.program;
+ var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
var checker = program.getTypeChecker();
var sourceFiles = program.getSourceFiles();
return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
case fixIdPrefix:
tryPrefixDeclaration(changes, diag.code, sourceFile, token);
break;
- case fixIdDelete: {
- if (token.kind === 135 /* InferKeyword */) {
- break; // Can't delete
- }
+ case fixIdDeleteImports: {
var importDecl = tryGetFullImport(token);
if (importDecl) {
changes.delete(sourceFile, importDecl);
}
+ else if (isImport(token)) {
+ tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ true);
+ }
+ break;
+ }
+ case fixIdDelete: {
+ if (token.kind === 135 /* InferKeyword */ || isImport(token)) {
+ break; // Can't delete
+ }
else if (ts.isJSDocTemplateTag(token)) {
changes.delete(sourceFile, token);
}
deleteTypeParameters(changes, sourceFile, token);
}
else if (ts.isObjectBindingPattern(token.parent)) {
- if (ts.isParameter(token.parent.parent)) {
- deleteDestructuringElements(changes, sourceFile, token.parent);
+ if (token.parent.parent.initializer) {
+ break;
}
- else {
+ else if (!ts.isParameter(token.parent.parent) || isNotProvidedArguments(token.parent.parent, checker, sourceFiles)) {
changes.delete(sourceFile, token.parent.parent);
}
}
+ else if (ts.isArrayBindingPattern(token.parent.parent) && token.parent.parent.parent.initializer) {
+ break;
+ }
else if (canDeleteEntireVariableStatement(sourceFile, token)) {
deleteEntireVariableStatement(changes, sourceFile, token.parent);
}
else {
- tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true);
+ tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ true);
}
break;
}
function deleteTypeParameters(changes, sourceFile, token) {
changes.delete(sourceFile, ts.Debug.checkDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist"));
}
- // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing.
+ function isImport(token) {
+ return token.kind === 99 /* ImportKeyword */
+ || token.kind === 78 /* Identifier */ && (token.parent.kind === 265 /* ImportSpecifier */ || token.parent.kind === 262 /* ImportClause */);
+ }
+ /** Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. */
function tryGetFullImport(token) {
return token.kind === 99 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined;
}
}
return false;
}
- function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) {
- tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll);
- if (ts.isIdentifier(token))
- deleteAssignments(changes, sourceFile, token, checker);
- }
- function deleteAssignments(changes, sourceFile, token, checker) {
- ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) {
- if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref)
- ref = ref.parent;
- if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) {
- changes.delete(sourceFile, ref.parent.parent);
- }
- });
+ function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, isFixAll) {
+ tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll);
+ if (ts.isIdentifier(token)) {
+ ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) {
+ if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref)
+ ref = ref.parent;
+ if (!isFixAll && mayDeleteExpression(ref)) {
+ changes.delete(sourceFile, ref.parent.parent);
+ }
+ });
+ }
}
- function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) {
+ function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll) {
var parent = token.parent;
if (ts.isParameter(parent)) {
- tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll);
+ tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, program, cancellationToken, isFixAll);
}
- else {
+ else if (!isFixAll || !(ts.isIdentifier(token) && ts.FindAllReferences.Core.isSymbolReferencedInFile(token, checker, sourceFile))) {
changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent);
}
}
- function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) {
+ function tryDeleteParameter(changes, sourceFile, parameter, checker, sourceFiles, program, cancellationToken, isFixAll) {
if (isFixAll === void 0) { isFixAll = false; }
- if (mayDeleteParameter(checker, sourceFile, p, isFixAll)) {
- if (p.modifiers && p.modifiers.length > 0 &&
- (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) {
- p.modifiers.forEach(function (modifier) { return changes.deleteModifier(sourceFile, modifier); });
+ if (mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll)) {
+ if (parameter.modifiers && parameter.modifiers.length > 0 &&
+ (!ts.isIdentifier(parameter.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile))) {
+ parameter.modifiers.forEach(function (modifier) { return changes.deleteModifier(sourceFile, modifier); });
}
- else {
- changes.delete(sourceFile, p);
- deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker);
+ else if (!parameter.initializer && isNotProvidedArguments(parameter, checker, sourceFiles)) {
+ changes.delete(sourceFile, parameter);
}
}
}
- function mayDeleteParameter(checker, sourceFile, parameter, isFixAll) {
+ function isNotProvidedArguments(parameter, checker, sourceFiles) {
+ var index = parameter.parent.parameters.indexOf(parameter);
+ // Just in case the call didn't provide enough arguments.
+ return !ts.FindAllReferences.Core.someSignatureUsage(parameter.parent, sourceFiles, checker, function (_, call) { return !call || call.arguments.length > index; });
+ }
+ function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll) {
var parent = parameter.parent;
switch (parent.kind) {
case 165 /* MethodDeclaration */:
- // Don't remove a parameter if this overrides something.
- var symbol = checker.getSymbolAtLocation(parent.name);
- if (ts.isMemberSymbolInBaseType(symbol, checker))
- return false;
- // falls through
case 166 /* Constructor */:
+ var index = parent.parameters.indexOf(parameter);
+ var referent = ts.isMethodDeclaration(parent) ? parent.name : parent;
+ var entries = ts.FindAllReferences.Core.getReferencedSymbolsForNode(parent.pos, referent, program, sourceFiles, cancellationToken);
+ if (entries) {
+ for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) {
+ var entry = entries_2[_i];
+ for (var _a = 0, _b = entry.references; _a < _b.length; _a++) {
+ var reference = _b[_a];
+ if (reference.kind === 1 /* Node */) {
+ // argument in super(...)
+ var isSuperCall_1 = ts.isSuperKeyword(reference.node)
+ && ts.isCallExpression(reference.node.parent)
+ && reference.node.parent.arguments.length > index;
+ // argument in super.m(...)
+ var isSuperMethodCall = ts.isPropertyAccessExpression(reference.node.parent)
+ && ts.isSuperKeyword(reference.node.parent.expression)
+ && ts.isCallExpression(reference.node.parent.parent)
+ && reference.node.parent.parent.arguments.length > index;
+ // parameter in overridden or overriding method
+ var isOverriddenMethod = (ts.isMethodDeclaration(reference.node.parent) || ts.isMethodSignature(reference.node.parent))
+ && reference.node.parent !== parameter.parent
+ && reference.node.parent.parameters.length > index;
+ if (isSuperCall_1 || isSuperMethodCall || isOverriddenMethod)
+ return false;
+ }
+ }
+ }
+ }
return true;
case 251 /* FunctionDeclaration */: {
if (parent.name && isCallbackLike(checker, sourceFile, parent.name)) {
return ts.Debug.failBadSyntaxKind(parent);
}
}
- function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) {
- ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) {
- var index = deletedParameter.parent.parameters.indexOf(deletedParameter);
- if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments.
- changes.delete(sourceFile, call.arguments[index]);
- }
- });
- }
function isCallbackLike(checker, sourceFile, name) {
return !!ts.FindAllReferences.Core.eachSymbolReferenceInFile(name, checker, sourceFile, function (reference) {
return ts.isIdentifier(reference) && ts.isCallExpression(reference.parent) && reference.parent.arguments.indexOf(reference) >= 0;
parameters.slice(index + 1).every(function (p) { return ts.isIdentifier(p.name) && !p.symbol.isReferenced; }) :
index === parameters.length - 1;
}
+ function mayDeleteExpression(node) {
+ return ((ts.isBinaryExpression(node.parent) && node.parent.left === node) ||
+ ((ts.isPostfixUnaryExpression(node.parent) || ts.isPrefixUnaryExpression(node.parent)) && node.parent.operand === node)) && ts.isExpressionStatement(node.parent.parent);
+ }
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
var fixId = "fixAwaitInSyncFunction";
var errorCodes = [
ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
- ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code,
+ ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
];
codefix.registerCodeFix({
errorCodes: errorCodes,
if (!signature) {
return;
}
- var paramTags = ts.mapDefined(parameterInferences, function (inference) {
+ var inferences = ts.mapDefined(parameterInferences, function (inference) {
var param = inference.declaration;
// only infer parameters that have (1) no type and (2) an accessible inferred type
- if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
+ if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name)) {
return;
+ }
var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
- var name = ts.factory.cloneNode(param.name);
- ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
- return typeNode && ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!inference.isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, "");
+ if (typeNode) {
+ var name = ts.factory.cloneNode(param.name);
+ ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
+ return { name: ts.factory.cloneNode(param.name), param: param, isOptional: !!inference.isOptional, typeNode: typeNode };
+ }
});
- addJSDocTags(changes, sourceFile, signature, paramTags);
+ if (!inferences.length) {
+ return;
+ }
+ if (ts.isArrowFunction(signature) || ts.isFunctionExpression(signature)) {
+ var needParens = ts.isArrowFunction(signature) && !ts.findChildOfKind(signature, 20 /* OpenParenToken */, sourceFile);
+ if (needParens) {
+ changes.insertNodeBefore(sourceFile, ts.first(signature.parameters), ts.factory.createToken(20 /* OpenParenToken */));
+ }
+ ts.forEach(inferences, function (_a) {
+ var typeNode = _a.typeNode, param = _a.param;
+ var typeTag = ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode));
+ var jsDoc = ts.factory.createJSDocComment(/*comment*/ undefined, [typeTag]);
+ changes.insertNodeAt(sourceFile, param.getStart(sourceFile), jsDoc, { suffix: " " });
+ });
+ if (needParens) {
+ changes.insertNodeAfter(sourceFile, ts.last(signature.parameters), ts.factory.createToken(21 /* CloseParenToken */));
+ }
+ }
+ else {
+ var paramTags = ts.map(inferences, function (_a) {
+ var name = _a.name, typeNode = _a.typeNode, isOptional = _a.isOptional;
+ return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, "");
+ });
+ addJSDocTags(changes, sourceFile, signature, paramTags);
+ }
}
function addJSDocTags(changes, sourceFile, parent, newTags) {
var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; });
oldTags[i] = merged;
return !!merged;
}); });
- var tag = ts.factory.createJSDocComment(comments.join("\n"), ts.factory.createNodeArray(__spreadArrays((oldTags || ts.emptyArray), unmergedNewTags)));
+ var tag = ts.factory.createJSDocComment(comments.join("\n"), ts.factory.createNodeArray(__spreadArray(__spreadArray([], (oldTags || ts.emptyArray)), unmergedNewTags)));
var jsDocNode = parent.kind === 209 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent;
jsDocNode.jsDoc = parent.jsDoc;
jsDocNode.jsDocCache = parent.jsDocCache;
case 209 /* ArrowFunction */:
case 208 /* FunctionExpression */:
var parent = containingFunction.parent;
- searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ?
+ searchToken = (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent)) && ts.isIdentifier(parent.name) ?
parent.name :
containingFunction.name;
break;
case 251 /* FunctionDeclaration */:
case 165 /* MethodDeclaration */:
+ case 164 /* MethodSignature */:
searchToken = containingFunction.name;
break;
}
numberIndex: ts.forEach(usages, function (u) { return u.numberIndex; }),
stringIndex: ts.forEach(usages, function (u) { return u.stringIndex; }),
candidateThisTypes: ts.flatMap(usages, function (u) { return u.candidateThisTypes; }),
- inferredTypes: undefined,
+ inferredTypes: undefined, // clear type cache
};
}
function single() {
return undefined;
}
var usage = createEmptyUsage();
- for (var _i = 0, references_2 = references; _i < references_2.length; _i++) {
- var reference = references_2[_i];
+ for (var _i = 0, references_3 = references; _i < references_3.length; _i++) {
+ var reference = references_3[_i];
cancellationToken.throwIfCancellationRequested();
calculateUsageOfNode(reference, usage);
}
- var calls = __spreadArrays(usage.constructs || [], usage.calls || []);
+ var calls = __spreadArray(__spreadArray([], usage.constructs || []), usage.calls || []);
return declaration.parameters.map(function (parameter, parameterIndex) {
var types = [];
var isRest = ts.isRestParameter(parameter);
}
function thisParameter() {
var usage = createEmptyUsage();
- for (var _i = 0, references_3 = references; _i < references_3.length; _i++) {
- var reference = references_3[_i];
+ for (var _i = 0, references_4 = references; _i < references_4.length; _i++) {
+ var reference = references_4[_i];
cancellationToken.throwIfCancellationRequested();
calculateUsageOfNode(reference, usage);
}
}
function inferTypesFromReferencesSingle(references) {
var usage = createEmptyUsage();
- for (var _i = 0, references_4 = references; _i < references_4.length; _i++) {
- var reference = references_4[_i];
+ for (var _i = 0, references_5 = references; _i < references_5.length; _i++) {
+ var reference = references_5[_i];
cancellationToken.throwIfCancellationRequested();
calculateUsageOfNode(reference, usage);
}
return ts.factory.updateMethodDeclaration(signatureDeclaration,
/*decorators*/ undefined, modifiers, signatureDeclaration.asteriskToken, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, type, body);
}
- function createMethodFromCallExpression(context, importAdder, call, methodName, modifierFlags, contextNode, inJs) {
- var body = !ts.isInterfaceDeclaration(contextNode);
- var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent;
+ function createSignatureDeclarationFromCallExpression(kind, context, importAdder, call, name, modifierFlags, contextNode) {
+ var quotePreference = ts.getQuotePreference(context.sourceFile, context.preferences);
var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions());
- var checker = context.program.getTypeChecker();
var tracker = getNoopSymbolTrackerWithResolver(context);
- var types = ts.map(args, function (arg) {
- return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker);
- });
+ var checker = context.program.getTypeChecker();
+ var isJs = ts.isInJSFile(contextNode);
+ var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent;
+ var contextualType = isJs ? undefined : checker.getContextualType(call);
var names = ts.map(args, function (arg) {
return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined;
});
- var contextualType = checker.getContextualType(call);
- var returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker);
- var quotePreference = ts.getQuotePreference(context.sourceFile, context.preferences);
- return ts.factory.createMethodDeclaration(
- /*decorators*/ undefined,
- /*modifiers*/ modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined,
- /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.factory.createToken(41 /* AsteriskToken */) : undefined, methodName,
- /*questionToken*/ undefined,
- /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) {
- return ts.factory.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i);
- }),
- /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs),
- /*type*/ returnType, body ? createStubbedMethodBody(quotePreference) : undefined);
+ var types = isJs ? [] : ts.map(args, function (arg) {
+ return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker);
+ });
+ var modifiers = modifierFlags
+ ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags))
+ : undefined;
+ var asteriskToken = ts.isYieldExpression(parent)
+ ? ts.factory.createToken(41 /* AsteriskToken */)
+ : undefined;
+ var typeParameters = isJs || typeArguments === undefined
+ ? undefined
+ : ts.map(typeArguments, function (_, i) {
+ return ts.factory.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i);
+ });
+ var parameters = createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, isJs);
+ var type = isJs || contextualType === undefined
+ ? undefined
+ : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker);
+ if (kind === 165 /* MethodDeclaration */) {
+ return ts.factory.createMethodDeclaration(
+ /*decorators*/ undefined, modifiers, asteriskToken, name,
+ /*questionToken*/ undefined, typeParameters, parameters, type, ts.isInterfaceDeclaration(contextNode) ? undefined : createStubbedMethodBody(quotePreference));
+ }
+ return ts.factory.createFunctionDeclaration(
+ /*decorators*/ undefined, modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference));
}
- codefix.createMethodFromCallExpression = createMethodFromCallExpression;
+ codefix.createSignatureDeclarationFromCallExpression = createSignatureDeclarationFromCallExpression;
function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) {
var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker);
if (typeNode && ts.isImportTypeNode(typeNode)) {
/*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(quotePreference));
}
function createStubbedMethodBody(quotePreference) {
+ return createStubbedBody(ts.Diagnostics.Method_not_implemented.message, quotePreference);
+ }
+ function createStubbedBody(text, quotePreference) {
return ts.factory.createBlock([ts.factory.createThrowStatement(ts.factory.createNewExpression(ts.factory.createIdentifier("Error"),
/*typeArguments*/ undefined,
// TODO Handle auto quote preference.
- [ts.factory.createStringLiteral("Method not implemented.", /*isSingleQuote*/ quotePreference === 0 /* Single */)]))],
+ [ts.factory.createStringLiteral(text, /*isSingleQuote*/ quotePreference === 0 /* Single */)]))],
/*multiline*/ true);
}
+ codefix.createStubbedBody = createStubbedBody;
function createVisibilityModifier(flags) {
if (flags & 4 /* Public */) {
return ts.factory.createToken(122 /* PublicKeyword */);
(function (codefix) {
function generateAccessorFromProperty(file, program, start, end, context, _actionName) {
var fieldInfo = getAccessorConvertiblePropertyAtPosition(file, program, start, end);
- if (!fieldInfo || !fieldInfo.info)
+ if (!fieldInfo || ts.refactor.isRefactorErrorInfo(fieldInfo))
return undefined;
var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var _a = fieldInfo.info, isStatic = _a.isStatic, isReadonly = _a.isReadonly, fieldName = _a.fieldName, accessorName = _a.accessorName, originalName = _a.originalName, type = _a.type, container = _a.container, declaration = _a.declaration;
+ var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration;
ts.suppressLeadingAndTrailingTrivia(fieldName);
ts.suppressLeadingAndTrailingTrivia(accessorName);
ts.suppressLeadingAndTrailingTrivia(declaration);
var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name);
var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name);
return {
- info: {
- isStatic: ts.hasStaticModifier(declaration),
- isReadonly: ts.hasEffectiveReadonlyModifier(declaration),
- type: getDeclarationType(declaration, program),
- container: declaration.kind === 160 /* Parameter */ ? declaration.parent.parent : declaration.parent,
- originalName: declaration.name.text,
- declaration: declaration,
- fieldName: fieldName,
- accessorName: accessorName,
- renameAccessor: startWithUnderscore
- }
+ isStatic: ts.hasStaticModifier(declaration),
+ isReadonly: ts.hasEffectiveReadonlyModifier(declaration),
+ type: getDeclarationType(declaration, program),
+ container: declaration.kind === 160 /* Parameter */ ? declaration.parent.parent : declaration.parent,
+ originalName: declaration.name.text,
+ declaration: declaration,
+ fieldName: fieldName,
+ accessorName: accessorName,
+ renameAccessor: startWithUnderscore
};
}
codefix.getAccessorConvertiblePropertyAtPosition = getAccessorConvertiblePropertyAtPosition;
var type = typeChecker.getTypeFromTypeNode(typeNode);
if (!typeChecker.isTypeAssignableTo(typeChecker.getUndefinedType(), type)) {
var types = ts.isUnionTypeNode(typeNode) ? typeNode.types : [typeNode];
- return ts.factory.createUnionTypeNode(__spreadArrays(types, [ts.factory.createKeywordTypeNode(150 /* UndefinedKeyword */)]));
+ return ts.factory.createUnionTypeNode(__spreadArray(__spreadArray([], types), [ts.factory.createKeywordTypeNode(150 /* UndefinedKeyword */)]));
}
}
return typeNode;
// import Bluebird = require("bluebird");
variations.push(createAction(context, sourceFile, node, ts.factory.createImportEqualsDeclaration(
/*decorators*/ undefined,
- /*modifiers*/ undefined, namespace.name, ts.factory.createExternalModuleReference(node.moduleSpecifier))));
+ /*modifiers*/ undefined,
+ /*isTypeOnly*/ false, namespace.name, ts.factory.createExternalModuleReference(node.moduleSpecifier))));
}
return variations;
}
function doChange(changes, sourceFile, info) {
var allowSyntheticDefaults = info.allowSyntheticDefaults, defaultImportName = info.defaultImportName, namedImports = info.namedImports, statement = info.statement, required = info.required;
changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults
- ? ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, defaultImportName, ts.factory.createExternalModuleReference(required))
+ ? ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, ts.factory.createExternalModuleReference(required))
: ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required));
}
function getInfo(sourceFile, program, pos) {
var mappedTypeParameter = ts.factory.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type);
var mappedIntersectionType = ts.factory.createMappedTypeNode(ts.hasEffectiveReadonlyModifier(indexSignature) ? ts.factory.createModifier(142 /* ReadonlyKeyword */) : undefined, mappedTypeParameter,
/*nameType*/ undefined, indexSignature.questionToken, indexSignature.type);
- var intersectionType = ts.factory.createIntersectionTypeNode(__spreadArrays(ts.getAllSuperTypeNodes(container), [
+ var intersectionType = ts.factory.createIntersectionTypeNode(__spreadArray(__spreadArray(__spreadArray([], ts.getAllSuperTypeNodes(container)), [
mappedIntersectionType
- ], (otherMembers.length ? [ts.factory.createTypeLiteralNode(otherMembers)] : ts.emptyArray)));
+ ]), (otherMembers.length ? [ts.factory.createTypeLiteralNode(otherMembers)] : ts.emptyArray)));
changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType));
}
})(codefix = ts.codefix || (ts.codefix = {}));
var refactor;
(function (refactor) {
var refactorName = "Convert export";
- var actionNameDefaultToNamed = "Convert default export to named export";
- var actionNameNamedToDefault = "Convert named export to default export";
+ var defaultToNamedAction = {
+ name: "Convert default export to named export",
+ description: ts.Diagnostics.Convert_default_export_to_named_export.message,
+ kind: "refactor.rewrite.export.named"
+ };
+ var namedToDefaultAction = {
+ name: "Convert named export to default export",
+ description: ts.Diagnostics.Convert_named_export_to_default_export.message,
+ kind: "refactor.rewrite.export.default"
+ };
refactor.registerRefactor(refactorName, {
+ kinds: [
+ defaultToNamedAction.kind,
+ namedToDefaultAction.kind
+ ],
getAvailableActions: function (context) {
var info = getInfo(context, context.triggerReason === "invoked");
if (!info)
return ts.emptyArray;
- if (info.error === undefined) {
- var description = info.info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message;
- var actionName = info.info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault;
- return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
+ if (!refactor.isRefactorErrorInfo(info)) {
+ var action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction;
+ return [{ name: refactorName, description: action.description, actions: [action] }];
}
if (context.preferences.provideRefactorNotApplicableReason) {
return [
- { name: refactorName, description: ts.Diagnostics.Convert_default_export_to_named_export.message, actions: [{ name: actionNameDefaultToNamed, description: ts.Diagnostics.Convert_default_export_to_named_export.message, notApplicableReason: info.error }] },
- { name: refactorName, description: ts.Diagnostics.Convert_named_export_to_default_export.message, actions: [{ name: actionNameNamedToDefault, description: ts.Diagnostics.Convert_named_export_to_default_export.message, notApplicableReason: info.error }] },
+ { name: refactorName, description: ts.Diagnostics.Convert_default_export_to_named_export.message, actions: [
+ __assign(__assign({}, defaultToNamedAction), { notApplicableReason: info.error }),
+ __assign(__assign({}, namedToDefaultAction), { notApplicableReason: info.error }),
+ ] }
];
}
return ts.emptyArray;
},
getEditsForAction: function (context, actionName) {
- ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault, "Unexpected action name");
- var edits = ts.textChanges.ChangeTracker.with(context, function (t) { var _a; return doChange(context.file, context.program, ts.Debug.checkDefined((_a = getInfo(context)) === null || _a === void 0 ? void 0 : _a.info, "context must have info"), t, context.cancellationToken); });
+ ts.Debug.assert(actionName === defaultToNamedAction.name || actionName === namedToDefaultAction.name, "Unexpected action name");
+ var info = getInfo(context);
+ ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info");
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, info, t, context.cancellationToken); });
return { edits: edits, renameFilename: undefined, renameLocation: undefined };
},
});
+ ;
function getInfo(context, considerPartialSpans) {
if (considerPartialSpans === void 0) { considerPartialSpans = true; }
var file = context.file;
case 254 /* TypeAliasDeclaration */:
case 256 /* ModuleDeclaration */: {
var node = exportNode;
- return node.name && ts.isIdentifier(node.name) ? { info: { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } } : undefined;
+ return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
}
case 232 /* VariableStatement */: {
var vs = exportNode;
if (!decl.initializer)
return undefined;
ts.Debug.assert(!wasDefault, "Can't have a default flag here");
- return ts.isIdentifier(decl.name) ? { info: { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } } : undefined;
+ return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
}
default:
return undefined;
var refactor;
(function (refactor) {
var refactorName = "Convert import";
- var actionNameNamespaceToNamed = "Convert namespace import to named imports";
- var actionNameNamedToNamespace = "Convert named imports to namespace import";
+ var namespaceToNamedAction = {
+ name: "Convert namespace import to named imports",
+ description: ts.Diagnostics.Convert_namespace_import_to_named_imports.message,
+ kind: "refactor.rewrite.import.named",
+ };
+ var namedToNamespaceAction = {
+ name: "Convert named imports to namespace import",
+ description: ts.Diagnostics.Convert_named_imports_to_namespace_import.message,
+ kind: "refactor.rewrite.import.namespace",
+ };
refactor.registerRefactor(refactorName, {
+ kinds: [
+ namespaceToNamedAction.kind,
+ namedToNamespaceAction.kind
+ ],
getAvailableActions: function (context) {
- var i = getImportToConvert(context, context.triggerReason === "invoked");
- if (!i)
+ var info = getImportToConvert(context, context.triggerReason === "invoked");
+ if (!info)
return ts.emptyArray;
- if (i.error === undefined) {
- var description = i.info.kind === 263 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message;
- var actionName = i.info.kind === 263 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace;
- return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
+ if (!refactor.isRefactorErrorInfo(info)) {
+ var namespaceImport = info.kind === 263 /* NamespaceImport */;
+ var action = namespaceImport ? namespaceToNamedAction : namedToNamespaceAction;
+ return [{ name: refactorName, description: action.description, actions: [action] }];
}
if (context.preferences.provideRefactorNotApplicableReason) {
return [
- { name: refactorName, description: ts.Diagnostics.Convert_namespace_import_to_named_imports.message, actions: [{ name: actionNameNamespaceToNamed, description: ts.Diagnostics.Convert_namespace_import_to_named_imports.message, notApplicableReason: i.error }] },
- { name: refactorName, description: ts.Diagnostics.Convert_named_imports_to_namespace_import.message, actions: [{ name: actionNameNamedToNamespace, description: ts.Diagnostics.Convert_named_imports_to_namespace_import.message, notApplicableReason: i.error }] }
+ { name: refactorName, description: namespaceToNamedAction.description, actions: [__assign(__assign({}, namespaceToNamedAction), { notApplicableReason: info.error })] },
+ { name: refactorName, description: namedToNamespaceAction.description, actions: [__assign(__assign({}, namedToNamespaceAction), { notApplicableReason: info.error })] }
];
}
return ts.emptyArray;
},
getEditsForAction: function (context, actionName) {
- ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace, "Unexpected action name");
- var edits = ts.textChanges.ChangeTracker.with(context, function (t) { var _a; return doChange(context.file, context.program, t, ts.Debug.checkDefined((_a = getImportToConvert(context)) === null || _a === void 0 ? void 0 : _a.info, "Context must provide an import to convert")); });
+ ts.Debug.assert(actionName === namespaceToNamedAction.name || actionName === namedToNamespaceAction.name, "Unexpected action name");
+ var info = getImportToConvert(context);
+ ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info");
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, info); });
return { edits: edits, renameFilename: undefined, renameLocation: undefined };
}
});
if (!importClause.namedBindings) {
return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_namespace_import_or_named_imports) };
}
- return { info: importClause.namedBindings };
+ return importClause.namedBindings;
}
function doChange(sourceFile, program, changes, toConvert) {
var checker = program.getTypeChecker();
var nodesToReplace = [];
var conflictingNames = new ts.Map();
ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) {
- if (!ts.isPropertyAccessExpression(id.parent)) {
+ if (!ts.isPropertyAccessOrQualifiedName(id.parent)) {
usedAsNamespaceOrDefault = true;
}
else {
- var parent = ts.cast(id.parent, ts.isPropertyAccessExpression);
- var exportName = parent.name.text;
+ var exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text;
if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) {
conflictingNames.set(exportName, true);
}
- ts.Debug.assert(parent.expression === id, "Parent expression should match id");
- nodesToReplace.push(parent);
+ ts.Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id");
+ nodesToReplace.push(id.parent);
}
});
// We may need to change `mod.x` to `_x` to avoid a name conflict.
var exportNameToImportName = new ts.Map();
for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) {
- var propertyAccess = nodesToReplace_1[_i];
- var exportName = propertyAccess.name.text;
+ var propertyAccessOrQualifiedName = nodesToReplace_1[_i];
+ var exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text;
var importName = exportNameToImportName.get(exportName);
if (importName === undefined) {
exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName);
}
- changes.replaceNode(sourceFile, propertyAccess, ts.factory.createIdentifier(importName));
+ changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, ts.factory.createIdentifier(importName));
}
var importSpecifiers = [];
exportNameToImportName.forEach(function (name, propertyName) {
changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.factory.createIdentifier(toConvert.name.text) : undefined, importSpecifiers));
}
}
+ function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) {
+ return ts.isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right;
+ }
+ function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) {
+ return ts.isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left;
+ }
function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) {
var importDecl = toConvert.parent.parent;
var moduleSpecifier = importDecl.moduleSpecifier;
(function (convertToOptionalChainExpression) {
var refactorName = "Convert to optional chain expression";
var convertToOptionalChainExpressionMessage = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_optional_chain_expression);
- refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction });
+ var toOptionalChainAction = {
+ name: refactorName,
+ description: convertToOptionalChainExpressionMessage,
+ kind: "refactor.rewrite.expression.optionalChain",
+ };
+ refactor.registerRefactor(refactorName, {
+ kinds: [toOptionalChainAction.kind],
+ getAvailableActions: getAvailableActions,
+ getEditsForAction: getEditsForAction
+ });
function getAvailableActions(context) {
var info = getInfo(context, context.triggerReason === "invoked");
if (!info)
return ts.emptyArray;
- if (!info.error) {
+ if (!refactor.isRefactorErrorInfo(info)) {
return [{
name: refactorName,
description: convertToOptionalChainExpressionMessage,
- actions: [{
- name: refactorName,
- description: convertToOptionalChainExpressionMessage
- }]
+ actions: [toOptionalChainAction],
}];
}
if (context.preferences.provideRefactorNotApplicableReason) {
return [{
name: refactorName,
description: convertToOptionalChainExpressionMessage,
- actions: [{
- name: refactorName,
- description: convertToOptionalChainExpressionMessage,
- notApplicableReason: info.error
- }]
+ actions: [__assign(__assign({}, toOptionalChainAction), { notApplicableReason: info.error })],
}];
}
return ts.emptyArray;
}
function getEditsForAction(context, actionName) {
var info = getInfo(context);
- if (!info || !info.info)
- return undefined;
+ ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info");
var edits = ts.textChanges.ChangeTracker.with(context, function (t) {
- return doChange(context.file, context.program.getTypeChecker(), t, ts.Debug.checkDefined(info.info, "context must have info"), actionName);
+ return doChange(context.file, context.program.getTypeChecker(), t, info, actionName);
});
return { edits: edits, renameFilename: undefined, renameLocation: undefined };
}
}
if ((ts.isPropertyAccessExpression(condition) || ts.isIdentifier(condition))
&& getMatchingStart(condition, finalExpression.expression)) {
- return { info: { finalExpression: finalExpression, occurrences: [condition], expression: expression } };
+ return { finalExpression: finalExpression, occurrences: [condition], expression: expression };
}
else if (ts.isBinaryExpression(condition)) {
var occurrences = getOccurrencesInExpression(finalExpression.expression, condition);
- return occurrences ? { info: { finalExpression: finalExpression, occurrences: occurrences, expression: expression } } :
+ return occurrences ? { finalExpression: finalExpression, occurrences: occurrences, expression: expression } :
{ error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_matching_access_expressions) };
}
}
if (!finalExpression)
return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_convertible_access_expression) };
var occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left);
- return occurrences ? { info: { finalExpression: finalExpression, occurrences: occurrences, expression: expression } } :
+ return occurrences ? { finalExpression: finalExpression, occurrences: occurrences, expression: expression } :
{ error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_matching_access_expressions) };
}
/**
(function (addOrRemoveBracesToArrowFunction) {
var refactorName = "Convert overload list to single signature";
var refactorDescription = ts.Diagnostics.Convert_overload_list_to_single_signature.message;
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ var functionOverloadAction = {
+ name: refactorName,
+ description: refactorDescription,
+ kind: "refactor.rewrite.function.overloadList",
+ };
+ refactor.registerRefactor(refactorName, {
+ kinds: [functionOverloadAction.kind],
+ getEditsForAction: getEditsForAction,
+ getAvailableActions: getAvailableActions
+ });
function getAvailableActions(context) {
var file = context.file, startPosition = context.startPosition, program = context.program;
var info = getConvertableOverloadListAtPosition(file, startPosition, program);
return [{
name: refactorName,
description: refactorDescription,
- actions: [{
- name: refactorName,
- description: refactorDescription
- }]
+ actions: [functionOverloadAction]
}];
}
function getEditsForAction(context) {
var extractSymbol;
(function (extractSymbol) {
var refactorName = "Extract Symbol";
- refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction });
+ var extractConstantAction = {
+ name: "Extract Constant",
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant),
+ kind: "refactor.extract.constant",
+ };
+ var extractFunctionAction = {
+ name: "Extract Function",
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function),
+ kind: "refactor.extract.function",
+ };
+ refactor.registerRefactor(refactorName, {
+ kinds: [
+ extractConstantAction.kind,
+ extractFunctionAction.kind
+ ],
+ getAvailableActions: getAvailableActions,
+ getEditsForAction: getEditsForAction
+ });
/**
* Compute the associated code actions
* Exported for tests.
*/
function getAvailableActions(context) {
+ var requestedRefactor = context.kind;
var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context), context.triggerReason === "invoked");
var targetRange = rangeToExtract.targetRange;
if (targetRange === undefined) {
if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) {
return ts.emptyArray;
}
- return [{
+ var errors = [];
+ if (refactor.refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) {
+ errors.push({
name: refactorName,
- description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function),
- actions: [{
- description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function),
- name: "function_extract_error",
- notApplicableReason: getStringError(rangeToExtract.errors)
- }]
- },
- {
+ description: extractFunctionAction.description,
+ actions: [__assign(__assign({}, extractFunctionAction), { notApplicableReason: getStringError(rangeToExtract.errors) })]
+ });
+ }
+ if (refactor.refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) {
+ errors.push({
name: refactorName,
- description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant),
- actions: [{
- description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant),
- name: "constant_extract_error",
- notApplicableReason: getStringError(rangeToExtract.errors)
- }]
- }];
+ description: extractConstantAction.description,
+ actions: [__assign(__assign({}, extractConstantAction), { notApplicableReason: getStringError(rangeToExtract.errors) })]
+ });
+ }
+ return errors;
}
var extractions = getPossibleExtractions(targetRange, context);
if (extractions === undefined) {
for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) {
var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction;
var description = functionExtraction.description;
- if (functionExtraction.errors.length === 0) {
- // Don't issue refactorings with duplicated names.
- // Scopes come back in "innermost first" order, so extractions will
- // preferentially go into nearer scopes
- if (!usedFunctionNames.has(description)) {
- usedFunctionNames.set(description, true);
- functionActions.push({
+ if (refactor.refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) {
+ if (functionExtraction.errors.length === 0) {
+ // Don't issue refactorings with duplicated names.
+ // Scopes come back in "innermost first" order, so extractions will
+ // preferentially go into nearer scopes
+ if (!usedFunctionNames.has(description)) {
+ usedFunctionNames.set(description, true);
+ functionActions.push({
+ description: description,
+ name: "function_scope_" + i,
+ kind: extractFunctionAction.kind
+ });
+ }
+ }
+ else if (!innermostErrorFunctionAction) {
+ innermostErrorFunctionAction = {
description: description,
- name: "function_scope_" + i
- });
+ name: "function_scope_" + i,
+ notApplicableReason: getStringError(functionExtraction.errors),
+ kind: extractFunctionAction.kind
+ };
}
}
- else if (!innermostErrorFunctionAction) {
- innermostErrorFunctionAction = {
- description: description,
- name: "function_scope_" + i,
- notApplicableReason: getStringError(functionExtraction.errors)
- };
- }
// Skip these since we don't have a way to report errors yet
- if (constantExtraction.errors.length === 0) {
- // Don't issue refactorings with duplicated names.
- // Scopes come back in "innermost first" order, so extractions will
- // preferentially go into nearer scopes
- var description_1 = constantExtraction.description;
- if (!usedConstantNames.has(description_1)) {
- usedConstantNames.set(description_1, true);
- constantActions.push({
- description: description_1,
- name: "constant_scope_" + i
- });
+ if (refactor.refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) {
+ if (constantExtraction.errors.length === 0) {
+ // Don't issue refactorings with duplicated names.
+ // Scopes come back in "innermost first" order, so extractions will
+ // preferentially go into nearer scopes
+ var description_1 = constantExtraction.description;
+ if (!usedConstantNames.has(description_1)) {
+ usedConstantNames.set(description_1, true);
+ constantActions.push({
+ description: description_1,
+ name: "constant_scope_" + i,
+ kind: extractConstantAction.kind
+ });
+ }
+ }
+ else if (!innermostErrorConstantAction) {
+ innermostErrorConstantAction = {
+ description: description,
+ name: "constant_scope_" + i,
+ notApplicableReason: getStringError(constantExtraction.errors),
+ kind: extractConstantAction.kind
+ };
}
- }
- else if (!innermostErrorConstantAction) {
- innermostErrorConstantAction = {
- description: description,
- name: "constant_scope_" + i,
- notApplicableReason: getStringError(constantExtraction.errors)
- };
}
// *do* increment i anyway because we'll look for the i-th scope
// later when actually doing the refactoring if the user requests it
infos.push({
name: refactorName,
description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function),
- actions: functionActions
+ actions: functionActions,
});
}
else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) {
var refactor;
(function (refactor) {
var refactorName = "Extract type";
- var extractToTypeAlias = "Extract to type alias";
- var extractToInterface = "Extract to interface";
- var extractToTypeDef = "Extract to typedef";
+ var extractToTypeAliasAction = {
+ name: "Extract to type alias",
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_type_alias),
+ kind: "refactor.extract.type",
+ };
+ var extractToInterfaceAction = {
+ name: "Extract to interface",
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_interface),
+ kind: "refactor.extract.interface",
+ };
+ var extractToTypeDefAction = {
+ name: "Extract to typedef",
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_typedef),
+ kind: "refactor.extract.typedef"
+ };
refactor.registerRefactor(refactorName, {
+ kinds: [
+ extractToTypeAliasAction.kind,
+ extractToInterfaceAction.kind,
+ extractToTypeDefAction.kind
+ ],
getAvailableActions: function (context) {
var info = getRangeToExtract(context, context.triggerReason === "invoked");
if (!info)
return ts.emptyArray;
- if (info.error === undefined) {
+ if (!refactor.isRefactorErrorInfo(info)) {
return [{
name: refactorName,
description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_type),
- actions: info.info.isJS ? [{
- name: extractToTypeDef, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_typedef)
- }] : ts.append([{
- name: extractToTypeAlias, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_type_alias)
- }], info.info.typeElements && {
- name: extractToInterface, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_interface)
- })
+ actions: info.isJS ?
+ [extractToTypeDefAction] : ts.append([extractToTypeAliasAction], info.typeElements && extractToInterfaceAction)
}];
}
if (context.preferences.provideRefactorNotApplicableReason) {
name: refactorName,
description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_type),
actions: [
- { name: extractToTypeDef, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_typedef), notApplicableReason: info.error },
- { name: extractToTypeAlias, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_type_alias), notApplicableReason: info.error },
- { name: extractToInterface, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_interface), notApplicableReason: info.error },
+ __assign(__assign({}, extractToTypeDefAction), { notApplicableReason: info.error }),
+ __assign(__assign({}, extractToTypeAliasAction), { notApplicableReason: info.error }),
+ __assign(__assign({}, extractToInterfaceAction), { notApplicableReason: info.error }),
]
}];
}
return ts.emptyArray;
},
getEditsForAction: function (context, actionName) {
- var _a;
var file = context.file;
- var info = ts.Debug.checkDefined((_a = getRangeToExtract(context)) === null || _a === void 0 ? void 0 : _a.info, "Expected to find a range to extract");
+ var info = getRangeToExtract(context);
+ ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected to find a range to extract");
var name = ts.getUniqueName("NewType", file);
var edits = ts.textChanges.ChangeTracker.with(context, function (changes) {
switch (actionName) {
- case extractToTypeAlias:
+ case extractToTypeAliasAction.name:
ts.Debug.assert(!info.isJS, "Invalid actionName/JS combo");
return doTypeAliasChange(changes, file, name, info);
- case extractToTypeDef:
+ case extractToTypeDefAction.name:
ts.Debug.assert(info.isJS, "Invalid actionName/JS combo");
return doTypedefChange(changes, file, name, info);
- case extractToInterface:
+ case extractToInterfaceAction.name:
ts.Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo");
return doInterfaceChange(changes, file, name, info);
default:
if (!typeParameters)
return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.No_type_could_be_extracted_from_this_type_node) };
var typeElements = flattenTypeLiteralNodeReference(checker, selection);
- return { info: { isJS: isJS, selection: selection, firstStatement: firstStatement, typeParameters: typeParameters, typeElements: typeElements } };
+ return { isJS: isJS, selection: selection, firstStatement: firstStatement, typeParameters: typeParameters, typeElements: typeElements };
}
function flattenTypeLiteralNodeReference(checker, node) {
if (!node)
(function (generateGetAccessorAndSetAccessor) {
var actionName = "Generate 'get' and 'set' accessors";
var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message;
+ var generateGetSetAction = {
+ name: actionName,
+ description: actionDescription,
+ kind: "refactor.rewrite.property.generateAccessors",
+ };
refactor.registerRefactor(actionName, {
+ kinds: [generateGetSetAction.kind],
getEditsForAction: function (context, actionName) {
if (!context.endPosition)
return undefined;
var info = ts.codefix.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition);
- if (!info || !info.info)
- return undefined;
+ ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info");
var edits = ts.codefix.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName);
if (!edits)
return undefined;
var renameFilename = context.file.fileName;
- var nameNeedRename = info.info.renameAccessor ? info.info.accessorName : info.info.fieldName;
+ var nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName;
var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1;
- var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(info.info.declaration));
+ var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(info.declaration));
return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
},
getAvailableActions: function (context) {
var info = ts.codefix.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked");
if (!info)
return ts.emptyArray;
- if (!info.error) {
+ if (!refactor.isRefactorErrorInfo(info)) {
return [{
name: actionName,
description: actionDescription,
- actions: [
- {
- name: actionName,
- description: actionDescription
- }
- ]
+ actions: [generateGetSetAction],
}];
}
if (context.preferences.provideRefactorNotApplicableReason) {
return [{
name: actionName,
description: actionDescription,
- actions: [{
- name: actionName,
- description: actionDescription,
- notApplicableReason: info.error
- }]
+ actions: [__assign(__assign({}, generateGetSetAction), { notApplicableReason: info.error })],
}];
}
return ts.emptyArray;
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ ;
+ /**
+ * Checks if some refactor info has refactor error info.
+ */
+ function isRefactorErrorInfo(info) {
+ return info.error !== undefined;
+ }
+ refactor.isRefactorErrorInfo = isRefactorErrorInfo;
+ /**
+ * Checks if string "known" begins with string "requested".
+ * Used to match requested kinds with a known kind.
+ */
+ function refactorKindBeginsWith(known, requested) {
+ if (!requested)
+ return true;
+ return known.substr(0, requested.length) === requested;
+ }
+ refactor.refactorKindBeginsWith = refactorKindBeginsWith;
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var refactor;
(function (refactor) {
var refactorName = "Move to a new file";
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
+ var moveToNewFileAction = {
+ name: refactorName,
+ description: description,
+ kind: "refactor.move.newFile",
+ };
refactor.registerRefactor(refactorName, {
+ kinds: [moveToNewFileAction.kind],
getAvailableActions: function (context) {
- if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined)
- return ts.emptyArray;
- var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
- return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }];
+ var statements = getStatementsToMove(context);
+ if (context.preferences.allowTextChangesInNewFiles && statements) {
+ return [{ name: refactorName, description: description, actions: [moveToNewFileAction] }];
+ }
+ if (context.preferences.provideRefactorNotApplicableReason) {
+ return [{ name: refactorName, description: description, actions: [__assign(__assign({}, moveToNewFileAction), { notApplicableReason: ts.getLocaleSpecificMessage(ts.Diagnostics.Selection_is_not_a_valid_statement_or_statements) })]
+ }];
+ }
+ return ts.emptyArray;
},
getEditsForAction: function (context, actionName) {
ts.Debug.assert(actionName === refactorName, "Wrong refactor invoked");
var prologueDirectives = ts.takeWhile(oldFile.statements, ts.isPrologueDirective);
if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) {
deleteMovedStatements(oldFile, toMove.ranges, changes);
- return __spreadArrays(prologueDirectives, toMove.all);
+ return __spreadArray(__spreadArray([], prologueDirectives), toMove.all);
}
var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator;
var quotePreference = ts.getQuotePreference(oldFile, preferences);
var imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference);
var body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax);
if (imports.length && body.length) {
- return __spreadArrays(prologueDirectives, imports, [
+ return __spreadArray(__spreadArray(__spreadArray(__spreadArray([], prologueDirectives), imports), [
4 /* NewLineTrivia */
- ], body);
+ ]), body);
}
- return __spreadArrays(prologueDirectives, imports, body);
+ return __spreadArray(__spreadArray(__spreadArray([], prologueDirectives), imports), body);
}
function deleteMovedStatements(sourceFile, moved, changes) {
for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) {
updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode);
});
};
- for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
- var statement = _a[_i];
+ for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) {
+ var statement = _c[_b];
_loop_18(statement);
}
};
return ts.factory.createImportDeclaration(
/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString);
case 260 /* ImportEqualsDeclaration */:
- return ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString));
+ return ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString));
case 249 /* VariableDeclaration */:
return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString));
default:
case 253 /* InterfaceDeclaration */:
return ts.factory.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
case 260 /* ImportEqualsDeclaration */:
- return ts.factory.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
+ return ts.factory.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.isTypeOnly, d.name, d.moduleReference);
case 233 /* ExpressionStatement */:
return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
default:
}
}
function addCommonjsExport(decl) {
- return __spreadArrays([decl], getNamesToExportInCommonJS(decl).map(createExportAssignment));
+ return __spreadArray([decl], getNamesToExportInCommonJS(decl).map(createExportAssignment));
}
function getNamesToExportInCommonJS(decl) {
switch (decl.kind) {
(function (addOrRemoveBracesToArrowFunction) {
var refactorName = "Add or remove braces in an arrow function";
var refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message;
- var addBracesActionName = "Add braces to arrow function";
- var removeBracesActionName = "Remove braces from arrow function";
- var addBracesActionDescription = ts.Diagnostics.Add_braces_to_arrow_function.message;
- var removeBracesActionDescription = ts.Diagnostics.Remove_braces_from_arrow_function.message;
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ var addBracesAction = {
+ name: "Add braces to arrow function",
+ description: ts.Diagnostics.Add_braces_to_arrow_function.message,
+ kind: "refactor.rewrite.arrow.braces.add",
+ };
+ var removeBracesAction = {
+ name: "Remove braces from arrow function",
+ description: ts.Diagnostics.Remove_braces_from_arrow_function.message,
+ kind: "refactor.rewrite.arrow.braces.remove"
+ };
+ refactor.registerRefactor(refactorName, {
+ kinds: [removeBracesAction.kind],
+ getEditsForAction: getEditsForAction,
+ getAvailableActions: getAvailableActions
+ });
function getAvailableActions(context) {
var file = context.file, startPosition = context.startPosition, triggerReason = context.triggerReason;
var info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked");
if (!info)
return ts.emptyArray;
- if (info.error === undefined) {
+ if (!refactor.isRefactorErrorInfo(info)) {
return [{
name: refactorName,
description: refactorDescription,
actions: [
- info.info.addBraces ?
- {
- name: addBracesActionName,
- description: addBracesActionDescription
- } : {
- name: removeBracesActionName,
- description: removeBracesActionDescription
- }
+ info.addBraces ? addBracesAction : removeBracesAction
]
}];
}
return [{
name: refactorName,
description: refactorDescription,
- actions: [{
- name: addBracesActionName,
- description: addBracesActionDescription,
- notApplicableReason: info.error
- }, {
- name: removeBracesActionName,
- description: removeBracesActionDescription,
- notApplicableReason: info.error
- }]
+ actions: [
+ __assign(__assign({}, addBracesAction), { notApplicableReason: info.error }),
+ __assign(__assign({}, removeBracesAction), { notApplicableReason: info.error }),
+ ]
}];
}
return ts.emptyArray;
function getEditsForAction(context, actionName) {
var file = context.file, startPosition = context.startPosition;
var info = getConvertibleArrowFunctionAtPosition(file, startPosition);
- if (!info || !info.info)
- return undefined;
- var _a = info.info, expression = _a.expression, returnStatement = _a.returnStatement, func = _a.func;
+ ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info");
+ var expression = info.expression, returnStatement = info.returnStatement, func = info.func;
var body;
- if (actionName === addBracesActionName) {
+ if (actionName === addBracesAction.name) {
var returnStatement_1 = ts.factory.createReturnStatement(expression);
body = ts.factory.createBlock([returnStatement_1], /* multiLine */ true);
ts.suppressLeadingAndTrailingTrivia(body);
ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
}
- else if (actionName === removeBracesActionName && returnStatement) {
+ else if (actionName === removeBracesAction.name && returnStatement) {
var actualExpression = expression || ts.factory.createVoidZero();
body = ts.needsParentheses(actualExpression) ? ts.factory.createParenthesizedExpression(actualExpression) : actualExpression;
ts.suppressLeadingAndTrailingTrivia(body);
});
return { renameFilename: undefined, renameLocation: undefined, edits: edits };
}
- function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies) {
+ function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies, kind) {
if (considerFunctionBodies === void 0) { considerFunctionBodies = true; }
var node = ts.getTokenAtPosition(file, startPosition);
var func = ts.getContainingFunction(node);
if ((!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node) && !considerFunctionBodies)) {
return undefined;
}
- if (ts.isExpression(func.body)) {
- return {
- info: {
- func: func,
- addBraces: true,
- expression: func.body
- }
- };
+ if (refactor.refactorKindBeginsWith(addBracesAction.kind, kind) && ts.isExpression(func.body)) {
+ return { func: func, addBraces: true, expression: func.body };
}
- else if (func.body.statements.length === 1) {
+ else if (refactor.refactorKindBeginsWith(removeBracesAction.kind, kind) && ts.isBlock(func.body) && func.body.statements.length === 1) {
var firstStatement = ts.first(func.body.statements);
if (ts.isReturnStatement(firstStatement)) {
- return {
- info: {
- func: func,
- addBraces: false,
- expression: firstStatement.expression,
- returnStatement: firstStatement
- }
- };
+ return { func: func, addBraces: false, expression: firstStatement.expression, returnStatement: firstStatement };
}
}
return undefined;
(function (convertParamsToDestructuredObject) {
var refactorName = "Convert parameters to destructured object";
var minimumParameterLength = 2;
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ var refactorDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object);
+ var toDestructuredAction = {
+ name: refactorName,
+ description: refactorDescription,
+ kind: "refactor.rewrite.parameters.toDestructured"
+ };
+ refactor.registerRefactor(refactorName, {
+ kinds: [toDestructuredAction.kind],
+ getEditsForAction: getEditsForAction,
+ getAvailableActions: getAvailableActions
+ });
function getAvailableActions(context) {
var file = context.file, startPosition = context.startPosition;
var isJSFile = ts.isSourceFileJS(file);
var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
if (!functionDeclaration)
return ts.emptyArray;
- var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object);
return [{
name: refactorName,
- description: description,
- actions: [{
- name: refactorName,
- description: description
- }]
+ description: refactorDescription,
+ actions: [toDestructuredAction]
}];
}
function getEditsForAction(context, actionName) {
return { edits: [] }; // TODO: GH#30113
}
function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
- var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
- changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
- // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
- indentation: 0,
- leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
- trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
- });
+ var signature = groupedReferences.signature;
+ var newFunctionDeclarationParams = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
+ if (signature) {
+ var newSignatureParams = ts.map(createNewParameters(signature, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
+ replaceParameters(signature, newSignatureParams);
+ }
+ replaceParameters(functionDeclaration, newFunctionDeclarationParams);
var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
var call = functionCalls_1[_i];
changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
}
}
+ function replaceParameters(declarationOrSignature, parameterDeclarations) {
+ changes.replaceNodeRangeWithNodes(sourceFile, ts.first(declarationOrSignature.parameters), ts.last(declarationOrSignature.parameters), parameterDeclarations, {
+ joiner: ", ",
+ // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
+ indentation: 0,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
+ });
+ }
}
function getGroupedReferences(functionDeclaration, program, cancellationToken) {
var functionNames = getFunctionNames(functionDeclaration);
var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
- var names = ts.deduplicate(__spreadArrays(functionNames, classNames), ts.equateValues);
+ var names = ts.deduplicate(__spreadArray(__spreadArray([], functionNames), classNames), ts.equateValues);
var checker = program.getTypeChecker();
var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
var groupedReferences = groupReferences(references);
var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation);
var classSymbols = ts.map(classNames, getSymbolTargetAtLocation);
var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
+ var contextualSymbols = ts.map(functionNames, function (name) { return getSymbolForContextualType(name, checker); });
for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
var entry = referenceEntries_1[_i];
- if (entry.kind !== 1 /* Node */) {
+ if (entry.kind === 0 /* Span */) {
groupedReferences.valid = false;
continue;
}
+ /* Declarations in object literals may be implementations of method signatures which have a different symbol from the declaration
+ For example:
+ interface IFoo { m(a: number): void }
+ const foo: IFoo = { m(a: number): void {} }
+ In these cases we get the symbol for the signature from the contextual type.
+ */
+ if (ts.contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) {
+ if (isValidMethodSignature(entry.node.parent)) {
+ groupedReferences.signature = entry.node.parent;
+ continue;
+ }
+ var call = entryToFunctionCall(entry);
+ if (call) {
+ groupedReferences.functionCalls.push(call);
+ continue;
+ }
+ }
+ var contextualSymbol = getSymbolForContextualType(entry.node, checker);
+ if (contextualSymbol && ts.contains(contextualSymbols, contextualSymbol)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ }
/* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function.
Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test:
class A { foo(a: number, b: number) { return a + b; } }
return symbol && ts.getSymbolTarget(symbol, checker);
}
}
+ /**
+ * Gets the symbol for the contextual type of the node if it is not a union or intersection.
+ */
+ function getSymbolForContextualType(node, checker) {
+ var element = ts.getContainingObjectLiteralElement(node);
+ if (element) {
+ var contextualType = checker.getContextualTypeForObjectLiteralElement(element);
+ var symbol = contextualType === null || contextualType === void 0 ? void 0 : contextualType.getSymbol();
+ if (symbol && !(ts.getCheckFlags(symbol) & 6 /* Synthetic */)) {
+ return symbol;
+ }
+ }
+ }
function entryToImportOrExport(entry) {
var node = entry.node;
if (ts.isImportSpecifier(node.parent)
}
return false;
}
+ function isValidMethodSignature(node) {
+ return ts.isMethodSignature(node) && (ts.isInterfaceDeclaration(node.parent) || ts.isTypeLiteralNode(node.parent));
+ }
function isValidFunctionDeclaration(functionDeclaration, checker) {
if (!isValidParameterNodeArray(functionDeclaration.parameters, checker))
return false;
case 251 /* FunctionDeclaration */:
return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker);
case 165 /* MethodDeclaration */:
+ if (ts.isObjectLiteralExpression(functionDeclaration.parent)) {
+ var contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker);
+ // don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change
+ return (contextualSymbol === null || contextualSymbol === void 0 ? void 0 : contextualSymbol.declarations.length) === 1 && isSingleImplementation(functionDeclaration, checker);
+ }
return isSingleImplementation(functionDeclaration, checker);
case 166 /* Constructor */:
if (ts.isClassDeclaration(functionDeclaration.parent)) {
(function (convertStringOrTemplateLiteral) {
var refactorName = "Convert to template string";
var refactorDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_template_string);
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ var convertStringAction = {
+ name: refactorName,
+ description: refactorDescription,
+ kind: "refactor.rewrite.string"
+ };
+ refactor.registerRefactor(refactorName, {
+ kinds: [convertStringAction.kind],
+ getEditsForAction: getEditsForAction,
+ getAvailableActions: getAvailableActions
+ });
function getAvailableActions(context) {
var file = context.file, startPosition = context.startPosition;
var node = getNodeOrParentOfParentheses(file, startPosition);
var maybeBinary = getParentBinaryExpression(node);
var refactorInfo = { name: refactorName, description: refactorDescription, actions: [] };
if (ts.isBinaryExpression(maybeBinary) && isStringConcatenationValid(maybeBinary)) {
- refactorInfo.actions.push({ name: refactorName, description: refactorDescription });
+ refactorInfo.actions.push(convertStringAction);
+ return [refactorInfo];
+ }
+ else if (context.preferences.provideRefactorNotApplicableReason) {
+ refactorInfo.actions.push(__assign(__assign({}, convertStringAction), { notApplicableReason: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_string_concatenation) }));
return [refactorInfo];
}
return ts.emptyArray;
case 201 /* PropertyAccessExpression */:
case 202 /* ElementAccessExpression */:
return false;
+ case 218 /* TemplateExpression */:
case 216 /* BinaryExpression */:
return !(ts.isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent));
default:
function treeToArray(current) {
if (ts.isBinaryExpression(current)) {
var _a = treeToArray(current.left), nodes = _a.nodes, operators = _a.operators, leftHasString = _a.containsString, leftOperatorValid = _a.areOperatorsValid;
- if (!leftHasString && !ts.isStringLiteral(current.right)) {
+ if (!leftHasString && !ts.isStringLiteral(current.right) && !ts.isTemplateExpression(current.right)) {
return { nodes: [current], operators: [], containsString: false, areOperatorsValid: true };
}
var currentOperatorValid = current.operatorToken.kind === 39 /* PlusToken */;
};
};
function concatConsecutiveString(index, nodes) {
- var text = "";
var indexes = [];
- while (index < nodes.length && ts.isStringLiteral(nodes[index])) {
- var stringNode = nodes[index];
- text = text + stringNode.text;
- indexes.push(index);
- index++;
+ var text = "";
+ while (index < nodes.length) {
+ var node = nodes[index];
+ if (ts.isStringLiteralLike(node)) {
+ text = text + node.text;
+ indexes.push(index);
+ index++;
+ }
+ else if (ts.isTemplateExpression(node)) {
+ text = text + node.head.text;
+ break;
+ }
+ else {
+ break;
+ }
}
return [index, text, indexes];
}
var templateSpans = [];
var templateHead = ts.factory.createTemplateHead(headText);
copyCommentFromStringLiterals(headIndexes, templateHead);
- for (var i = begin; i < nodes.length; i++) {
+ var _loop_19 = function (i) {
var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]);
copyOperatorComments(i, currentNode);
var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], stringIndexes = _c[2];
i = newIndex - 1;
- var templatePart = i === nodes.length - 1 ? ts.factory.createTemplateTail(subsequentText) : ts.factory.createTemplateMiddle(subsequentText);
- copyCommentFromStringLiterals(stringIndexes, templatePart);
- templateSpans.push(ts.factory.createTemplateSpan(currentNode, templatePart));
+ var isLast = i === nodes.length - 1;
+ if (ts.isTemplateExpression(currentNode)) {
+ var spans = ts.map(currentNode.templateSpans, function (span, index) {
+ copyExpressionComments(span);
+ var nextSpan = currentNode.templateSpans[index + 1];
+ var text = span.literal.text + (nextSpan ? "" : subsequentText);
+ return ts.factory.createTemplateSpan(span.expression, isLast ? ts.factory.createTemplateTail(text) : ts.factory.createTemplateMiddle(text));
+ });
+ templateSpans.push.apply(templateSpans, spans);
+ }
+ else {
+ var templatePart = isLast ? ts.factory.createTemplateTail(subsequentText) : ts.factory.createTemplateMiddle(subsequentText);
+ copyCommentFromStringLiterals(stringIndexes, templatePart);
+ templateSpans.push(ts.factory.createTemplateSpan(currentNode, templatePart));
+ }
+ out_i_1 = i;
+ };
+ var out_i_1;
+ for (var i = begin; i < nodes.length; i++) {
+ _loop_19(i);
+ i = out_i_1;
}
return ts.factory.createTemplateExpression(templateHead, templateSpans);
}
// to copy comments following the opening & closing parentheses
// "foo" + ( /* comment */ 5 + 5 ) /* comment */ + "bar"
- function copyCommentsWhenParenthesized(node) {
+ function copyExpressionComments(node) {
var file = node.getSourceFile();
ts.copyTrailingComments(node, node.expression, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
ts.copyTrailingAsLeadingComments(node.expression, node.expression, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
}
function getExpressionFromParenthesesOrExpression(node) {
if (ts.isParenthesizedExpression(node)) {
- copyCommentsWhenParenthesized(node);
+ copyExpressionComments(node);
node = node.expression;
}
return node;
(function (convertArrowFunctionOrFunctionExpression) {
var refactorName = "Convert arrow function or function expression";
var refactorDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_arrow_function_or_function_expression);
- var toAnonymousFunctionActionName = "Convert to anonymous function";
- var toNamedFunctionActionName = "Convert to named function";
- var toArrowFunctionActionName = "Convert to arrow function";
- var toAnonymousFunctionActionDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_anonymous_function);
- var toNamedFunctionActionDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_named_function);
- var toArrowFunctionActionDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_arrow_function);
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ var toAnonymousFunctionAction = {
+ name: "Convert to anonymous function",
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_anonymous_function),
+ kind: "refactor.rewrite.function.anonymous",
+ };
+ var toNamedFunctionAction = {
+ name: "Convert to named function",
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_named_function),
+ kind: "refactor.rewrite.function.named",
+ };
+ var toArrowFunctionAction = {
+ name: "Convert to arrow function",
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_arrow_function),
+ kind: "refactor.rewrite.function.arrow",
+ };
+ refactor.registerRefactor(refactorName, {
+ kinds: [
+ toAnonymousFunctionAction.kind,
+ toNamedFunctionAction.kind,
+ toArrowFunctionAction.kind
+ ],
+ getEditsForAction: getEditsForAction,
+ getAvailableActions: getAvailableActions
+ });
function getAvailableActions(context) {
- var file = context.file, startPosition = context.startPosition, program = context.program;
+ var file = context.file, startPosition = context.startPosition, program = context.program, kind = context.kind;
var info = getFunctionInfo(file, startPosition, program);
if (!info)
return ts.emptyArray;
var selectedVariableDeclaration = info.selectedVariableDeclaration, func = info.func;
var possibleActions = [];
- if (selectedVariableDeclaration || (ts.isArrowFunction(func) && ts.isVariableDeclaration(func.parent))) {
- possibleActions.push({
- name: toNamedFunctionActionName,
- description: toNamedFunctionActionDescription
- });
+ var errors = [];
+ if (refactor.refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) {
+ var error = selectedVariableDeclaration || (ts.isArrowFunction(func) && ts.isVariableDeclaration(func.parent)) ?
+ undefined : ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_convert_to_named_function);
+ if (error) {
+ errors.push(__assign(__assign({}, toNamedFunctionAction), { notApplicableReason: error }));
+ }
+ else {
+ possibleActions.push(toNamedFunctionAction);
+ }
}
- if (!selectedVariableDeclaration && ts.isArrowFunction(func)) {
- possibleActions.push({
- name: toAnonymousFunctionActionName,
- description: toAnonymousFunctionActionDescription
- });
+ if (refactor.refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) {
+ var error = !selectedVariableDeclaration && ts.isArrowFunction(func) ?
+ undefined : ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_convert_to_anonymous_function);
+ if (error) {
+ errors.push(__assign(__assign({}, toAnonymousFunctionAction), { notApplicableReason: error }));
+ }
+ else {
+ possibleActions.push(toAnonymousFunctionAction);
+ }
}
- if (ts.isFunctionExpression(func)) {
- possibleActions.push({
- name: toArrowFunctionActionName,
- description: toArrowFunctionActionDescription
- });
+ if (refactor.refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) {
+ var error = ts.isFunctionExpression(func) ? undefined : ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_convert_to_arrow_function);
+ if (error) {
+ errors.push(__assign(__assign({}, toArrowFunctionAction), { notApplicableReason: error }));
+ }
+ else {
+ possibleActions.push(toArrowFunctionAction);
+ }
}
return [{
name: refactorName,
description: refactorDescription,
- actions: possibleActions
+ actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ?
+ errors : possibleActions
}];
}
function getEditsForAction(context, actionName) {
var func = info.func;
var edits = [];
switch (actionName) {
- case toAnonymousFunctionActionName:
+ case toAnonymousFunctionAction.name:
edits.push.apply(edits, getEditInfoForConvertToAnonymousFunction(context, func));
break;
- case toNamedFunctionActionName:
+ case toNamedFunctionAction.name:
var variableInfo = getVariableInfo(func);
if (!variableInfo)
return undefined;
edits.push.apply(edits, getEditInfoForConvertToNamedFunction(context, func, variableInfo));
break;
- case toArrowFunctionActionName:
+ case toArrowFunctionAction.name:
if (!ts.isFunctionExpression(func))
return undefined;
edits.push.apply(edits, getEditInfoForConvertToArrowFunction(context, func));
}
function getFunctionInfo(file, startPosition, program) {
var token = ts.getTokenAtPosition(file, startPosition);
- var arrowFunc = getArrowFunctionFromVariableDeclaration(token.parent);
- if (arrowFunc && !containingThis(arrowFunc.body))
- return { selectedVariableDeclaration: true, func: arrowFunc };
- var maybeFunc = ts.getContainingFunction(token);
var typeChecker = program.getTypeChecker();
+ var func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent);
+ if (func && !containingThis(func.body)) {
+ return { selectedVariableDeclaration: true, func: func };
+ }
+ var maybeFunc = ts.getContainingFunction(token);
if (maybeFunc &&
(ts.isFunctionExpression(maybeFunc) || ts.isArrowFunction(maybeFunc)) &&
!ts.rangeContainsRange(maybeFunc.body, token) &&
!containingThis(maybeFunc.body)) {
- if ((ts.isFunctionExpression(maybeFunc) && maybeFunc.name && ts.FindAllReferences.Core.isSymbolReferencedInFile(maybeFunc.name, typeChecker, file)))
+ if (ts.isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc))
return undefined;
return { selectedVariableDeclaration: false, func: maybeFunc };
}
function isSingleVariableDeclaration(parent) {
return ts.isVariableDeclaration(parent) || (ts.isVariableDeclarationList(parent) && parent.declarations.length === 1);
}
- function getArrowFunctionFromVariableDeclaration(parent) {
- if (!isSingleVariableDeclaration(parent))
+ function tryGetFunctionFromVariableDeclaration(sourceFile, typeChecker, parent) {
+ if (!isSingleVariableDeclaration(parent)) {
return undefined;
- var variableDeclaration = ts.isVariableDeclaration(parent) ? parent : parent.declarations[0];
+ }
+ var variableDeclaration = ts.isVariableDeclaration(parent) ? parent : ts.first(parent.declarations);
var initializer = variableDeclaration.initializer;
- if (!initializer || !ts.isArrowFunction(initializer))
- return undefined;
- return initializer;
+ if (initializer && (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer) && !isFunctionReferencedInFile(sourceFile, typeChecker, initializer))) {
+ return initializer;
+ }
+ return undefined;
}
function convertToBlock(body) {
if (ts.isExpression(body)) {
function canBeConvertedToExpression(body, head) {
return body.statements.length === 1 && ((ts.isReturnStatement(head) && !!head.expression));
}
+ function isFunctionReferencedInFile(sourceFile, typeChecker, node) {
+ return !!node.name && ts.FindAllReferences.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile);
+ }
})(convertArrowFunctionOrFunctionExpression = refactor.convertArrowFunctionOrFunctionExpression || (refactor.convertArrowFunctionOrFunctionExpression = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var inferFunctionReturnType;
+ (function (inferFunctionReturnType) {
+ var refactorName = "Infer function return type";
+ var refactorDescription = ts.Diagnostics.Infer_function_return_type.message;
+ var inferReturnTypeAction = {
+ name: refactorName,
+ description: refactorDescription,
+ kind: "refactor.rewrite.function.returnType"
+ };
+ refactor.registerRefactor(refactorName, {
+ kinds: [inferReturnTypeAction.kind],
+ getEditsForAction: getEditsForAction,
+ getAvailableActions: getAvailableActions
+ });
+ function getEditsForAction(context) {
+ var info = getInfo(context);
+ if (info && !refactor.isRefactorErrorInfo(info)) {
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) {
+ return t.tryInsertTypeAnnotation(context.file, info.declaration, info.returnTypeNode);
+ });
+ return { renameFilename: undefined, renameLocation: undefined, edits: edits };
+ }
+ return undefined;
+ }
+ function getAvailableActions(context) {
+ var info = getInfo(context);
+ if (!info)
+ return ts.emptyArray;
+ if (!refactor.isRefactorErrorInfo(info)) {
+ return [{
+ name: refactorName,
+ description: refactorDescription,
+ actions: [inferReturnTypeAction]
+ }];
+ }
+ if (context.preferences.provideRefactorNotApplicableReason) {
+ return [{
+ name: refactorName,
+ description: refactorDescription,
+ actions: [__assign(__assign({}, inferReturnTypeAction), { notApplicableReason: info.error })]
+ }];
+ }
+ return ts.emptyArray;
+ }
+ function getInfo(context) {
+ if (ts.isInJSFile(context.file) || !refactor.refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind))
+ return;
+ var token = ts.getTokenAtPosition(context.file, context.startPosition);
+ var declaration = ts.findAncestor(token, isConvertibleDeclaration);
+ if (!declaration || !declaration.body || declaration.type) {
+ return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Return_type_must_be_inferred_from_a_function) };
+ }
+ var typeChecker = context.program.getTypeChecker();
+ var returnType = tryGetReturnType(typeChecker, declaration);
+ if (!returnType) {
+ return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_determine_function_return_type) };
+ }
+ ;
+ var returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */);
+ if (returnTypeNode) {
+ return { declaration: declaration, returnTypeNode: returnTypeNode };
+ }
+ }
+ function isConvertibleDeclaration(node) {
+ switch (node.kind) {
+ case 251 /* FunctionDeclaration */:
+ case 208 /* FunctionExpression */:
+ case 209 /* ArrowFunction */:
+ case 165 /* MethodDeclaration */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ function tryGetReturnType(typeChecker, node) {
+ if (typeChecker.isImplementationOfOverload(node)) {
+ var signatures = typeChecker.getTypeAtLocation(node).getCallSignatures();
+ if (signatures.length > 1) {
+ return typeChecker.getUnionType(ts.mapDefined(signatures, function (s) { return s.getReturnType(); }));
+ }
+ }
+ var signature = typeChecker.getSignatureFromDeclaration(node);
+ if (signature) {
+ return typeChecker.getReturnTypeOfSignature(signature);
+ }
+ }
+ })(inferFunctionReturnType = refactor.inferFunctionReturnType || (refactor.inferFunctionReturnType = {}));
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
var ts;
(function (ts) {
/** The version of the language service API */
};
SignatureObject.prototype.getJsDocTags = function () {
if (this.jsDocTags === undefined) {
- this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : [];
+ this.jsDocTags = this.declaration ? getJsDocTags([this.declaration], this.checker) : [];
}
return this.jsDocTags;
};
function hasJSDocInheritDocTag(node) {
return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; });
}
+ function getJsDocTags(declarations, checker) {
+ var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations);
+ if (tags.length === 0 || declarations.some(hasJSDocInheritDocTag)) {
+ ts.forEachUnique(declarations, function (declaration) {
+ var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { return symbol.getJsDocTags(); });
+ if (inheritedTags) {
+ tags = __spreadArray(__spreadArray([], inheritedTags), tags);
+ }
+ });
+ }
+ return tags;
+ }
function getDocumentationComment(declarations, checker) {
if (!declarations)
return ts.emptyArray;
var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations);
- if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) {
+ if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) {
ts.forEachUnique(declarations, function (declaration) {
- var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217
+ var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { return symbol.getDocumentationComment(checker); });
// TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs
if (inheritedDocs)
doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc);
}
return doc;
}
- /**
- * Attempts to find JSDoc comments for possibly-inherited properties. Checks superclasses then traverses
- * implemented interfaces until a symbol is found with the same name and with documentation.
- * @param declaration The possibly-inherited declaration to find comments for.
- * @param propertyName The name of the possibly-inherited property.
- * @param typeChecker A TypeChecker, used to find inherited properties.
- * @returns A filled array of documentation comments if any were found, otherwise an empty array.
- */
- function findInheritedJSDocComments(declaration, propertyName, typeChecker) {
+ function findBaseOfDeclaration(checker, declaration, cb) {
return ts.firstDefined(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) {
- var superType = typeChecker.getTypeAtLocation(superTypeNode);
- var baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName);
- var inheritedDocs = baseProperty && baseProperty.getDocumentationComment(typeChecker);
- return inheritedDocs && inheritedDocs.length ? inheritedDocs : undefined;
+ var symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name);
+ return symbol ? cb(symbol) : undefined;
});
}
var SourceFileObject = /** @class */ (function (_super) {
return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind);
}
ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile;
+ var NoopCancellationToken = {
+ isCancellationRequested: ts.returnFalse,
+ throwIfCancellationRequested: ts.noop,
+ };
var CancellationTokenObject = /** @class */ (function () {
function CancellationTokenObject(cancellationToken) {
this.cancellationToken = cancellationToken;
}
CancellationTokenObject.prototype.isCancellationRequested = function () {
- return !!this.cancellationToken && this.cancellationToken.isCancellationRequested();
+ return this.cancellationToken.isCancellationRequested();
};
CancellationTokenObject.prototype.throwIfCancellationRequested = function () {
if (this.isCancellationRequested()) {
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" });
throw new ts.OperationCanceledException();
}
};
};
ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () {
if (this.isCancellationRequested()) {
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" });
throw new ts.OperationCanceledException();
}
};
"provideCallHierarchyIncomingCalls",
"provideCallHierarchyOutgoingCalls",
];
- var invalidOperationsInSyntacticMode = __spreadArrays(invalidOperationsInPartialSemanticMode, [
+ var invalidOperationsInSyntacticMode = __spreadArray(__spreadArray([], invalidOperationsInPartialSemanticMode), [
"getCompletionsAtPosition",
"getCompletionEntryDetails",
"getCompletionEntrySymbol",
var program;
var lastProjectVersion;
var lastTypesRootVersion = 0;
- var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken());
+ var cancellationToken = host.getCancellationToken
+ ? new CancellationTokenObject(host.getCancellationToken())
+ : NoopCancellationToken;
var currentDirectory = host.getCurrentDirectory();
// Check if the localized messages json is set, otherwise query the host for it
if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) {
}
// If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface
var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
- return __spreadArrays(semanticDiagnostics, declarationDiagnostics);
+ return __spreadArray(__spreadArray([], semanticDiagnostics), declarationDiagnostics);
}
function getSuggestionDiagnostics(fileName) {
synchronizeHostData();
}
function getCompilerOptionsDiagnostics() {
synchronizeHostData();
- return __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken));
+ return __spreadArray(__spreadArray([], program.getOptionsDiagnostics(cancellationToken)), program.getGlobalDiagnostics(cancellationToken));
}
function getCompletionsAtPosition(fileName, position, options) {
if (options === void 0) { options = ts.emptyOptions; }
}), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags;
return {
kind: symbolKind,
- kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
+ kindModifiers: ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol),
textSpan: ts.createTextSpanFromNode(nodeForQuickInfo, sourceFile),
displayParts: displayParts,
documentation: documentation,
synchronizeHostData();
return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
}
+ function getFileReferences(fileName) {
+ synchronizeHostData();
+ return ts.FindAllReferences.Core.getReferencesForFileName(fileName, program, program.getSourceFiles()).map(ts.FindAllReferences.toReferenceEntry);
+ }
function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) {
if (excludeDtsFiles === void 0) { excludeDtsFiles = false; }
synchronizeHostData();
? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName })
: Promise.reject("Host does not implement `installPackage`");
}
- function getDocCommentTemplateAtPosition(fileName, position) {
- return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position);
+ function getDocCommentTemplateAtPosition(fileName, position, options) {
+ return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position, options);
}
function isValidBraceCompletionAtPosition(fileName, position, openingBrace) {
// '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too
synchronizeHostData();
return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options);
}
- function getRefactorContext(file, positionOrRange, preferences, formatOptions, triggerReason) {
+ function getRefactorContext(file, positionOrRange, preferences, formatOptions, triggerReason, kind) {
var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1];
return {
file: file,
cancellationToken: cancellationToken,
preferences: preferences,
triggerReason: triggerReason,
+ kind: kind
};
}
function getSmartSelectionRange(fileName, position) {
return ts.SmartSelectionRange.getSmartSelectionRange(position, syntaxTreeCache.getCurrentSourceFile(fileName));
}
- function getApplicableRefactors(fileName, positionOrRange, preferences, triggerReason) {
+ function getApplicableRefactors(fileName, positionOrRange, preferences, triggerReason, kind) {
if (preferences === void 0) { preferences = ts.emptyOptions; }
synchronizeHostData();
var file = getValidSourceFile(fileName);
- return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, ts.emptyOptions, triggerReason));
+ return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, ts.emptyOptions, triggerReason, kind));
}
function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) {
if (preferences === void 0) { preferences = ts.emptyOptions; }
getTypeDefinitionAtPosition: getTypeDefinitionAtPosition,
getReferencesAtPosition: getReferencesAtPosition,
findReferences: findReferences,
+ getFileReferences: getFileReferences,
getOccurrencesAtPosition: getOccurrencesAtPosition,
getDocumentHighlights: getDocumentHighlights,
getNameOrDottedNameSpan: getNameOrDottedNameSpan,
var symbol = contextualType.getProperty(name);
return symbol ? [symbol] : ts.emptyArray;
}
- var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); });
+ var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return (ts.isObjectLiteralExpression(node.parent) || ts.isJsxAttributes(node.parent)) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); });
if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) {
var symbol = contextualType.getProperty(name);
if (symbol)
var _this = this;
return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); });
};
+ LanguageServiceShimObject.prototype.getFileReferences = function (fileName) {
+ var _this = this;
+ return this.forwardJSONCall("getFileReferences('" + fileName + ")", function () { return _this.languageService.getFileReferences(fileName); });
+ };
LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) {
var _this = this;
return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); });
return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
});
};
- LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) {
+ LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position, options) {
var _this = this;
- return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); });
+ return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position, options); });
};
/// NAVIGATE TO
/** Return a list of symbols that are interesting to navigate to */
typeAcquisition: configFile.typeAcquisition,
files: configFile.fileNames,
raw: configFile.raw,
- errors: realizeDiagnostics(__spreadArrays(result.parseDiagnostics, configFile.errors), "\r\n")
+ errors: realizeDiagnostics(__spreadArray(__spreadArray([], result.parseDiagnostics), configFile.errors), "\r\n")
};
});
};
/** @deprecated Use `factory.updateFunctionTypeNode` or the factory supplied by your transformation context instead. */
ts.updateFunctionTypeNode = ts.Debug.deprecate(ts.factory.updateFunctionTypeNode, factoryDeprecation);
/** @deprecated Use `factory.createConstructorTypeNode` or the factory supplied by your transformation context instead. */
- ts.createConstructorTypeNode = ts.Debug.deprecate(ts.factory.createConstructorTypeNode, factoryDeprecation);
+ ts.createConstructorTypeNode = ts.Debug.deprecate(function (typeParameters, parameters, type) {
+ return ts.factory.createConstructorTypeNode(/*modifiers*/ undefined, typeParameters, parameters, type);
+ }, factoryDeprecation);
/** @deprecated Use `factory.updateConstructorTypeNode` or the factory supplied by your transformation context instead. */
- ts.updateConstructorTypeNode = ts.Debug.deprecate(ts.factory.updateConstructorTypeNode, factoryDeprecation);
+ ts.updateConstructorTypeNode = ts.Debug.deprecate(function (node, typeParameters, parameters, type) {
+ return ts.factory.updateConstructorTypeNode(node, node.modifiers, typeParameters, parameters, type);
+ }, factoryDeprecation);
/** @deprecated Use `factory.createTypeQueryNode` or the factory supplied by your transformation context instead. */
ts.createTypeQueryNode = ts.Debug.deprecate(ts.factory.createTypeQueryNode, factoryDeprecation);
/** @deprecated Use `factory.updateTypeQueryNode` or the factory supplied by your transformation context instead. */
ts.createBindingElement = ts.Debug.deprecate(ts.factory.createBindingElement, factoryDeprecation);
/** @deprecated Use `factory.updateBindingElement` or the factory supplied by your transformation context instead. */
ts.updateBindingElement = ts.Debug.deprecate(ts.factory.updateBindingElement, factoryDeprecation);
- /** @deprecated Use `factory.createArrayLiteral` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createArrayLiteralExpression` or the factory supplied by your transformation context instead. */
ts.createArrayLiteral = ts.Debug.deprecate(ts.factory.createArrayLiteralExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateArrayLiteral` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateArrayLiteralExpression` or the factory supplied by your transformation context instead. */
ts.updateArrayLiteral = ts.Debug.deprecate(ts.factory.updateArrayLiteralExpression, factoryDeprecation);
- /** @deprecated Use `factory.createObjectLiteral` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createObjectLiteralExpression` or the factory supplied by your transformation context instead. */
ts.createObjectLiteral = ts.Debug.deprecate(ts.factory.createObjectLiteralExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateObjectLiteral` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateObjectLiteralExpression` or the factory supplied by your transformation context instead. */
ts.updateObjectLiteral = ts.Debug.deprecate(ts.factory.updateObjectLiteralExpression, factoryDeprecation);
- /** @deprecated Use `factory.createPropertyAccess` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createPropertyAccessExpression` or the factory supplied by your transformation context instead. */
ts.createPropertyAccess = ts.Debug.deprecate(ts.factory.createPropertyAccessExpression, factoryDeprecation);
- /** @deprecated Use `factory.updatePropertyAccess` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updatePropertyAccessExpression` or the factory supplied by your transformation context instead. */
ts.updatePropertyAccess = ts.Debug.deprecate(ts.factory.updatePropertyAccessExpression, factoryDeprecation);
/** @deprecated Use `factory.createPropertyAccessChain` or the factory supplied by your transformation context instead. */
ts.createPropertyAccessChain = ts.Debug.deprecate(ts.factory.createPropertyAccessChain, factoryDeprecation);
/** @deprecated Use `factory.updatePropertyAccessChain` or the factory supplied by your transformation context instead. */
ts.updatePropertyAccessChain = ts.Debug.deprecate(ts.factory.updatePropertyAccessChain, factoryDeprecation);
- /** @deprecated Use `factory.createElementAccess` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createElementAccessExpression` or the factory supplied by your transformation context instead. */
ts.createElementAccess = ts.Debug.deprecate(ts.factory.createElementAccessExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateElementAccess` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateElementAccessExpression` or the factory supplied by your transformation context instead. */
ts.updateElementAccess = ts.Debug.deprecate(ts.factory.updateElementAccessExpression, factoryDeprecation);
/** @deprecated Use `factory.createElementAccessChain` or the factory supplied by your transformation context instead. */
ts.createElementAccessChain = ts.Debug.deprecate(ts.factory.createElementAccessChain, factoryDeprecation);
/** @deprecated Use `factory.updateElementAccessChain` or the factory supplied by your transformation context instead. */
ts.updateElementAccessChain = ts.Debug.deprecate(ts.factory.updateElementAccessChain, factoryDeprecation);
- /** @deprecated Use `factory.createCall` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createCallExpression` or the factory supplied by your transformation context instead. */
ts.createCall = ts.Debug.deprecate(ts.factory.createCallExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateCall` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateCallExpression` or the factory supplied by your transformation context instead. */
ts.updateCall = ts.Debug.deprecate(ts.factory.updateCallExpression, factoryDeprecation);
/** @deprecated Use `factory.createCallChain` or the factory supplied by your transformation context instead. */
ts.createCallChain = ts.Debug.deprecate(ts.factory.createCallChain, factoryDeprecation);
/** @deprecated Use `factory.updateCallChain` or the factory supplied by your transformation context instead. */
ts.updateCallChain = ts.Debug.deprecate(ts.factory.updateCallChain, factoryDeprecation);
- /** @deprecated Use `factory.createNew` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createNewExpression` or the factory supplied by your transformation context instead. */
ts.createNew = ts.Debug.deprecate(ts.factory.createNewExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateNew` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateNewExpression` or the factory supplied by your transformation context instead. */
ts.updateNew = ts.Debug.deprecate(ts.factory.updateNewExpression, factoryDeprecation);
/** @deprecated Use `factory.createTypeAssertion` or the factory supplied by your transformation context instead. */
ts.createTypeAssertion = ts.Debug.deprecate(ts.factory.createTypeAssertion, factoryDeprecation);
/** @deprecated Use `factory.updateTypeAssertion` or the factory supplied by your transformation context instead. */
ts.updateTypeAssertion = ts.Debug.deprecate(ts.factory.updateTypeAssertion, factoryDeprecation);
- /** @deprecated Use `factory.createParen` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createParenthesizedExpression` or the factory supplied by your transformation context instead. */
ts.createParen = ts.Debug.deprecate(ts.factory.createParenthesizedExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateParen` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateParenthesizedExpression` or the factory supplied by your transformation context instead. */
ts.updateParen = ts.Debug.deprecate(ts.factory.updateParenthesizedExpression, factoryDeprecation);
/** @deprecated Use `factory.createFunctionExpression` or the factory supplied by your transformation context instead. */
ts.createFunctionExpression = ts.Debug.deprecate(ts.factory.createFunctionExpression, factoryDeprecation);
/** @deprecated Use `factory.updateFunctionExpression` or the factory supplied by your transformation context instead. */
ts.updateFunctionExpression = ts.Debug.deprecate(ts.factory.updateFunctionExpression, factoryDeprecation);
- /** @deprecated Use `factory.createDelete` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createDeleteExpression` or the factory supplied by your transformation context instead. */
ts.createDelete = ts.Debug.deprecate(ts.factory.createDeleteExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateDelete` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateDeleteExpression` or the factory supplied by your transformation context instead. */
ts.updateDelete = ts.Debug.deprecate(ts.factory.updateDeleteExpression, factoryDeprecation);
- /** @deprecated Use `factory.createTypeOf` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createTypeOfExpression` or the factory supplied by your transformation context instead. */
ts.createTypeOf = ts.Debug.deprecate(ts.factory.createTypeOfExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateTypeOf` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateTypeOfExpression` or the factory supplied by your transformation context instead. */
ts.updateTypeOf = ts.Debug.deprecate(ts.factory.updateTypeOfExpression, factoryDeprecation);
- /** @deprecated Use `factory.createVoid` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createVoidExpression` or the factory supplied by your transformation context instead. */
ts.createVoid = ts.Debug.deprecate(ts.factory.createVoidExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateVoid` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateVoidExpression` or the factory supplied by your transformation context instead. */
ts.updateVoid = ts.Debug.deprecate(ts.factory.updateVoidExpression, factoryDeprecation);
- /** @deprecated Use `factory.createAwait` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createAwaitExpression` or the factory supplied by your transformation context instead. */
ts.createAwait = ts.Debug.deprecate(ts.factory.createAwaitExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateAwait` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateAwaitExpression` or the factory supplied by your transformation context instead. */
ts.updateAwait = ts.Debug.deprecate(ts.factory.updateAwaitExpression, factoryDeprecation);
- /** @deprecated Use `factory.createPrefix` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createPrefixExpression` or the factory supplied by your transformation context instead. */
ts.createPrefix = ts.Debug.deprecate(ts.factory.createPrefixUnaryExpression, factoryDeprecation);
- /** @deprecated Use `factory.updatePrefix` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updatePrefixExpression` or the factory supplied by your transformation context instead. */
ts.updatePrefix = ts.Debug.deprecate(ts.factory.updatePrefixUnaryExpression, factoryDeprecation);
- /** @deprecated Use `factory.createPostfix` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createPostfixUnaryExpression` or the factory supplied by your transformation context instead. */
ts.createPostfix = ts.Debug.deprecate(ts.factory.createPostfixUnaryExpression, factoryDeprecation);
- /** @deprecated Use `factory.updatePostfix` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updatePostfixUnaryExpression` or the factory supplied by your transformation context instead. */
ts.updatePostfix = ts.Debug.deprecate(ts.factory.updatePostfixUnaryExpression, factoryDeprecation);
- /** @deprecated Use `factory.createBinary` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createBinaryExpression` or the factory supplied by your transformation context instead. */
ts.createBinary = ts.Debug.deprecate(ts.factory.createBinaryExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateConditional` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateConditionalExpression` or the factory supplied by your transformation context instead. */
ts.updateConditional = ts.Debug.deprecate(ts.factory.updateConditionalExpression, factoryDeprecation);
/** @deprecated Use `factory.createTemplateExpression` or the factory supplied by your transformation context instead. */
ts.createTemplateExpression = ts.Debug.deprecate(ts.factory.createTemplateExpression, factoryDeprecation);
ts.createTemplateTail = ts.Debug.deprecate(ts.factory.createTemplateTail, factoryDeprecation);
/** @deprecated Use `factory.createNoSubstitutionTemplateLiteral` or the factory supplied by your transformation context instead. */
ts.createNoSubstitutionTemplateLiteral = ts.Debug.deprecate(ts.factory.createNoSubstitutionTemplateLiteral, factoryDeprecation);
- /** @deprecated Use `factory.updateYield` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateYieldExpression` or the factory supplied by your transformation context instead. */
ts.updateYield = ts.Debug.deprecate(ts.factory.updateYieldExpression, factoryDeprecation);
- /** @deprecated Use `factory.createSpread` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createSpreadExpression` or the factory supplied by your transformation context instead. */
ts.createSpread = ts.Debug.deprecate(ts.factory.createSpreadElement, factoryDeprecation);
- /** @deprecated Use `factory.updateSpread` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateSpreadExpression` or the factory supplied by your transformation context instead. */
ts.updateSpread = ts.Debug.deprecate(ts.factory.updateSpreadElement, factoryDeprecation);
/** @deprecated Use `factory.createOmittedExpression` or the factory supplied by your transformation context instead. */
ts.createOmittedExpression = ts.Debug.deprecate(ts.factory.createOmittedExpression, factoryDeprecation);
ts.createStatement = ts.Debug.deprecate(ts.factory.createExpressionStatement, factoryDeprecation);
/** @deprecated Use `factory.updateExpressionStatement` or the factory supplied by your transformation context instead. */
ts.updateStatement = ts.Debug.deprecate(ts.factory.updateExpressionStatement, factoryDeprecation);
- /** @deprecated Use `factory.createIf` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createIfStatement` or the factory supplied by your transformation context instead. */
ts.createIf = ts.Debug.deprecate(ts.factory.createIfStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateIf` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateIfStatement` or the factory supplied by your transformation context instead. */
ts.updateIf = ts.Debug.deprecate(ts.factory.updateIfStatement, factoryDeprecation);
- /** @deprecated Use `factory.createDo` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createDoStatement` or the factory supplied by your transformation context instead. */
ts.createDo = ts.Debug.deprecate(ts.factory.createDoStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateDo` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateDoStatement` or the factory supplied by your transformation context instead. */
ts.updateDo = ts.Debug.deprecate(ts.factory.updateDoStatement, factoryDeprecation);
- /** @deprecated Use `factory.createWhile` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createWhileStatement` or the factory supplied by your transformation context instead. */
ts.createWhile = ts.Debug.deprecate(ts.factory.createWhileStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateWhile` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateWhileStatement` or the factory supplied by your transformation context instead. */
ts.updateWhile = ts.Debug.deprecate(ts.factory.updateWhileStatement, factoryDeprecation);
- /** @deprecated Use `factory.createFor` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createForStatement` or the factory supplied by your transformation context instead. */
ts.createFor = ts.Debug.deprecate(ts.factory.createForStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateFor` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateForStatement` or the factory supplied by your transformation context instead. */
ts.updateFor = ts.Debug.deprecate(ts.factory.updateForStatement, factoryDeprecation);
- /** @deprecated Use `factory.createForIn` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createForInStatement` or the factory supplied by your transformation context instead. */
ts.createForIn = ts.Debug.deprecate(ts.factory.createForInStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateForIn` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateForInStatement` or the factory supplied by your transformation context instead. */
ts.updateForIn = ts.Debug.deprecate(ts.factory.updateForInStatement, factoryDeprecation);
- /** @deprecated Use `factory.createForOf` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createForOfStatement` or the factory supplied by your transformation context instead. */
ts.createForOf = ts.Debug.deprecate(ts.factory.createForOfStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateForOf` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateForOfStatement` or the factory supplied by your transformation context instead. */
ts.updateForOf = ts.Debug.deprecate(ts.factory.updateForOfStatement, factoryDeprecation);
- /** @deprecated Use `factory.createContinue` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createContinueStatement` or the factory supplied by your transformation context instead. */
ts.createContinue = ts.Debug.deprecate(ts.factory.createContinueStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateContinue` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateContinueStatement` or the factory supplied by your transformation context instead. */
ts.updateContinue = ts.Debug.deprecate(ts.factory.updateContinueStatement, factoryDeprecation);
- /** @deprecated Use `factory.createBreak` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createBreakStatement` or the factory supplied by your transformation context instead. */
ts.createBreak = ts.Debug.deprecate(ts.factory.createBreakStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateBreak` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateBreakStatement` or the factory supplied by your transformation context instead. */
ts.updateBreak = ts.Debug.deprecate(ts.factory.updateBreakStatement, factoryDeprecation);
- /** @deprecated Use `factory.createReturn` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createReturnStatement` or the factory supplied by your transformation context instead. */
ts.createReturn = ts.Debug.deprecate(ts.factory.createReturnStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateReturn` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateReturnStatement` or the factory supplied by your transformation context instead. */
ts.updateReturn = ts.Debug.deprecate(ts.factory.updateReturnStatement, factoryDeprecation);
- /** @deprecated Use `factory.createWith` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createWithStatement` or the factory supplied by your transformation context instead. */
ts.createWith = ts.Debug.deprecate(ts.factory.createWithStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateWith` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateWithStatement` or the factory supplied by your transformation context instead. */
ts.updateWith = ts.Debug.deprecate(ts.factory.updateWithStatement, factoryDeprecation);
- /** @deprecated Use `factory.createSwitch` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createSwitchStatement` or the factory supplied by your transformation context instead. */
ts.createSwitch = ts.Debug.deprecate(ts.factory.createSwitchStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateSwitch` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateSwitchStatement` or the factory supplied by your transformation context instead. */
ts.updateSwitch = ts.Debug.deprecate(ts.factory.updateSwitchStatement, factoryDeprecation);
- /** @deprecated Use `factory.createLabel` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createLabelStatement` or the factory supplied by your transformation context instead. */
ts.createLabel = ts.Debug.deprecate(ts.factory.createLabeledStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateLabel` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateLabelStatement` or the factory supplied by your transformation context instead. */
ts.updateLabel = ts.Debug.deprecate(ts.factory.updateLabeledStatement, factoryDeprecation);
- /** @deprecated Use `factory.createThrow` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createThrowStatement` or the factory supplied by your transformation context instead. */
ts.createThrow = ts.Debug.deprecate(ts.factory.createThrowStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateThrow` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateThrowStatement` or the factory supplied by your transformation context instead. */
ts.updateThrow = ts.Debug.deprecate(ts.factory.updateThrowStatement, factoryDeprecation);
- /** @deprecated Use `factory.createTry` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createTryStatement` or the factory supplied by your transformation context instead. */
ts.createTry = ts.Debug.deprecate(ts.factory.createTryStatement, factoryDeprecation);
- /** @deprecated Use `factory.updateTry` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateTryStatement` or the factory supplied by your transformation context instead. */
ts.updateTry = ts.Debug.deprecate(ts.factory.updateTryStatement, factoryDeprecation);
/** @deprecated Use `factory.createDebuggerStatement` or the factory supplied by your transformation context instead. */
ts.createDebuggerStatement = ts.Debug.deprecate(ts.factory.createDebuggerStatement, factoryDeprecation);
ts.createPartiallyEmittedExpression = ts.Debug.deprecate(ts.factory.createPartiallyEmittedExpression, factoryDeprecation);
/** @deprecated Use `factory.updatePartiallyEmittedExpression` or the factory supplied by your transformation context instead. */
ts.updatePartiallyEmittedExpression = ts.Debug.deprecate(ts.factory.updatePartiallyEmittedExpression, factoryDeprecation);
- /** @deprecated Use `factory.createCommaList` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.createCommaListExpression` or the factory supplied by your transformation context instead. */
ts.createCommaList = ts.Debug.deprecate(ts.factory.createCommaListExpression, factoryDeprecation);
- /** @deprecated Use `factory.updateCommaList` or the factory supplied by your transformation context instead. */
+ /** @deprecated Use `factory.updateCommaListExpression` or the factory supplied by your transformation context instead. */
ts.updateCommaList = ts.Debug.deprecate(ts.factory.updateCommaListExpression, factoryDeprecation);
/** @deprecated Use `factory.createBundle` or the factory supplied by your transformation context instead. */
ts.createBundle = ts.Debug.deprecate(ts.factory.createBundle, factoryDeprecation);
* NOTE: It is unsafe to change any properties of a `Node` that relate to its AST children, as those changes won't be
* captured with respect to transformations.
*
- * @deprecated Use `factory.cloneNode` instead and use `setCommentRange` or `setSourceMapRange` and avoid setting `parent`.
+ * @deprecated Use an appropriate `factory.update...` method instead, use `setCommentRange` or `setSourceMapRange`, and avoid setting `parent`.
*/
ts.getMutableClone = ts.Debug.deprecate(function getMutableClone(node) {
var clone = ts.factory.cloneNode(node);
ts.setTextRange(clone, node);
ts.setParent(clone, node.parent);
return clone;
- }, { since: "4.0", warnAfter: "4.1", message: "Use `factory.cloneNode` instead and use `setCommentRange` or `setSourceMapRange` and avoid setting `parent`." });
+ }, { since: "4.0", warnAfter: "4.1", message: "Use an appropriate `factory.update...` method instead, use `setCommentRange` or `setSourceMapRange`, and avoid setting `parent`." });
// #endregion Node Factory top-level exports
// DEPRECATION: Renamed node tests
// DEPRECATION PLAN: